【m】插件上传

This commit is contained in:
2026-04-28 16:48:04 +08:00
parent 459db5ec01
commit 753878bdbb
631 changed files with 91583 additions and 11 deletions

View File

@@ -0,0 +1,419 @@
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.EnhancedTouch;
using EnhancedTouch = UnityEngine.InputSystem.EnhancedTouch.Touch;
using Gyroscope = UnityEngine.InputSystem.Gyroscope;
#if URS_USE_AR_SUBSYSTEMS
using UnityEngine.XR.ARSubsystems;
#endif
namespace Unity.RenderStreaming.Samples
{
using UnityInputSystem = UnityEngine.InputSystem.InputSystem;
static class TouchScreenExtension
{
public static IEnumerable<EnhancedTouch> GetTouches(this Touchscreen screen)
{
return EnhancedTouch.activeTouches.Where(touch => touch.screen == screen);
}
}
[RequireComponent(typeof(InputChannelReceiverBase))]
class SimpleCameraController : MonoBehaviour
{
class CameraState
{
public float yaw;
public float pitch;
public float roll;
public float x;
public float y;
public float z;
public void SetFromTransform(Transform t)
{
pitch = t.eulerAngles.x;
yaw = t.eulerAngles.y;
roll = t.eulerAngles.z;
x = t.position.x;
y = t.position.y;
z = t.position.z;
}
public void Translate(Vector3 translation)
{
Vector3 rotatedTranslation = Quaternion.Euler(pitch, yaw, roll) * translation;
x += rotatedTranslation.x;
y += rotatedTranslation.y;
z += rotatedTranslation.z;
}
public void LerpTowards(CameraState target, float positionLerpPct, float rotationLerpPct)
{
yaw = Mathf.Lerp(yaw, target.yaw, rotationLerpPct);
pitch = Mathf.Lerp(pitch, target.pitch, rotationLerpPct);
roll = Mathf.Lerp(roll, target.roll, rotationLerpPct);
x = Mathf.Lerp(x, target.x, positionLerpPct);
y = Mathf.Lerp(y, target.y, positionLerpPct);
z = Mathf.Lerp(z, target.z, positionLerpPct);
}
public void UpdateTransform(Transform t)
{
t.eulerAngles = new Vector3(pitch, yaw, roll);
t.position = new Vector3(x, y, z);
}
}
[Header("Movement Settings")]
[Tooltip("Movement Sensitivity Factor."), Range(0.001f, 1f)]
[SerializeField] float m_movementSensitivityFactor = 0.1f;
[Tooltip("Exponential boost factor on translation, controllable by mouse wheel.")]
[SerializeField]
private float boost = 3.5f;
[Tooltip("Time it takes to interpolate camera position 99% of the way to the target."), Range(0.001f, 1f)]
[SerializeField]
private float positionLerpTime = 0.2f;
[Header("Rotation Settings")]
[Tooltip("X = Change in mouse position.\nY = Multiplicative factor for camera rotation.")]
[SerializeField]
private AnimationCurve mouseSensitivityCurve = new AnimationCurve(new Keyframe(0f, 0.5f, 0f, 5f), new Keyframe(1f, 2.5f, 0f, 0f));
[Tooltip("Time it takes to interpolate camera rotation 99% of the way to the target."), Range(0.001f, 1f)]
[SerializeField]
private float rotationLerpTime = 0.01f;
[Tooltip("Whether or not to invert our Y axis for mouse input to rotation.")]
[SerializeField]
private bool invertY = false;
[Tooltip("Instance for controlling UI that renders to the camera.")]
[SerializeField]
private UIController uiController = null;
[SerializeField] private InputChannelReceiverBase receiver;
readonly CameraState m_TargetCameraState = new CameraState();
readonly CameraState m_InterpolatingCameraState = new CameraState();
readonly CameraState m_InitialCameraState = new CameraState();
private List<Gamepad> listGamepad = new List<Gamepad>();
private List<Keyboard> listKeyboard = new List<Keyboard>();
private List<Mouse> listMouse = new List<Mouse>();
private List<Gyroscope> listGyroscpe = new List<Gyroscope>();
private List<TrackedDevice> listTracker = new List<TrackedDevice>();
private List<Touchscreen> listScreen = new List<Touchscreen>();
#if URS_USE_AR_SUBSYSTEMS
private List<HandheldARInputDevice> listHandheld = new List<HandheldARInputDevice>();
#endif
void Awake()
{
if (receiver == null)
receiver = GetComponent<InputChannelReceiverBase>();
receiver.onDeviceChange += OnDeviceChange;
EnhancedTouchSupport.Enable();
}
void OnDeviceChange(InputDevice device, InputDeviceChange change)
{
switch (change)
{
case InputDeviceChange.Added:
SetDevice(device);
return;
case InputDeviceChange.Removed:
SetDevice(device, false);
return;
}
}
void SetDevice(InputDevice device, bool add = true)
{
uiController?.SetDevice(device, add);
switch (device)
{
case Mouse mouse:
if (add)
listMouse.Add(mouse);
else
listMouse.Remove(mouse);
return;
case Keyboard keyboard:
if (add)
listKeyboard.Add(keyboard);
else
listKeyboard.Remove(keyboard);
return;
case Touchscreen screen:
if (add)
listScreen.Add(screen);
else
listScreen.Remove(screen);
return;
case Gamepad pad:
if (add)
listGamepad.Add(pad);
else
listGamepad.Remove(pad);
return;
case Gyroscope gyroscope:
if (add)
listGyroscpe.Add(gyroscope);
else
listGyroscpe.Remove(gyroscope);
return;
case TrackedDevice tracker:
if (add)
listTracker.Add(tracker);
else
listTracker.Remove(tracker);
return;
#if URS_USE_AR_SUBSYSTEMS
case HandheldARInputDevice handheld:
if (add)
listHandheld.Add(handheld);
else
listHandheld.Remove(handheld);
return;
#endif
}
}
void OnEnable()
{
m_TargetCameraState.SetFromTransform(transform);
m_InterpolatingCameraState.SetFromTransform(transform);
}
//---------------------------------------------------------------------------------------------------------------------
Vector3 GetTranslationFromInput(Vector2 input)
{
if (!invertY)
{
input.y *= -1;
}
Vector3 dir = Vector3.right * input.x * m_movementSensitivityFactor;
dir += Vector3.back * input.y * m_movementSensitivityFactor;
return dir;
}
//---------------------------------------------------------------------------------------------------------------------
void UpdateTargetCameraStateFromInput(Vector2 input)
{
if (!invertY)
{
input.y *= -1;
}
float mouseSensitivityFactor = mouseSensitivityCurve.Evaluate(input.magnitude);
m_TargetCameraState.yaw += input.x * mouseSensitivityFactor;
m_TargetCameraState.pitch += input.y * mouseSensitivityFactor;
}
//---------------------------------------------------------------------------------------------------------------------
Vector3 GetInputTranslationDirection()
{
Vector3 direction = new Vector3();
// keyboard control
foreach (var keyboard in listKeyboard)
{
if (keyboard.wKey.isPressed)
{
direction += Vector3.forward;
}
if (keyboard.sKey.isPressed)
{
direction += Vector3.back;
}
if (keyboard.aKey.isPressed)
{
direction += Vector3.left;
}
if (keyboard.dKey.isPressed)
{
direction += Vector3.right;
}
if (keyboard.qKey.isPressed)
{
direction += Vector3.down;
}
if (keyboard.eKey.isPressed)
{
direction += Vector3.up;
}
// Speed up movement when shift key held
if (keyboard.leftShiftKey.isPressed)
{
direction *= 10.0f;
}
}
// gamepad right stick control
foreach (var gamepad in listGamepad)
{
if (gamepad?.rightStick != null)
{
var axis = gamepad.rightStick.ReadValue();
direction += new Vector3(axis.x, 0, axis.y);
}
}
// touch
foreach (var screen in listScreen)
{
var touches = screen.GetTouches();
//Translation
if (touches?.Count() == 2)
{
var activeTouches = touches.ToArray();
direction = GetTranslationFromInput((activeTouches[0].delta + activeTouches[1].delta) / 2f);
}
}
// mouse
foreach (var mouse in listMouse)
{
if (IsMouseDragged(mouse, true))
{
direction = GetTranslationFromInput(mouse.delta.ReadValue());
}
}
return direction;
}
void FixedUpdate()
{
foreach (var keyboard in listKeyboard)
{
if (keyboard.uKey.isPressed)
{
ResetCamera();
return;
}
}
foreach (var tracker in listTracker)
{
if (tracker != null && tracker.enabled)
{
m_TargetCameraState.UpdateTransform(transform);
transform.position += tracker.devicePosition.ReadValue();
transform.eulerAngles += tracker.deviceRotation.ReadValue().eulerAngles;
return;
}
}
#if URS_USE_AR_SUBSYSTEMS
foreach(var handheld in listHandheld)
{
if (handheld != null && handheld.enabled)
{
m_TargetCameraState.UpdateTransform(transform);
transform.position += handheld.devicePosition.ReadValue();
transform.eulerAngles += handheld.deviceRotation.ReadValue().eulerAngles;
return;
}
}
#endif
// Rotation
foreach (var mouse in listMouse)
{
if (IsMouseDragged(mouse, false))
{
UpdateTargetCameraStateFromInput(mouse.delta.ReadValue());
}
}
foreach (var screen in listScreen)
{
var touches = screen.GetTouches();
if (touches.Count() == 1)
{
var activeTouches = touches.ToArray();
UpdateTargetCameraStateFromInput(activeTouches[0].delta);
}
}
foreach (var gyroscope in listGyroscpe)
{
if (gyroscope != null && gyroscope.enabled)
{
var v = gyroscope.angularVelocity.ReadValue();
m_TargetCameraState.yaw += v.x;
m_TargetCameraState.pitch -= v.y;
m_TargetCameraState.roll += v.z;
}
}
// Rotation from joystick
foreach (var gamepad in listGamepad)
{
if (gamepad.leftStick != null)
UpdateTargetCameraStateFromInput(gamepad.leftStick.ReadValue());
}
// Translation
var translation = GetInputTranslationDirection() * Time.deltaTime;
translation *= Mathf.Pow(2.0f, boost);
m_TargetCameraState.Translate(translation);
// Framerate-independent interpolation
// Calculate the lerp amount, such that we get 99% of the way to our target in the specified time
var positionLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / positionLerpTime) * Time.deltaTime);
var rotationLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / rotationLerpTime) * Time.deltaTime);
m_InterpolatingCameraState.LerpTowards(m_TargetCameraState, positionLerpPct, rotationLerpPct);
m_InterpolatingCameraState.UpdateTransform(transform);
}
void ResetCamera()
{
m_InitialCameraState.UpdateTransform(transform);
m_TargetCameraState.SetFromTransform(transform);
m_InterpolatingCameraState.SetFromTransform(transform);
}
//---------------------------------------------------------------------------------------------------------------------
static bool IsMouseDragged(Mouse m, bool useLeftButton)
{
if (null == m)
return false;
if (Screen.safeArea.Contains(m.position.ReadValue()))
{
//check left/right click
if ((useLeftButton && m.leftButton.isPressed) || (!useLeftButton && m.rightButton.isPressed))
{
return true;
}
}
return false;
}
}
}

