123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716 |
- using UnityEngine;
- using UnityEngine.XR;
- using System.Collections.Generic;
- #if ZED_STEAM_VR
- using Valve.VR;
- #endif
- #if UNITY_EDITOR
- using UnityEditor;
- #endif
- public class ZEDControllerTracker : MonoBehaviour
- {
-
-
-
- private string loadeddevice = "";
- #if ZED_STEAM_VR //Only enabled if the SteamVR Unity plugin is detected.
-
-
-
-
- protected CVRSystem openvrsystem = OpenVR.System;
-
-
-
- protected VRControllerState_t controllerstate;
-
-
-
- protected VRControllerState_t lastcontrollerstate;
-
-
-
- protected const uint controllerstatesize = 64;
-
-
-
-
- public enum EIndex
- {
- None = -1,
- Hmd = (int)OpenVR.k_unTrackedDeviceIndex_Hmd,
- Device1,
- Device2,
- Device3,
- Device4,
- Device5,
- Device6,
- Device7,
- Device8,
- Device9,
- Device10,
- Device11,
- Device12,
- Device13,
- Device14,
- Device15
- }
- [HideInInspector]
- public EIndex index = EIndex.None;
-
-
-
-
- private float timerSteamVR = 0.0f;
-
-
-
-
- private float timerMaxSteamVR = 0.25f;
- private Devices oldDevice;
-
-
-
-
- [Tooltip("If true, will use a direct API check to OpenVR's API to check if a button is down.\r\n" +
- "Does not work if using the SteamVR plugin 2.0 or higher as well as the action system it includes. ")]
- public bool useLegacySteamVRInput = false;
- #endif
-
-
-
-
- public Dictionary<int, List<TimedPoseData>> poseData = new Dictionary<int, List<TimedPoseData>>();
-
-
-
- public enum Devices
- {
- RightController,
- LeftController,
- ViveTracker,
- Hmd,
- };
-
-
-
- [Tooltip("Type of trackable device that should be tracked.")]
- public Devices deviceToTrack;
-
-
-
-
- [Tooltip("Latency in milliseconds to be applied on the movement of this tracked object, so that virtual controllers don't" +
- " move ahead of their real-world image.")]
- [Range(0, 200)]
- public int latencyCompensation = 78;
-
-
-
-
- [Tooltip("If true, and this is a controller, will offset controller's position by the difference between " +
- "the VR headset and the ZED's tracked position. This keeps controller's position relative to the ZED. ")]
- [LabelOverride("Enable Controller Drift Fix")]
- public bool correctControllerDrift = true;
-
-
-
-
-
-
-
-
-
- [Tooltip("The Serial number of the controller/tracker to be tracked." +
- " If specified, overrides the 'Device to Track' selection.")]
- public string SNHolder = "";
-
-
-
-
- protected Transform zedRigRoot;
-
-
-
- [Tooltip("Reference to the scene's ZEDManager component. Used for compensating for headset drift when this is on a controller. " +
- "If left blank, will be set to the first available ZEDManager.")]
- public ZEDManager zedManager = null;
-
-
-
- protected virtual void Awake()
- {
- #if ZED_STEAM_VR
- openvrsystem = OpenVR.System;
- #endif
- poseData.Clear();
- poseData.Add(1, new List<TimedPoseData>());
-
- loadeddevice = XRSettings.loadedDeviceName;
- if (!zedManager)
- {
- zedManager = FindObjectOfType<ZEDManager>();
-
- if (ZEDManager.GetInstances().Count > 1)
- {
-
- Debug.Log("Warning: ZEDController automatically set itself to first available ZED (" + zedManager.cameraID + ") because zedManager " +
- "value wasn't set, but there are multiple ZEDManagers in the scene. Assign a reference directly to ensure no unexpected behavior.");
- }
- }
- if (zedManager) zedRigRoot = zedManager.GetZedRootTansform();
- }
-
-
-
-
-
- protected virtual void Update()
- {
- #if ZED_OCULUS //Used only if the Oculus Integration plugin is detected.
-
- if (OVRManager.isHmdPresent && loadeddevice.ToString().ToLower().Contains("oculus"))
- {
- if (OVRInput.GetConnectedControllers().ToString().ToLower().Contains("touch"))
- {
-
- if (deviceToTrack == Devices.LeftController)
- RegisterPosition(1, OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch));
- if (deviceToTrack == Devices.RightController)
- RegisterPosition(1, OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch), OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch));
- if (deviceToTrack == Devices.Hmd)
- {
- #if UNITY_2019_3_OR_NEWER
- InputDevice head = InputDevices.GetDeviceAtXRNode(XRNode.CenterEye);
- head.TryGetFeatureValue(CommonUsages.devicePosition, out Vector3 headPosition);
- head.TryGetFeatureValue(CommonUsages.deviceRotation, out Quaternion headRotation);
- RegisterPosition(1, headPosition, headRotation);
- #else
- RegisterPosition(1, InputTracking.GetLocalPosition(XRNode.CenterEye), InputTracking.GetLocalRotation(XRNode.CenterEye));
- #endif
- }
-
- if (poseData.Count > 0)
- {
- sl.Pose p;
-
- p = GetValuePosition(1, (float)(latencyCompensation / 1000.0f));
- transform.position = p.translation;
- transform.rotation = p.rotation;
- }
- }
- }
-
- OVRInput.Update();
- #endif
- #if ZED_STEAM_VR
- UpdateControllerState();
- timerSteamVR += Time.deltaTime;
- if (timerSteamVR <= timerMaxSteamVR)
- return;
- timerSteamVR = 0f;
-
- if (index == EIndex.None && loadeddevice.Contains("OpenVR"))
- {
-
-
-
- if (deviceToTrack == Devices.ViveTracker)
- {
- var error = ETrackedPropertyError.TrackedProp_Success;
- for (uint i = 0; i < 16; i++)
- {
- var result = new System.Text.StringBuilder((int)64);
- OpenVR.System.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_RenderModelName_String, result, 64, ref error);
- if (result.ToString().Contains("tracker"))
- {
- index = (EIndex)i;
- break;
- }
- }
- }
-
- if (deviceToTrack == Devices.RightController)
- {
- index = (EIndex)OpenVR.System.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.RightHand);
- }
-
- if (deviceToTrack == Devices.LeftController)
- {
- index = (EIndex)OpenVR.System.GetTrackedDeviceIndexForControllerRole(ETrackedControllerRole.LeftHand);
- }
-
- if (deviceToTrack == Devices.Hmd)
- {
- index = EIndex.Hmd;
- }
-
- if (SNHolder.Equals("NONE"))
- {
- Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.PAD_CAMERA_CALIBRATION_NOT_FOUND));
- }
- else if (SNHolder != null && index != EIndex.None)
- {
-
- var snerror = ETrackedPropertyError.TrackedProp_Success;
- var snresult = new System.Text.StringBuilder((int)64);
- OpenVR.System.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_SerialNumber_String, snresult, 64, ref snerror);
- if (!snresult.ToString().Contains(SNHolder))
- {
- Debug.LogWarning(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.PAD_CAMERA_CALIBRATION_MISMATCH) + " Serial Number: " + SNHolder);
-
- for (int i = 0; i < 16; i++)
- {
-
- var chsnresult = new System.Text.StringBuilder((int)64);
- OpenVR.System.GetStringTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_RenderModelName_String, snresult, 64, ref snerror);
- if (snresult.ToString().Contains("tracker"))
- {
- index = (EIndex)i;
- OpenVR.System.GetStringTrackedDeviceProperty((uint)i, ETrackedDeviceProperty.Prop_SerialNumber_String, snresult, 64, ref snerror);
- }
- if (snresult.ToString().Contains(SNHolder))
- {
- index = (EIndex)i;
- string deviceRole = OpenVR.System.GetControllerRoleForTrackedDeviceIndex((uint)index).ToString();
- if (deviceRole.Equals("RightHand"))
- deviceToTrack = Devices.RightController;
- else if (deviceRole.Equals("LeftHand"))
- deviceToTrack = Devices.LeftController;
- else if (deviceRole.Equals("Invalid"))
- {
- var error = ETrackedPropertyError.TrackedProp_Success;
- var result = new System.Text.StringBuilder((int)64);
- OpenVR.System.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, result, 64, ref error);
- if (result.ToString().Contains("tracker"))
- deviceToTrack = Devices.ViveTracker;
- }
- Debug.Log("A connected device with the correct Serial Number was found, and assigned to " + this + " the correct device to track.");
- break;
- }
- }
- }
- }
- oldDevice = deviceToTrack;
- }
- if (deviceToTrack != oldDevice)
- index = EIndex.None;
- #endif
- }
- #if ZED_STEAM_VR
-
-
-
- public bool isValid { get; private set; }
-
-
-
- protected void OnNewPoses(TrackedDevicePose_t newpose)
- {
- if (index == EIndex.None)
- return;
- var i = (int)index;
- isValid = false;
- if (!newpose.bDeviceIsConnected)
- return;
- if (!newpose.bPoseIsValid)
- return;
- isValid = true;
-
- var pose = new SteamVR_Utils.RigidTransform(newpose.mDeviceToAbsoluteTracking);
-
- RegisterPosition(1, pose.pos, pose.rot);
-
- sl.Pose p = GetValuePosition(1, (float)(latencyCompensation / 1000.0f));
- transform.localPosition = p.translation;
- transform.localRotation = p.rotation;
- }
- protected void OnEnable()
- {
- if (openvrsystem == null)
- {
- enabled = false;
- return;
- }
- }
- protected void OnDisable()
- {
- isValid = false;
- }
- protected virtual void UpdateControllerState()
- {
- lastcontrollerstate = controllerstate;
-
- if (index > EIndex.Hmd)
- {
- if (OpenVR.Compositor != null){
- ETrackingUniverseOrigin tracktype = OpenVR.Compositor.GetTrackingSpace();
- TrackedDevicePose_t[] absoluteposes = new TrackedDevicePose_t[16];
- openvrsystem.GetDeviceToAbsoluteTrackingPose(tracktype, 0, absoluteposes);
- TrackedDevicePose_t newposes = absoluteposes[(int)index];
- OnNewPoses(newposes);
- }
- }
-
- if (useLegacySteamVRInput)
- {
- openvrsystem.GetControllerState((uint)index, ref controllerstate, controllerstatesize);
- }
- }
-
-
-
-
- [System.ObsoleteAttribute("ZEDControllerTracker's GetVRButton methods are deprecated.\r\n " +
- "Use ZEDControllerTracker_DemoInputs.GetVRButtonDown_Legacy instead., false")]
- public bool GetVRButtonDown(EVRButtonId buttonid)
- {
- if (openvrsystem == null) return false;
- bool washeldlastupdate = (lastcontrollerstate.ulButtonPressed & (1UL << (int)buttonid)) > 0L;
- if (washeldlastupdate == true) return false;
- bool isheld = (controllerstate.ulButtonPressed & (1UL << (int)buttonid)) > 0L;
- return isheld;
- }
-
-
-
-
- [System.ObsoleteAttribute("ZEDControllerTracker's GetVRButton methods are deprecated.\r\n " +
- "Use ZEDControllerTracker_DemoInputs.GetVRButtonHeld_Legacy instead.", false)]
- public bool GetVRButtonHeld(EVRButtonId buttonid)
- {
- if (openvrsystem == null) return false;
- bool isheld = (controllerstate.ulButtonPressed & (1UL << (int)buttonid)) > 0L;
- return isheld;
- }
-
-
-
-
- [System.ObsoleteAttribute("ZEDControllerTracker's GetVRButton methods are deprecated.\r\n " +
- "Use ZEDControllerTracker_DemoInputs.GetVRButtonReleased_Legacy instead.", false)]
- public bool GetVRButtonReleased(EVRButtonId buttonid)
- {
- if (openvrsystem == null) return false;
- bool washeldlastupdate = (lastcontrollerstate.ulButtonPressed & (1UL << (int)buttonid)) > 0L;
- if (washeldlastupdate == false) return false;
- bool isheld = (controllerstate.ulButtonPressed & (1UL << (int)buttonid)) > 0L;
- return !isheld;
- }
-
-
-
-
-
- [System.ObsoleteAttribute("ZEDControllerTracker.GetAxis is deprecated.\r\n " +
- "Use ZEDControllerTracker_DemoInputs.GetVRAxis_Legacy instead.", false)]
- public Vector2 GetAxis(EVRButtonId buttonid)
- {
-
- uint axis = (uint)buttonid - (uint)EVRButtonId.k_EButton_Axis0;
- if (axis < 0 || axis > 4)
- {
- Debug.LogError("Called GetAxis with " + buttonid + ", which is not an axis.");
- return Vector2.zero;
- }
- switch (axis)
- {
- case 0: return new Vector2(controllerstate.rAxis0.x, controllerstate.rAxis0.y);
- case 1: return new Vector2(controllerstate.rAxis1.x, controllerstate.rAxis1.y);
- case 2: return new Vector2(controllerstate.rAxis2.x, controllerstate.rAxis2.y);
- case 3: return new Vector2(controllerstate.rAxis3.x, controllerstate.rAxis3.y);
- case 4: return new Vector2(controllerstate.rAxis4.x, controllerstate.rAxis4.y);
- default: return Vector2.zero;
- }
- }
- #endif
-
-
-
-
-
-
- private sl.Pose GetValuePosition(int keyindex, float timeDelay)
- {
- sl.Pose p = new sl.Pose();
- if (poseData.ContainsKey(keyindex))
- {
-
- p.translation = poseData[keyindex][poseData[keyindex].Count - 1].position;
- p.rotation = poseData[keyindex][poseData[keyindex].Count - 1].rotation;
- float idealTS = (Time.time - timeDelay);
- for (int i = 0; i < poseData[keyindex].Count; ++i)
- {
- if (poseData[keyindex][i].timestamp > idealTS)
- {
- int currentIndex = i;
- if (currentIndex > 0)
- {
-
- float timeBetween = poseData[keyindex][currentIndex].timestamp - poseData[keyindex][currentIndex - 1].timestamp;
- float alpha = ((Time.time - poseData[keyindex][currentIndex - 1].timestamp) - timeDelay) / timeBetween;
-
- Vector3 pos = Vector3.Lerp(poseData[keyindex][currentIndex - 1].position, poseData[keyindex][currentIndex].position, alpha);
- Quaternion rot = Quaternion.Lerp(poseData[keyindex][currentIndex - 1].rotation, poseData[keyindex][currentIndex].rotation, alpha);
-
- p = new sl.Pose();
- p.translation = pos;
- p.rotation = rot;
-
- if (correctControllerDrift == true &&
- (deviceToTrack == Devices.LeftController || deviceToTrack == Devices.RightController || deviceToTrack == Devices.ViveTracker) &&
- (zedManager != null && zedManager.IsStereoRig == true && !zedManager.transform.IsChildOf(transform)))
- {
-
- #if UNITY_2019_3_OR_NEWER
- InputDevice head = InputDevices.GetDeviceAtXRNode(XRNode.Head);
- head.TryGetFeatureValue(CommonUsages.devicePosition, out Vector3 headPosition);
- Vector3 zedhmdposoffset = zedRigRoot.position - headPosition;
- #else
- Vector3 zedhmdposoffset = zedRigRoot.position - InputTracking.GetLocalPosition(XRNode.Head);
- #endif
- p.translation += zedhmdposoffset;
- }
-
- poseData[keyindex].RemoveRange(0, currentIndex - 1);
- }
- return p;
- }
- }
- }
- return p;
- }
-
-
-
-
-
-
- private void RegisterPosition(int keyindex, Vector3 position, Quaternion rot)
- {
- TimedPoseData currentPoseData = new TimedPoseData();
- currentPoseData.timestamp = Time.time;
- currentPoseData.rotation = rot;
- currentPoseData.position = position;
- poseData[keyindex].Add(currentPoseData);
- }
-
-
-
-
-
- public struct TimedPoseData
- {
-
-
-
- public float timestamp;
-
-
-
- public Quaternion rotation;
-
-
-
- public Vector3 position;
- }
- }
- #if UNITY_EDITOR
- [CustomEditor(typeof(ZEDControllerTracker)), CanEditMultipleObjects]
- public class ZEDVRDependencies : Editor
- {
- [SerializeField]
- static string defineName;
- static string packageName;
- public override void OnInspectorGUI()
- {
-
- if (CheckPackageExists("SteamVR_Camera.cs"))
- {
- defineName = "ZED_STEAM_VR";
- packageName = "SteamVR";
- }
-
- else if (CheckPackageExists("OVRManager"))
- {
- defineName = "ZED_OCULUS";
- packageName = "Oculus";
- }
- if (EditorPrefs.GetBool(packageName))
- {
- DrawDefaultInspector();
- }
- else
- {
- GUILayout.Space(20);
- if (GUILayout.Button("Load " + packageName + " data"))
- {
- if (CheckPackageExists(packageName))
- {
- ActivateDefine();
- }
- }
- if (packageName == "SteamVR")
- EditorGUILayout.HelpBox(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.STEAMVR_NOT_INSTALLED), MessageType.Warning);
- else if (packageName == "Oculus")
- EditorGUILayout.HelpBox(ZEDLogMessage.Error2Str(ZEDLogMessage.ERROR.OVR_NOT_INSTALLED), MessageType.Warning);
- }
- }
-
-
-
-
-
-
-
- public static bool CheckPackageExists(string name)
- {
- string[] packages = AssetDatabase.FindAssets(name);
- return packages.Length != 0;
- }
-
-
-
-
- public static void ActivateDefine()
- {
- EditorPrefs.SetBool(packageName, true);
- string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
- if (defines.Length != 0)
- {
- if (!defines.Contains(defineName))
- {
- defines += ";" + defineName;
- }
- }
- else
- {
- if (!defines.Contains(defineName))
- {
- defines += defineName;
- }
- }
- PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, defines);
- }
-
-
-
-
-
- public static void DeactivateDefine(string packagename)
- {
- EditorPrefs.SetBool(packagename, false);
- string defines = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
- if (defines.Length != 0)
- {
- if (defineName != null && defines.Contains(defineName))
- {
- defines = defines.Remove(defines.IndexOf(defineName), defineName.Length);
- if (defines.LastIndexOf(";") == defines.Length - 1 && defines.Length != 0)
- {
- defines.Remove(defines.LastIndexOf(";"), 1);
- }
- }
- }
- PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, defines);
- }
- }
- #endif
|