public bool IsDeviceConnected(uint idx) { if (!IsReady()) { return(false); } return(openvr.IsTrackedDeviceConnected(idx)); }
private void TrackingLoop() { try { EVRInitError initError = EVRInitError.None; CVRSystem cvrSystem = OpenVR.Init(ref initError, EVRApplicationType.VRApplication_Utility); var chaperone = OpenVR.Chaperone; var quadArea = new HmdQuad_t(); chaperone.GetPlayAreaRect(ref quadArea); _playArea = quadArea.ToPlayArea(); if (initError != EVRInitError.None) { throw new InvalidOperationException($"EVR init erro: {initError}"); } while (_keepReading) { TrackedDevicePose_t[] trackedDevicePoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount]; cvrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0f, trackedDevicePoses); for (uint trackedDeviceIndex = 0; trackedDeviceIndex < OpenVR.k_unMaxTrackedDeviceCount; trackedDeviceIndex++) { if (cvrSystem.IsTrackedDeviceConnected(trackedDeviceIndex)) { ETrackedDeviceClass deviceClass = cvrSystem.GetTrackedDeviceClass(trackedDeviceIndex); if (true) { VRControllerState_t controllerState = new VRControllerState_t(); cvrSystem.GetControllerState(1, ref controllerState, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t))); ETrackingResult trackingResult = trackedDevicePoses[trackedDeviceIndex].eTrackingResult; bool trigger = controllerState.rAxis1.x > 0.9f; bool menuButton = (controllerState.ulButtonPressed & (1ul << (int)EVRButtonId.k_EButton_ApplicationMenu)) != 0; bool gripButton = (controllerState.ulButtonPressed & (1ul << (int)EVRButtonId.k_EButton_Grip)) != 0; if (trackingResult == ETrackingResult.Running_OK) { HmdMatrix34_t trackingMatrix = trackedDevicePoses[trackedDeviceIndex].mDeviceToAbsoluteTracking; Vector3 speedVector = trackedDevicePoses[trackedDeviceIndex].vVelocity.ToVelocityVector(); Vector3 position = trackingMatrix.ToPositionVector(); DeviceTrackingData trackingUpdate = new DeviceTrackingData((int)trackedDeviceIndex, deviceClass.ToString(), position, trackingMatrix.ToRotationQuaternion()); NewPoseUpdate?.Invoke(this, trackingUpdate); } } } } Thread.Sleep(UpdatedInterval); } } catch (Exception e) { Console.WriteLine($"Error: {e}"); } finally { OpenVR.Shutdown(); } }
void HMDCoords() { if (!vrContext.IsTrackedDeviceConnected((uint)HMD.Id)) { return; } //TrackedDevicePose_t struct is a OpenVR struct. See line 180 in the openvr.h header. TrackedDevicePose_t[] trackedDevicePose = new TrackedDevicePose_t[1]; //if (vrContext.IsInputFocusCapturedByAnotherProcess()) // printf("\nINFO--Input Focus by Another Process"); vrContext.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0f, trackedDevicePose); var mat = ConvertMatrix(trackedDevicePose[0].mDeviceToAbsoluteTracking); HMD.Position = GetPosition(mat); HMD.Rotation = GetRotation(mat); //Console.WriteLine(111111); //Console.WriteLine(mat); }
private static void SteamVr() { Console.WriteLine("Starting"); EVRInitError initError = EVRInitError.None; CVRSystem cvrSystem = OpenVR.Init(ref initError, EVRApplicationType.VRApplication_Utility); Console.WriteLine("Error: " + initError.ToString()); if (cvrSystem == null) { Console.WriteLine("Error!"); } while (true) { Thread.Sleep(1); TrackedDevicePose_t[] trackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount]; cvrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseRawAndUncalibrated, 0f, trackedDevicePose); VRControllerState_t controllerState = new VRControllerState_t(); cvrSystem.GetControllerState(1, ref controllerState, (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(VRControllerState_t))); int trigger = controllerState.rAxis1.x > 0.9f ? 1 : 0; bool topButtom = (controllerState.ulButtonPressed & (1ul << (int)EVRButtonId.k_EButton_ApplicationMenu)) != 0; TrackedDevicePose_t pose = trackedDevicePose[1]; ETrackingResult trackingResult = pose.eTrackingResult; HmdMatrix34_t hmdMatrix = pose.mDeviceToAbsoluteTracking; Position pos = new Position(hmdMatrix); Rotation rot = new Rotation(hmdMatrix); Console.WriteLine($"Position: {pos} Rotation: {rot} trigger {trigger} app {topButtom}"); foreach (Socket client in _clients.ToArray()) { try { client.Send(Encoding.ASCII.GetBytes($"S{pos.ToData()} {rot.ToData()} {trigger} {(topButtom ? 1 : 0)}E")); } catch (Exception) { _clients.Remove(client); } } } for (int i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++) { if (cvrSystem?.IsTrackedDeviceConnected((uint)i) ?? false) { ETrackedDeviceClass deviceClass = cvrSystem.GetTrackedDeviceClass((uint)i); Console.WriteLine($"index: {i} is {deviceClass}"); } } Console.ReadLine(); OpenVR.Shutdown(); Console.WriteLine("Shut down"); Console.ReadLine(); }
// Token: 0x06000DE5 RID: 3557 RVA: 0x000587C0 File Offset: 0x000569C0 private void OnEnable() { if (!string.IsNullOrEmpty(this.modelOverride)) { Debug.Log("Model override is really only meant to be used in the scene view for lining things up; using it at runtime is discouraged. Use tracked device index instead to ensure the correct model is displayed for all users."); base.enabled = false; return; } CVRSystem system = OpenVR.System; if (system != null && system.IsTrackedDeviceConnected((uint)this.index)) { this.UpdateModel(); } this.deviceConnectedAction.enabled = true; this.hideRenderModelsAction.enabled = true; this.modelSkinSettingsHaveChangedAction.enabled = true; }
private static void UpdateDevices(CVRSystem system, ref uint overlayIndex) { m_Lock.EnterWriteLock(); try { m_Devices.Clear(); } finally { m_Lock.ExitWriteLock(); } var sb = new StringBuilder(256); var state = new VRControllerState_t(); for (var i = 0u; i < OpenVR.k_unMaxTrackedDeviceCount; ++i) { var devClass = system.GetTrackedDeviceClass(i); if (devClass == ETrackedDeviceClass.Controller || devClass == ETrackedDeviceClass.GenericTracker || devClass == ETrackedDeviceClass.TrackingReference) { var err = ETrackedPropertyError.TrackedProp_Success; var batteryPercentage = system.GetFloatTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_DeviceBatteryPercentage_Float, ref err); if (err != ETrackedPropertyError.TrackedProp_Success) { batteryPercentage = 1f; } sb.Clear(); system.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_TrackingSystemName_String, sb, (uint)sb.Capacity, ref err); var isOculus = sb.ToString().IndexOf("oculus", StringComparison.OrdinalIgnoreCase) >= 0; // Oculus : B/Y, Bit 1, Mask 2 // Oculus : A/X, Bit 7, Mask 128 // Vive : Menu, Bit 1, Mask 2, // Vive : Grip, Bit 2, Mask 4 var role = system.GetControllerRoleForTrackedDeviceIndex(i); if (role == ETrackedControllerRole.LeftHand || role == ETrackedControllerRole.RightHand) { if (system.GetControllerState(i, ref state, (uint)Marshal.SizeOf(state)) && (state.ulButtonPressed & (isOculus ? 2u : 4u)) != 0) { if (role == ETrackedControllerRole.LeftHand) { Array.Copy(m_L_Translation, m_Translation, 3); Array.Copy(m_L_Rotation, m_Rotation, 3); } else { Array.Copy(m_R_Translation, m_Translation, 3); Array.Copy(m_R_Rotation, m_Rotation, 3); } overlayIndex = i; } } var type = string.Empty; if (devClass == ETrackedDeviceClass.Controller) { if (role == ETrackedControllerRole.LeftHand) { type = "leftController"; } else if (role == ETrackedControllerRole.RightHand) { type = "rightController"; } else { type = "controller"; } } else if (devClass == ETrackedDeviceClass.GenericTracker) { type = "tracker"; } else if (devClass == ETrackedDeviceClass.TrackingReference) { type = "base"; } var item = new[] { type, system.IsTrackedDeviceConnected(i) ? "connected" : "disconnected", (batteryPercentage * 100).ToString() }; m_Lock.EnterWriteLock(); try { m_Devices.Add(item); } finally { m_Lock.ExitWriteLock(); } } } }
void KeepAlive() { KeepAliveCounter++; if (StopRequested) { Stop(); return; } if (VRSys == null) { if (KeepAliveCounter % InitializationDivider != 0) // do not attempt initialization on every loop. { return; } // ***** INITIALIZATION ****** //if (!OpenVR.IsHmdPresent()) // Note that this also leaks memory // To avoid a memory leak, check that SteamVR is running before trying to Initialize if (System.Diagnostics.Process.GetProcessesByName(Config.SteamVRProcessName).Any()) { if (InitAttemptCount >= InitAttemptLimit) { Stop(true); // no point to keep looping and eating memory forever } InitAttemptCount++; OpenVRConnStatus = OpenVRConnectionStatus.Initializing; // do not carelessly call OpenVR.Init(), it will leak memory VRSys = OpenVR.Init(ref LastOpenVRError, EVRApplicationType.VRApplication_Background); if (LastOpenVRError != EVRInitError.None || VRSys == null) { if (LastOpenVRError == EVRInitError.Init_HmdNotFound || LastOpenVRError == EVRInitError.Init_HmdNotFoundPresenceFailed) { OpenVRConnStatus = OpenVRConnectionStatus.NoHMD; Thread.Sleep(SleepTimeAfterQuit); } return; } bool hmdFound = false; // check devices and find HMD index (but I suppose it's always 0) - Documentation is vague. // For example, what's the purpose of OpenVR.k_unTrackedDeviceIndex_Hmd? What about multiple HMDs... for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++) { if (VRSys.IsTrackedDeviceConnected(i)) { ETrackedDeviceClass c = VRSys.GetTrackedDeviceClass(i); if (c == ETrackedDeviceClass.HMD) { HmdIndex = i; hmdFound = true; break; } } } if (!hmdFound) { EndCurrentSession(); OpenVRConnStatus = OpenVRConnectionStatus.NoHMD; Thread.Sleep(SleepTimeAfterQuit); return; } PoseArray = new TrackedDevicePose_t[HmdIndex + 1]; for (int i = 0; i < PoseArray.Length; i++) { PoseArray[i] = new TrackedDevicePose_t(); } if (SteamVRWasOffBefore) { // Wait a bit more before reporting OK and allowing hmd queries when SteamVR is started AFTER CG. // The initial yaw values from the API sometimes threw the counter off by one half-turn. // Maybe there's a small window at the beginning when the headset readings are not stable... // This is very hard to reproduce/test as it happens so rarely. Shooting in the dark here. Thread.Sleep(3000); SteamVRWasOffBefore = false; } else { Thread.Sleep(500); } OpenVRConnStatus = OpenVRConnectionStatus.AllOK; } else { SteamVRWasOffBefore = true; OpenVRConnStatus = OpenVRConnectionStatus.NoSteamVR; } } else // VRSys != null (connection has been initialized) { // Check quit request VRSys.PollNextEvent(ref NextVREvent, (uint)System.Runtime.InteropServices.Marshal.SizeOf(NextVREvent)); // this doesn't always work... I suppose the quit event can fly by when the poll rate is relatively low // It seems that SteamVR kills the VR processes that don't get Quit event with PollNextEvent(). if (NextVREvent.eventType == (uint)EVREventType.VREvent_Quit) { OpenVRConnStatus = OpenVRConnectionStatus.SteamVRQuit; // to immediately prevent native methods from being called EndCurrentSession(); OpenVRConnStatus = OpenVRConnectionStatus.SteamVRQuit; // again to get correct status (changed in EndCurrentSession()) // a good sleep before starting to poll steamvr -process again Thread.Sleep(SleepTimeAfterQuit); } else { bool interaction = (VRSys.GetTrackedDeviceActivityLevel(HmdIndex) == EDeviceActivityLevel.k_EDeviceActivityLevel_UserInteraction); if (interaction == HMDUserInteraction_previousReading) { HMDUserInteractionCounter++; } else { HMDUserInteractionCounter = 0; } HMDUserInteraction_previousReading = interaction; // some buffer to filter out false flags (and conveniently some delay for notifications) // ... although false flags are not really possible the way OpenVR currently works if (HMDUserInteractionCounter > HMDUserInteractionDivider) { if (HMDUserInteraction_buffered != interaction) { HMDUserInteraction_buffered = interaction; if (interaction) { Worker.ReportProgress(1, null); } else { Worker.ReportProgress(2, null); } } HMDUserInteractionCounter = 0; } } } }
private async void ParseTrackingFrame() { try { for (uint id = 0; id < OpenVR.k_unMaxTrackedDeviceCount; id++) { if (vr_pointer != null) { TrackedDevicePose_t[] trackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount]; if (!vr_pointer.IsTrackedDeviceConnected(id)) { continue; } VRControllerState_t controllState = new VRControllerState_t(); ETrackedDeviceClass trackedDeviceClass = vr_pointer.GetTrackedDeviceClass(id); switch (trackedDeviceClass) { case ETrackedDeviceClass.Controller: vr_pointer.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, id, ref controllState, OpenVR.k_unMaxTrackedDeviceCount, ref trackedDevicePose[id]); HmdVector3_t position = GetPosition(trackedDevicePose[id].mDeviceToAbsoluteTracking); // devicePose->mDeviceToAbsoluteTracking); HmdVector3_t rotation = GetRotationEuler(trackedDevicePose[id].mDeviceToAbsoluteTracking); int positionControllerX = (int)position.v0; int positionControllerY = (int)position.v1; int positionControllerZ = (int)position.v2 * (-1); int rotationControllerX = (int)rotation.v0 + 180; int rotationControllerY = (int)rotation.v1; int rotationControllerZ = (int)rotation.v2; if (ControlViewModel.teleporOffset[0] != -1) { ControlViewModel.transOffSetControllerX = ControlViewModel.teleporOffset[0]; ControlViewModel.transOffSetControllerY = ControlViewModel.teleporOffset[1]; ControlViewModel.transOffSetControllerZ = ControlViewModel.teleporOffset[2]; ControlViewModel.rotOffSetControllerZ = ControlViewModel.teleporOffset[3]; } ETrackedControllerRole result = vr_pointer.GetControllerRoleForTrackedDeviceIndex(id); if (result != ETrackedControllerRole.LeftHand && lastController != ETrackedControllerRole.LeftHand) { RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.LeftController); } if (result != ETrackedControllerRole.RightHand && lastController != ETrackedControllerRole.RightHand) { RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.RightController); } switch (result) { case ETrackedControllerRole.Invalid: break; case ETrackedControllerRole.LeftHand: if (communicationProtocolUdp == false) { MessageBuffer mb2 = new MessageBuffer(); someThingTracked = true; int type = 101; mb2.add(type); mb2.add(userId); int handid = 1; mb2.add(handid); mb2.add(positionControllerX + ControlViewModel.transOffSetControllerX); mb2.add(positionControllerY + ControlViewModel.transOffSetControllerY); mb2.add(positionControllerZ + ControlViewModel.transOffSetControllerZ); mb2.add(rotationControllerX); mb2.add(rotationControllerY); mb2.add(rotationControllerZ); mb2.add(ControlViewModel.rotOffSetControllerZ); RaiseControllerEvent(new TrackingChangedEventArgs(true), Tracker.LeftController); Message msg = new Message(mb2, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE); lock (tcpSocketManager.send_msg(msg)) { tcpSocketManager.send_msg(msg); } Thread.Sleep(20); break; } break; case ETrackedControllerRole.RightHand: if (communicationProtocolUdp == false) { MessageBuffer mb2 = new MessageBuffer(); someThingTracked = true; int type = 101; mb2.add(type); mb2.add(userId); int handid = 2; mb2.add(handid); mb2.add(positionControllerX + ControlViewModel.transOffSetControllerX); mb2.add(positionControllerY + ControlViewModel.transOffSetControllerY); mb2.add(positionControllerZ + ControlViewModel.transOffSetControllerZ); mb2.add(rotationControllerX); mb2.add(rotationControllerY); mb2.add(rotationControllerZ); mb2.add(ControlViewModel.rotOffSetControllerZ); Message msg = new Message(mb2, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE); RaiseControllerEvent(new TrackingChangedEventArgs(true), Tracker.RightController); lock (tcpSocketManager.send_msg(msg)) { tcpSocketManager.send_msg(msg); } Thread.Sleep(20); break; } break; } break; } } } } catch (Exception e) { log.Warn("ParseTrackingFrame in Controller Tracking wurde beendet!" + e); RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.LeftController); RaiseControllerEvent(new TrackingChangedEventArgs(false), Tracker.RightController); } }
private bool StartupOVR() { EVRInitError error = EVRInitError.Driver_Failed; vr = OpenVR.Init(ref error, EVRApplicationType.VRApplication_Overlay); if (error != EVRInitError.None) { Debug.WriteLine("OpenVR Init Error: " + error.ToString()); return(false); } overlay = OpenVR.Overlay; EVROverlayError overlayError = overlay.CreateOverlay("Jstf_ovr_cards", "OpenVR Cards System Overlay", ref overlayHandle); if (overlayError != EVROverlayError.None) { OpenVR.Shutdown(); Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString()); return(false); } /*overlayError = overlay.SetOverlayFromFile(overlayHandle, AssetsPath + "overlay.png"); * if (overlayError != EVROverlayError.None) * { * CleanupOVR(); * Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString()); * return false; * }*/ overlayError = overlay.SetOverlayInputMethod(overlayHandle, VROverlayInputMethod.Mouse); if (overlayError != EVROverlayError.None) { CleanupOVR(); Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString()); return(false); } overlayTexture = new Texture_t { eType = ETextureType.OpenGL, eColorSpace = EColorSpace.Auto, handle = (IntPtr)textureId }; overlayError = overlay.SetOverlayTexture(overlayHandle, ref overlayTexture); if (overlayError != EVROverlayError.None) { CleanupOVR(); Debug.WriteLine("OpenVR Overlay Error: " + overlayError.ToString()); return(false); } HmdId = OpenVR.k_unTrackedDeviceIndex_Hmd; for (uint i = HmdId + 1; i < OpenVR.k_unMaxTrackedDeviceCount; i++) { if (vr.IsTrackedDeviceConnected(i)) { ETrackedDeviceClass cls = vr.GetTrackedDeviceClass(i); if (cls == ETrackedDeviceClass.Controller) { ETrackedControllerRole rl = vr.GetControllerRoleForTrackedDeviceIndex(i); if (rl == ETrackedControllerRole.LeftHand) { LeftControllerId = i; Debug.WriteLine("Found Left Controller"); } else if (rl == ETrackedControllerRole.RightHand) { RightControllerId = i; Debug.WriteLine("Found Right Controller"); } } } } mat = new HmdMatrix34_t { m0 = 1, m1 = 0, m2 = 0, m3 = 0f, m4 = 0, m5 = 1, m6 = 0, m7 = 0.1f, m8 = 0, m9 = 0, m10 = 1, m11 = 0f }; overlayError = overlay.SetOverlayTransformTrackedDeviceRelative(overlayHandle, RightControllerId, ref mat); if (overlayError != EVROverlayError.None) { Debug.WriteLine("Cannot bind overlay to Tracked device."); Debug.WriteLine("Error: " + overlayError.ToString()); CleanupOVR(); return(false); } overlayError = overlay.SetOverlayWidthInMeters(overlayHandle, 0.2f); if (overlayError != EVROverlayError.None) { Debug.WriteLine("Cannot set overlay size."); Debug.WriteLine("Error: " + overlayError.ToString()); CleanupOVR(); return(false); } overlayError = overlay.SetOverlayAlpha(overlayHandle, 1); if (overlayError != EVROverlayError.None) { Debug.WriteLine("Cannot set overlay alpha."); Debug.WriteLine("Error: " + overlayError.ToString()); CleanupOVR(); return(false); } overlayError = overlay.SetOverlayColor(overlayHandle, 1, 1, 1); if (overlayError != EVROverlayError.None) { Debug.WriteLine("Cannot set overlay color."); Debug.WriteLine("Error: " + overlayError.ToString()); CleanupOVR(); return(false); } #if DEBUG Debug.WriteLine("OpenVR Startup Complete"); #endif return(true); }
public unsafe override bool GatherInput(XRControllerState[] state_controllers, out int controllerCount, out bool leftSet, out int leftSetIndex, out bool rightSet, out int rightSetIndex, out SideToSet sideToSet) { // defaults GatherInputDefaults(out controllerCount, out leftSet, out leftSetIndex, out rightSet, out rightSetIndex, out sideToSet); // reset controllers ResetControllers(state_controllers); // validate OpenVR is avaliable if (!isInit) { return(false); } if (system == null || !system.IsInputAvailable() || input.IsUsingLegacyInput()) { return(false); } // get controller connection status and side for (uint i = 0; i != OpenVR.k_unMaxTrackedDeviceCount; ++i) { if (!system.IsTrackedDeviceConnected(i)) { continue; } if (system.GetTrackedDeviceClass(i) != ETrackedDeviceClass.Controller) { continue; } // get controller type ETrackedPropertyError e = ETrackedPropertyError.TrackedProp_Success; system.GetStringTrackedDeviceProperty(i, ETrackedDeviceProperty.Prop_ControllerType_String, OpenVR_Shared.propertyText, (uint)OpenVR_Shared.propertyText.Capacity, ref e); if (e != ETrackedPropertyError.TrackedProp_Success) { continue; } // ignore gamepads if (OpenVR_Shared.propertyText.Equals(OpenVR_Shared.propertyText_Gamepad)) { continue; } // get controller var controller = state_controllers[controllerCount]; controller.connected = true; // get controller type if (OpenVR_Shared.propertyText.Equals(OpenVR_Shared.propertyText_ViveController)) { controller.type = XRInputControllerType.HTCVive; } else if (OpenVR_Shared.propertyText.Equals(OpenVR_Shared.propertyText_ViveCosmosController)) { controller.type = XRInputControllerType.HTCViveCosmos; } else if (OpenVR_Shared.propertyText.Equals(OpenVR_Shared.propertyText_IndexController)) { controller.type = XRInputControllerType.ValveIndex; } else if (OpenVR_Shared.propertyText.ToString().StartsWith(OpenVR_Shared.propertyText_Oculus.ToString())) { controller.type = XRInputControllerType.Oculus; } else if (OpenVR_Shared.propertyText.Equals(OpenVR_Shared.propertyText_WMR)) { controller.type = XRInputControllerType.WMR; } else if (OpenVR_Shared.propertyText.Equals(OpenVR_Shared.propertyText_WMR_G2)) { controller.type = XRInputControllerType.WMR_G2; } // update controller side var role = system.GetControllerRoleForTrackedDeviceIndex(i); switch (role) { case ETrackedControllerRole.LeftHand: controller.side = XRControllerSide.Left; leftSet = true; leftSetIndex = controllerCount; leftHand = (int)i; break; case ETrackedControllerRole.RightHand: controller.side = XRControllerSide.Right; rightSet = true; rightSetIndex = controllerCount; rightHand = (int)i; break; default: controller.side = XRControllerSide.Unknown; break; } state_controllers[controllerCount] = controller; ++controllerCount; } // pre-finish/pre-resolve unknown controller sides GatherInputFinish(state_controllers, controllerCount, ref leftSet, ref leftSetIndex, ref rightSet, ref rightSetIndex, ref sideToSet); // update inputs var error = input.UpdateActionState(actionSets, (uint)Marshal.SizeOf <VRActiveActionSet_t>()); if (error != EVRInputError.None) { Debug.LogError("UpdateActionState: " + error.ToString()); } // get hands var controllerRight = new XRControllerState(); var controllerLeft = new XRControllerState(); if (rightSet) { controllerRight = state_controllers[rightSetIndex]; } if (leftSet) { controllerLeft = state_controllers[leftSetIndex]; } // update bumper buttons/touch controllerRight.buttonBumper.Update(GetButtonState(viveAction_BumperButton, viveSource_RightHand)); controllerLeft.buttonBumper.Update(GetButtonState(viveAction_BumperButton, viveSource_LeftHand)); controllerRight.touchBumper.Update(GetButtonState(viveAction_BumperTouch, viveSource_RightHand)); controllerLeft.touchBumper.Update(GetButtonState(viveAction_BumperTouch, viveSource_LeftHand)); // update trigger buttons/touch controllerRight.buttonTrigger.Update(GetButtonState(viveAction_TriggerButton, viveSource_RightHand)); controllerLeft.buttonTrigger.Update(GetButtonState(viveAction_TriggerButton, viveSource_LeftHand)); controllerRight.touchTrigger.Update(GetButtonState(viveAction_TriggerTouch, viveSource_RightHand)); controllerLeft.touchTrigger.Update(GetButtonState(viveAction_TriggerTouch, viveSource_LeftHand)); // update grip buttons/touch controllerRight.buttonGrip.Update(GetButtonState(viveAction_GripButton, viveSource_RightHand)); controllerLeft.buttonGrip.Update(GetButtonState(viveAction_GripButton, viveSource_LeftHand)); controllerRight.touchGrip.Update(GetButtonState(viveAction_GripTouch, viveSource_RightHand)); controllerLeft.touchGrip.Update(GetButtonState(viveAction_GripTouch, viveSource_LeftHand)); // update menu buttons/touch controllerRight.buttonMenu.Update(GetButtonState(viveAction_MenuButton, viveSource_RightHand)); controllerLeft.buttonMenu.Update(GetButtonState(viveAction_MenuButton, viveSource_LeftHand)); controllerRight.touchMenu.Update(GetButtonState(viveAction_MenuTouch, viveSource_RightHand)); controllerLeft.touchMenu.Update(GetButtonState(viveAction_MenuTouch, viveSource_LeftHand)); // update button/touch 1 controllerRight.button1.Update(GetButtonState(viveAction_Button1, viveSource_RightHand)); controllerLeft.button1.Update(GetButtonState(viveAction_Button1, viveSource_LeftHand)); controllerRight.touch1.Update(GetButtonState(viveAction_Touch1, viveSource_RightHand)); controllerLeft.touch1.Update(GetButtonState(viveAction_Touch1, viveSource_LeftHand)); // update button/touch 2 controllerRight.button2.Update(GetButtonState(viveAction_Button2, viveSource_RightHand)); controllerLeft.button2.Update(GetButtonState(viveAction_Button2, viveSource_LeftHand)); controllerRight.touch2.Update(GetButtonState(viveAction_Touch2, viveSource_RightHand)); controllerLeft.touch2.Update(GetButtonState(viveAction_Touch2, viveSource_LeftHand)); // update grip if (controllerRight.type == XRInputControllerType.HTCVive || controllerRight.type == XRInputControllerType.WMR) { controllerRight.grip.Update(controllerRight.buttonGrip.on ? 1 : 0);// simulate analog state } else { controllerRight.grip.Update(GetAnalogState(viveAction_Grip, viveSource_RightHand).x); } if (controllerLeft.type == XRInputControllerType.HTCVive || controllerLeft.type == XRInputControllerType.WMR) { controllerLeft.grip.Update(controllerLeft.buttonGrip.on ? 1 : 0);// simulate analog state } else { controllerLeft.grip.Update(GetAnalogState(viveAction_Grip, viveSource_LeftHand).x); } // update triggers controllerRight.trigger.Update(GetAnalogState(viveAction_Trigger, viveSource_RightHand).x); controllerLeft.trigger.Update(GetAnalogState(viveAction_Trigger, viveSource_LeftHand).x); // update trackpads / touch / button if (controllerRight.type == XRInputControllerType.HTCVive) { controllerRight.joystick.Update(GetAnalogState(viveAction_Touchpad1, viveSource_RightHand)); controllerRight.buttonJoystick.Update(GetButtonState(viveAction_Touchpad1_Button, viveSource_RightHand)); } else { controllerRight.joystick2.Update(GetAnalogState(viveAction_Touchpad1, viveSource_RightHand)); controllerRight.buttonJoystick2.Update(GetButtonState(viveAction_Touchpad1_Button, viveSource_RightHand)); } if (controllerLeft.type == XRInputControllerType.HTCVive) { controllerLeft.joystick.Update(GetAnalogState(viveAction_Touchpad1, viveSource_LeftHand)); controllerLeft.buttonJoystick.Update(GetButtonState(viveAction_Touchpad1_Button, viveSource_LeftHand)); } else { controllerLeft.joystick2.Update(GetAnalogState(viveAction_Touchpad1, viveSource_LeftHand)); controllerLeft.buttonJoystick2.Update(GetButtonState(viveAction_Touchpad1_Button, viveSource_LeftHand)); } // update joysticks / touch / button if (controllerRight.type != XRInputControllerType.HTCVive) { controllerRight.joystick.Update(GetAnalogState(viveAction_Joystick1, viveSource_RightHand)); controllerRight.touchJoystick.Update(GetButtonState(viveAction_Joystick1_Touch, viveSource_RightHand)); controllerRight.buttonJoystick.Update(GetButtonState(viveAction_Joystick1_Button, viveSource_RightHand)); } if (controllerLeft.type != XRInputControllerType.HTCVive) { controllerLeft.joystick.Update(GetAnalogState(viveAction_Joystick1, viveSource_LeftHand)); controllerLeft.touchJoystick.Update(GetButtonState(viveAction_Joystick1_Touch, viveSource_LeftHand)); controllerLeft.buttonJoystick.Update(GetButtonState(viveAction_Joystick1_Button, viveSource_LeftHand)); } // copy back hand updates if (rightSet) { state_controllers[rightSetIndex] = controllerRight; } if (leftSet) { state_controllers[leftSetIndex] = controllerLeft; } return(true); }
private void VRInit() { // init var error = EVRInitError.None; system = OpenVR.Init(ref error); if (error != EVRInitError.None) { throw new Exception(); } OpenVR.GetGenericInterface(OpenVR.IVRSystem_Version, ref error); if (error != EVRInitError.None) { throw new Exception(); } TrackedDevicePose_t[] m_rTrackedDevicePose = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount]; TrackedDevicePose_t TrackedDevicePose = new TrackedDevicePose_t(); VRControllerState_t controllerState = new VRControllerState_t(); while (true) { system.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, m_rTrackedDevicePose); for (uint unDevice = 0; unDevice < OpenVR.k_unMaxTrackedDeviceCount; unDevice++) { if (!system.IsTrackedDeviceConnected(unDevice)) { continue; } HmdVector3_t position; HmdQuaternion_t quaternion; // Get what type of device it is and work with its data ETrackedDeviceClass trackedDeviceClass = system.GetTrackedDeviceClass(unDevice); ETrackedControllerRole trackedControllerRole = system.GetControllerRoleForTrackedDeviceIndex(unDevice); ETrackingResult eTrackingResult; switch (trackedDeviceClass) { case ETrackedDeviceClass.HMD: // get the position and rotation position = GetPosition(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking); quaternion = GetRotation(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking); // for printing some more info to the user about the state of the device/pose eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult; // print the tracking data Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { HmdIndex.Text = String.Format("{0}", unDevice); HmdVectorX.Text = String.Format("{0:F4}", position.v0); HmdVectorY.Text = String.Format("{0:F4}", position.v1); HmdVectorZ.Text = String.Format("{0:F4}", position.v2); HmdQuaternionX.Text = String.Format("{0:F4}", quaternion.x); HmdQuaternionY.Text = String.Format("{0:F4}", quaternion.y); HmdQuaternionZ.Text = String.Format("{0:F4}", quaternion.z); HmdQuaternionW.Text = String.Format("{0:F4}", quaternion.w); HmdState.Text = GetDeviceState(eTrackingResult); })); break; case ETrackedDeviceClass.Controller: // get the position and rotation position = GetPosition(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking); quaternion = GetRotation(m_rTrackedDevicePose[unDevice].mDeviceToAbsoluteTracking); // for printing some more info to the user about the state of the device/pose eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult; // get Controllers info system.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, unDevice, ref controllerState, (uint)Marshal.SizeOf(controllerState), ref TrackedDevicePose); switch (trackedControllerRole) { case ETrackedControllerRole.LeftHand: // print the tracking data Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { CLIndex.Text = String.Format("{0}", unDevice); CLVectorX.Text = String.Format("{0:F4}", position.v0); CLVectorY.Text = String.Format("{0:F4}", position.v1); CLVectorZ.Text = String.Format("{0:F4}", position.v2); CLQuaternionX.Text = String.Format("{0:F4}", quaternion.x); CLQuaternionY.Text = String.Format("{0:F4}", quaternion.y); CLQuaternionZ.Text = String.Format("{0:F4}", quaternion.z); CLQuaternionW.Text = String.Format("{0:F4}", quaternion.w); CLState.Text = GetDeviceState(eTrackingResult); CLulPressed.Text = String.Format("{0}", controllerState.ulButtonPressed); CLulTouched.Text = String.Format("{0}", controllerState.ulButtonTouched); CLAxis0X.Text = String.Format("{0:F4}", controllerState.rAxis0.x); CLAxis0Y.Text = String.Format("{0:F4}", controllerState.rAxis0.y); CLAxis1X.Text = String.Format("{0:F4}", controllerState.rAxis1.x); CLAxis1Y.Text = String.Format("{0:F4}", controllerState.rAxis1.y); CLAxis2X.Text = String.Format("{0:F4}", controllerState.rAxis2.x); CLAxis2Y.Text = String.Format("{0:F4}", controllerState.rAxis2.y); CLAxis3X.Text = String.Format("{0:F4}", controllerState.rAxis3.x); CLAxis3Y.Text = String.Format("{0:F4}", controllerState.rAxis3.y); CLAxis4X.Text = String.Format("{0:F4}", controllerState.rAxis4.x); CLAxis4Y.Text = String.Format("{0:F4}", controllerState.rAxis4.y); })); break; case ETrackedControllerRole.RightHand: // print the tracking data Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { CRIndex.Text = String.Format("{0}", unDevice); CRVectorX.Text = String.Format("{0:F4}", position.v0); CRVectorY.Text = String.Format("{0:F4}", position.v1); CRVectorZ.Text = String.Format("{0:F4}", position.v2); CRQuaternionX.Text = String.Format("{0:F4}", quaternion.x); CRQuaternionY.Text = String.Format("{0:F4}", quaternion.y); CRQuaternionZ.Text = String.Format("{0:F4}", quaternion.z); CRQuaternionW.Text = String.Format("{0:F4}", quaternion.w); CRState.Text = GetDeviceState(eTrackingResult); CRulPressed.Text = String.Format("{0}", controllerState.ulButtonPressed); CRulTouched.Text = String.Format("{0}", controllerState.ulButtonTouched); CRAxis0X.Text = String.Format("{0:F4}", controllerState.rAxis0.x); CRAxis0Y.Text = String.Format("{0:F4}", controllerState.rAxis0.y); CRAxis1X.Text = String.Format("{0:F4}", controllerState.rAxis1.x); CRAxis1Y.Text = String.Format("{0:F4}", controllerState.rAxis1.y); CRAxis2X.Text = String.Format("{0:F4}", controllerState.rAxis2.x); CRAxis2Y.Text = String.Format("{0:F4}", controllerState.rAxis2.y); CRAxis3X.Text = String.Format("{0:F4}", controllerState.rAxis3.x); CRAxis3Y.Text = String.Format("{0:F4}", controllerState.rAxis3.y); CRAxis4X.Text = String.Format("{0:F4}", controllerState.rAxis4.x); CRAxis4Y.Text = String.Format("{0:F4}", controllerState.rAxis4.y); })); break; } break; case ETrackedDeviceClass.GenericTracker: system.GetControllerStateWithPose(ETrackingUniverseOrigin.TrackingUniverseStanding, unDevice, ref controllerState, (uint)Marshal.SizeOf(controllerState), ref TrackedDevicePose); // get the position and rotation position = GetPosition(TrackedDevicePose.mDeviceToAbsoluteTracking); quaternion = GetRotation(TrackedDevicePose.mDeviceToAbsoluteTracking); // for printing some more info to the user about the state of the device/pose eTrackingResult = m_rTrackedDevicePose[unDevice].eTrackingResult; // print the tracking data Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate { TrackerIndex.Text = String.Format("{0}", unDevice); TrackerVectorX.Text = String.Format("{0:F4}", position.v0); TrackerVectorY.Text = String.Format("{0:F4}", position.v1); TrackerVectorZ.Text = String.Format("{0:F4}", position.v2); TrackerQuaternionX.Text = String.Format("{0:F4}", quaternion.x); TrackerQuaternionY.Text = String.Format("{0:F4}", quaternion.y); TrackerQuaternionZ.Text = String.Format("{0:F4}", quaternion.z); TrackerQuaternionW.Text = String.Format("{0:F4}", quaternion.w); TrackerState.Text = GetDeviceState(eTrackingResult); })); break; } Thread.Sleep(10); } } }
private async Task ParseTrackingFrameAsync(CancellationToken token) { try { for (uint i = 0; i < OpenVR.k_unMaxTrackedDeviceCount; i++) { if (!token.IsCancellationRequested) { TrackedDevicePose_t[] trackedDevicePose = new TrackedDevicePose_t[10]; if (!m_pHMD.IsTrackedDeviceConnected(i)) { continue; } ETrackedDeviceClass trackedDeviceClass = m_pHMD.GetTrackedDeviceClass(i); switch (trackedDeviceClass) { case ETrackedDeviceClass.HMD: m_pHMD.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseStanding, 0, trackedDevicePose); HmdVector3_t position = GetPosition(trackedDevicePose[0].mDeviceToAbsoluteTracking); // devicePose->mDeviceToAbsoluteTracking); HmdVector3_t rotation = GetRotationEuler(trackedDevicePose[0].mDeviceToAbsoluteTracking); int positionX = (int)position.v0; int positionY = (int)position.v1; int positionZ = (int)position.v2 * (-1); int rotationX = (int)rotation.v0 + 360; int rotationY = (int)rotation.v1 + 90; int rotationZ = (int)rotation.v2 * (-1); if (ControlViewModel.teleporOffset[0] != -1) { lock (ControlViewModel.teleporOffset) { ControlViewModel.transOffSetHeadX = ControlViewModel.teleporOffset[0]; ControlViewModel.transOffSetHeadY = ControlViewModel.teleporOffset[1]; ControlViewModel.transOffSetHeadZ = ControlViewModel.teleporOffset[2]; ControlViewModel.rotOffSetHeadZ = ControlViewModel.teleporOffset[3]; } } if (communicationProtocolUdp == false) { MessageBuffer mb = new MessageBuffer(); int type = 100; string ipAdress = ServerManager.clientIpAddressForTracking; mb.add(type); mb.add(userId); mb.add(ipAdress); mb.add(positionX + ControlViewModel.transOffSetHeadX); mb.add(positionY + ControlViewModel.transOffSetHeadY); mb.add(positionZ + ControlViewModel.transOffSetHeadZ); mb.add(rotationX - ControlViewModel.rotOffSetHeadZ); mb.add(rotationY); mb.add(rotationZ); Message msg = new Message(mb, Message.MessagesType.COVISE_MESSAGE_VRB_MESSAGE); lock (tcpSocketManager.send_msg(msg)) { tcpSocketManager.send_msg(msg); } Thread.Sleep(20); break; } break; } } } } catch (Exception e) { log.Warn("ParseTrackingFrameAsync in Hmd Tracking wurde beendet!"); RaiseSampleEvent(new TrackingChangedEventArgs(e)); } }
public bool IsDeviceConnected(uint idx) { ReadyCheck(); //実行可能な状態かチェック return(openvr.IsTrackedDeviceConnected(idx)); }
public bool IsConnected(int deviceIndex) => hmd.IsTrackedDeviceConnected((uint)deviceIndex);