View File

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

View File

@@ -0,0 +1,123 @@
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
namespace Unity.RenderStreaming.Samples
{
[RequireComponent(typeof(RectTransform))]
class UIController : MonoBehaviour
{
[SerializeField] Text text;
[SerializeField] CanvasGroup canvasGroup;
[SerializeField] Image pointer;
[SerializeField] GameObject noticeTouchControl;
[SerializeField]
private AnimationCurve transitionCurve =
new AnimationCurve(
new Keyframe(0.75f, 1f, 0f, 0f),
new Keyframe(1f, 0f, 0f, 0f));
private float timeTransition = 0f;
private Color transparentColor = new Color(0, 0, 0, 0);
private RectTransform m_rectTransform = null;
private Keyboard m_keyboard;
private Mouse m_mouse;
private Touchscreen m_screen;
public void SetDevice(InputDevice device, bool add = false)
{
switch (device)
{
case Mouse mouse:
m_mouse = add ? mouse : null;
return;
case Keyboard keyboard:
m_keyboard = add ? keyboard : null;
if (add)
m_keyboard.onTextInput += OnTextInput;
return;
case Touchscreen screen:
m_screen = add ? screen : null;
if (noticeTouchControl != null)
{
noticeTouchControl.SetActive(add);
}
return;
}
}
void Start()
{
m_rectTransform = GetComponent<RectTransform>();
canvasGroup.alpha = 0;
text.text = string.Empty;
}
void FixedUpdate()
{
if (m_keyboard != null && !m_keyboard.anyKey.isPressed &&
!Mathf.Approximately(canvasGroup.alpha, 0f))
{
timeTransition += Time.deltaTime;
canvasGroup.alpha = transitionCurve.Evaluate(timeTransition);
if (Mathf.Approximately(canvasGroup.alpha, 0f))
{
text.text = string.Empty;
}
}
bool pointerFromMouse = HighlightPointerFromMouse(
m_mouse, new Vector2Int(Screen.width, Screen.height));
if (pointerFromMouse)
return;
var touches = m_screen?.GetTouches();
if (touches != null && touches.Count() > 0)
{
var position = Vector2.zero;
var count = touches.Count();
var activeTouches = touches.ToArray();
for (var i = 0; i < count; i++)
{
position += activeTouches[i].screenPosition;
}
pointer.rectTransform.anchoredPosition = position / (float)count;
pointer.color = Color.red;
}
else
{
pointer.color = transparentColor;
}
}
//----------------------------------------------------------------------------------------------------------------------
bool HighlightPointerFromMouse(Mouse mouse, Vector2Int screenSize)
{
if (mouse == null)
return false;
if (!Screen.safeArea.Contains(mouse.position.ReadValue()))
return false;
if (!mouse.leftButton.isPressed && !mouse.rightButton.isPressed)
return false;
Vector2 mousePos = mouse.position.ReadValue();
Vector2 pos = mousePos / screenSize * new Vector2(m_rectTransform.rect.width, m_rectTransform.rect.height);
pointer.rectTransform.anchoredPosition = pos;
pointer.color = Color.red;
return true;
}
void OnTextInput(char c)
{
canvasGroup.alpha = 1f;
text.text = c.ToString();
timeTransition = 0;
}
}
}

View File

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

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 046cb2f7ca8d1d84094628415dddd155
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

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

View File

@@ -0,0 +1,406 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.EnhancedTouch;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Users;
using UE = UnityEngine;
namespace Unity.RenderStreaming.Samples
{
using UnityInputSystem = UnityEngine.InputSystem.InputSystem;
enum KeyboardEventType
{
KeyUp = 0,
KeyDown = 1,
}
enum EventType
{
Keyboard = 0,
Mouse = 1,
MouseWheel = 2,
Touch = 3,
ButtonClick = 4,
Gamepad = 5,
}
enum GamepadEventType
{
ButtonUp = 0,
ButtonDown = 1,
ButtonPressed = 2,
Axis = 3
}
enum GamepadKeyCode
{
Button0 = 0,
Button1,
Button2,
Button3,
Button4,
Button5,
Button6,
Button7,
Button8,
Button9,
Axis0Button,
Axis1Button,
DpadUp,
DpadDown,
DpadLeft,
DpadRight,
Axis0 = 100,
Axis1
}
internal static class RemoteInputReceiver
{
private static readonly Dictionary<RemoteInput, uint> s_mapRemoteInputAndInputUserId;
private static readonly List<RemoteInput> s_listRemoteInput;
static RemoteInputReceiver()
{
s_mapRemoteInputAndInputUserId = new Dictionary<RemoteInput, uint>();
s_listRemoteInput = new List<RemoteInput>();
}
internal static void Dispose()
{
s_mapRemoteInputAndInputUserId.Clear();
s_listRemoteInput.Clear();
}
public static IReadOnlyList<RemoteInput> All()
{
return s_listRemoteInput;
}
public static RemoteInput Create()
{
InputUser user = InputUser.CreateUserWithoutPairedDevices();
user = InputUser.PerformPairingWithDevice(UnityInputSystem.AddDevice<Mouse>(), user);
user = InputUser.PerformPairingWithDevice(UnityInputSystem.AddDevice<Keyboard>(), user);
user = InputUser.PerformPairingWithDevice(UnityInputSystem.AddDevice<Gamepad>(), user);
user = InputUser.PerformPairingWithDevice(UnityInputSystem.AddDevice<Touchscreen>(), user);
RemoteInput remoteInput = new RemoteInput(ref user);
s_mapRemoteInputAndInputUserId.Add(remoteInput, user.id);
s_listRemoteInput.Add(remoteInput);
return remoteInput;
}
internal static void Delete(RemoteInput remoteInput)
{
if (remoteInput == null)
{
throw new ArgumentException("The instance of argument is null");
}
bool found = s_mapRemoteInputAndInputUserId.TryGetValue(remoteInput, out uint userId);
if (!found)
{
throw new ArgumentException("The instance of argument is not found");
}
InputUser user = InputUser.all.First(_user => _user.id == userId);
var arrayDeviceId = user.pairedDevices.Select(device => device.deviceId).ToArray();
user.UnpairDevicesAndRemoveUser();
foreach (var deviceId in arrayDeviceId)
{
UnityInputSystem.RemoveDevice(UnityInputSystem.GetDeviceById(deviceId));
}
s_mapRemoteInputAndInputUserId.Remove(remoteInput);
s_listRemoteInput.Remove(remoteInput);
}
}
public interface IInput
{
Mouse RemoteMouse { get; }
Keyboard RemoteKeyboard { get; }
Touchscreen RemoteTouchscreen { get; }
Gamepad RemoteGamepad { get; }
}
internal class RemoteInput : IInput, IDisposable
{
private GamepadState m_gamepadState;
public Mouse RemoteMouse { get; }
public Keyboard RemoteKeyboard { get; }
public Touchscreen RemoteTouchscreen { get; }
public Gamepad RemoteGamepad { get; }
public Action<int> ActionButtonClick;
private UnityEngine.Vector2Int m_prevMousePos;
private KeyboardState m_keyboardState = new KeyboardState();
private bool disposed;
internal RemoteInput(ref InputUser user)
{
RemoteMouse = user.pairedDevices.FirstOrDefault(device => device is Mouse) as Mouse;
RemoteKeyboard = user.pairedDevices.FirstOrDefault(device => device is Keyboard) as Keyboard;
RemoteTouchscreen = user.pairedDevices.FirstOrDefault(device => device is Touchscreen) as Touchscreen;
RemoteGamepad = user.pairedDevices.FirstOrDefault(device => device is Gamepad) as Gamepad;
}
~RemoteInput()
{
Dispose();
}
public void Dispose()
{
if (this.disposed)
{
return;
}
RemoteInputReceiver.Delete(this);
this.disposed = true;
GC.SuppressFinalize(this);
}
//---------------------------------------------------------------------------------------------------------------------
public void ProcessInput(byte[] bytes)
{
if (bytes == null)
throw new ArgumentNullException();
if (bytes.Length == 0)
throw new ArgumentException("byte length is zero");
switch ((EventType)bytes[0])
{
case EventType.Keyboard:
var type = (KeyboardEventType)bytes[1];
var repeat = bytes[2] == 1;
var key = bytes[3];
var character = (char)bytes[4];
ProcessKeyEvent(type, repeat, key, character);
break;
case EventType.Mouse:
var deltaX = BitConverter.ToInt16(bytes, 1);
var deltaY = BitConverter.ToInt16(bytes, 3);
var button = bytes[5];
ProcessMouseMoveEvent(deltaX, deltaY, button);
break;
case EventType.MouseWheel:
var scrollX = BitConverter.ToSingle(bytes, 1);
var scrollY = BitConverter.ToSingle(bytes, 5);
ProcessMouseWheelEvent(scrollX, scrollY);
break;
case EventType.Touch:
{
var length = bytes[1];
var index = 2;
var touches = new TouchState[length];
for (int i = 0; i < length; i++)
{
const int INPUTSYSTEM_ZERO_ID_GUARD = 128; //ID 0 is reserved by inputsystem
int identifier = BitConverter.ToInt32(bytes, index) + INPUTSYSTEM_ZERO_ID_GUARD;
index += 4;
var phase = (UnityEngine.InputSystem.TouchPhase)bytes[index];
index += 1;
var pageX = BitConverter.ToInt16(bytes, index);
index += 2;
var pageY = BitConverter.ToInt16(bytes, index);
index += 2;
var force = BitConverter.ToSingle(bytes, index);
index += 4;
touches[i] = new TouchState
{
touchId = identifier,
phase = phase,
position = new UnityEngine.Vector2Int(pageX, pageY),
pressure = force
};
}
ProcessTouchMoveEvent(touches);
if (Touch.activeTouches.Count > length)
{
ChangeEndStateUnusedTouches(touches);
}
}
break;
case EventType.ButtonClick:
var elementId = BitConverter.ToInt16(bytes, 1);
ProcessButtonClickEvent(elementId);
break;
case EventType.Gamepad:
{
GamepadEventType gamepadEventType = (GamepadEventType)bytes[1];
switch (gamepadEventType)
{
case GamepadEventType.ButtonDown:
case GamepadEventType.ButtonUp:
case GamepadEventType.ButtonPressed:
{
var buttonIndex = bytes[2];
var value = BitConverter.ToDouble(bytes, 3);
ProcessGamepadButtonEvent(gamepadEventType, (GamepadKeyCode)buttonIndex, value);
}
break;
case GamepadEventType.Axis:
{
var buttonIndex = bytes[2];
var x = BitConverter.ToDouble(bytes, 3);
var y = BitConverter.ToDouble(bytes, 11);
ProcessGamepadAxisEvent(x, y, (GamepadKeyCode)buttonIndex);
}
break;
}
UnityInputSystem.QueueStateEvent(RemoteGamepad, m_gamepadState);
}
break;
}
}
#region Gamepads Events
void ProcessGamepadButtonEvent(GamepadEventType state, GamepadKeyCode buttonIndex, double value)
{
GamepadButton buttonToUpdate = GamepadButton.DpadUp;
GamepadState gamepadState = m_gamepadState;
switch (buttonIndex)
{
case GamepadKeyCode.DpadUp:
buttonToUpdate = GamepadButton.DpadUp;
break;
case GamepadKeyCode.DpadDown:
buttonToUpdate = GamepadButton.DpadDown;
break;
case GamepadKeyCode.DpadLeft:
buttonToUpdate = GamepadButton.DpadLeft;
break;
case GamepadKeyCode.DpadRight:
buttonToUpdate = GamepadButton.DpadRight;
break;
case GamepadKeyCode.Button0:
buttonToUpdate = GamepadButton.B;
break;
case GamepadKeyCode.Button1:
buttonToUpdate = GamepadButton.A;
break;
case GamepadKeyCode.Button2:
buttonToUpdate = GamepadButton.Y;
break;
case GamepadKeyCode.Button3:
buttonToUpdate = GamepadButton.X;
break;
case GamepadKeyCode.Button4:
buttonToUpdate = GamepadButton.LeftShoulder;
break;
case GamepadKeyCode.Button5:
buttonToUpdate = GamepadButton.RightShoulder;
break;
case GamepadKeyCode.Button6:
buttonToUpdate = GamepadButton.LeftTrigger;
gamepadState.leftTrigger = (float)value;
break;
case GamepadKeyCode.Button7:
buttonToUpdate = GamepadButton.RightTrigger;
gamepadState.rightTrigger = (float)value;
break;
case GamepadKeyCode.Axis0Button:
buttonToUpdate = GamepadButton.LeftStick;
break;
case GamepadKeyCode.Axis1Button:
buttonToUpdate = GamepadButton.RightStick;
break;
default:
UE.Debug.Log("Unmapped button code: " + buttonIndex);
break;
}
m_gamepadState = gamepadState.WithButton(buttonToUpdate, GamepadEventType.ButtonDown == state || GamepadEventType.ButtonPressed == state);
}
void ProcessGamepadAxisEvent(double x, double y, GamepadKeyCode axisKeyCode)
{
GamepadState gamepadState = m_gamepadState;
if (axisKeyCode == GamepadKeyCode.Axis0)
gamepadState.leftStick = new UE.Vector2((float)x, (float)y);
if (axisKeyCode == GamepadKeyCode.Axis1)
gamepadState.rightStick = new UE.Vector2((float)x, (float)y);
m_gamepadState = gamepadState;
}
#endregion
void ProcessKeyEvent(KeyboardEventType state, bool repeat, byte keyCode, char character)
{
switch (state)
{
case KeyboardEventType.KeyDown:
if (!repeat)
{
m_keyboardState.Set((Key)keyCode, true);
UnityInputSystem.QueueStateEvent(RemoteKeyboard, m_keyboardState);
}
if (character != 0)
{
UnityInputSystem.QueueTextEvent(RemoteKeyboard, character);
}
break;
case KeyboardEventType.KeyUp:
m_keyboardState.Set((Key)keyCode, false);
UnityInputSystem.QueueStateEvent(RemoteKeyboard, m_keyboardState);
break;
}
}
void ProcessMouseMoveEvent(short x, short y, byte button)
{
UnityEngine.Vector2Int pos = new UnityEngine.Vector2Int(x, y);
UnityEngine.Vector2Int delta = pos - m_prevMousePos;
UnityInputSystem.QueueStateEvent(RemoteMouse, new MouseState
{
position = pos,
delta = delta,
buttons = button
});
m_prevMousePos = pos;
}
void ProcessMouseWheelEvent(float scrollX, float scrollY)
{
UnityInputSystem.QueueStateEvent(RemoteMouse, new MouseState { scroll = new UnityEngine.Vector2(scrollX, scrollY) });
}
void ProcessTouchMoveEvent(TouchState[] touches)
{
for (var i = 0; i < touches.Length; i++)
{
UnityInputSystem.QueueStateEvent(RemoteTouchscreen, touches[i]);
}
}
void ChangeEndStateUnusedTouches(TouchState[] touches)
{
int touchCount = Touch.activeTouches.Count;
for (var i = 0; i < touchCount; i++)
{
int touchId = Touch.activeTouches[i].touchId;
if (!Array.Exists(touches, v => v.touchId == touchId))
{
if (Touch.activeTouches[i].phase == TouchPhase.Ended)
{
continue;
}
UnityInputSystem.QueueStateEvent(RemoteTouchscreen, new TouchState
{
touchId = touchId,
phase = TouchPhase.Ended,
position = Touch.activeTouches[i].screenPosition
});
}
}
}
void ProcessButtonClickEvent(int elementId)
{
ActionButtonClick?.Invoke(elementId);
}
}
}

View File

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

View File

@@ -0,0 +1,25 @@
{
"name": "Unity.RenderStreaming.Sample.WebBrowserInput",
"rootNamespace": "",
"references": [
"GUID:40a5acf76f04c4c8ebb69605e4b0d5c7",
"GUID:f12aafacab75a87499e7e45c873ffab8",
"GUID:75469ad4d38634e559750d17036d5f7c"
],
"includePlatforms": [
"Android",
"Editor",
"iOS",
"LinuxStandalone64",
"macOSStandalone",
"WindowsStandalone64"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 87691ed9decf63846bb1eb6a338b76b8
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,104 @@
using System;
using Unity.WebRTC;
using UnityEngine;
using UnityEngine.InputSystem;
namespace Unity.RenderStreaming.Samples
{
/// <summary>
///
/// </summary>
[Serializable]
class ButtonClickEvent : UnityEngine.Events.UnityEvent<int> { }
/// <summary>
///
/// </summary>
[Serializable]
class ButtonClickElement
{
[Tooltip("Specifies the ID on the HTML")]
public int elementId;
public ButtonClickEvent click;
}
/// <summary>
///
/// </summary>
public class WebBrowserInputChannelReceiver : InputChannelReceiverBase
{
/// <summary>
///
/// </summary>
[SerializeField, Tooltip("Array to set your own click event")]
private ButtonClickElement[] arrayButtonClickEvent;
/// <summary>
///
/// </summary>
public override event Action<InputDevice, InputDeviceChange> onDeviceChange;
private RemoteInput remoteInput;
/// <summary>
///
/// </summary>
/// <param name="track"></param>
public override void SetChannel(string connectionId, RTCDataChannel channel)
{
if (channel == null)
{
if (remoteInput != null)
{
onDeviceChange?.Invoke(remoteInput.RemoteGamepad, InputDeviceChange.Removed);
onDeviceChange?.Invoke(remoteInput.RemoteKeyboard, InputDeviceChange.Removed);
onDeviceChange?.Invoke(remoteInput.RemoteMouse, InputDeviceChange.Removed);
onDeviceChange?.Invoke(remoteInput.RemoteTouchscreen, InputDeviceChange.Removed);
if (Channel != null)
{
Channel.OnMessage -= remoteInput.ProcessInput;
}
remoteInput.Dispose();
remoteInput = null;
}
}
else
{
remoteInput = RemoteInputReceiver.Create();
remoteInput.ActionButtonClick = OnButtonClick;
channel.OnMessage += remoteInput.ProcessInput;
onDeviceChange?.Invoke(remoteInput.RemoteGamepad, InputDeviceChange.Added);
onDeviceChange?.Invoke(remoteInput.RemoteKeyboard, InputDeviceChange.Added);
onDeviceChange?.Invoke(remoteInput.RemoteMouse, InputDeviceChange.Added);
onDeviceChange?.Invoke(remoteInput.RemoteTouchscreen, InputDeviceChange.Added);
}
base.SetChannel(connectionId, channel);
}
/// <summary>
///
/// </summary>
/// <param name="elementId"></param>
public virtual void OnButtonClick(int elementId)
{
foreach (var element in arrayButtonClickEvent)
{
if (element.elementId == elementId)
{
element.click.Invoke(elementId);
}
}
}
/// <summary>
///
/// </summary>
public virtual void OnDestroy()
{
remoteInput?.Dispose();
}
}
}

View File

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

View File

@@ -0,0 +1,40 @@
using UnityEngine;
using UnityEngine.UI;
namespace Unity.RenderStreaming.Samples
{
class WebBrowserInputSample : MonoBehaviour
{
[SerializeField] SignalingManager renderStreaming;
[SerializeField] Dropdown dropdownCamera;
[SerializeField] Transform[] cameras;
[SerializeField] CopyTransform copyTransform;
RenderStreamingSettings settings;
private void Awake()
{
settings = SampleManager.Instance.Settings;
}
// Start is called before the first frame update
void Start()
{
dropdownCamera.onValueChanged.AddListener(OnChangeCamera);
if (renderStreaming.runOnAwake)
return;
if (settings != null)
renderStreaming.useDefaultSettings = settings.UseDefaultSettings;
if (settings?.SignalingSettings != null)
renderStreaming.SetSignalingSettings(settings.SignalingSettings);
renderStreaming.Run();
}
void OnChangeCamera(int value)
{
copyTransform.SetOrigin(cameras[value]);
}
}
}

View File

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

View File

@@ -0,0 +1,22 @@
fileFormatVersion: 2
guid: b694c794feaae6a449003215c571243a
AudioImporter:
externalObjects: {}
serializedVersion: 6
defaultSettings:
loadType: 0
sampleRateSetting: 2
sampleRateOverride: 48000
compressionFormat: 0
quality: 1
conversionMode: 0
platformSettingOverrides: {}
forceToMono: 0
normalize: 1
preloadAudioData: 1
loadInBackground: 0
ambisonic: 0
3D: 1
userData:
assetBundleName:
assetBundleVariant: