OVRInputModule.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. /************************************************************************************
  2. Copyright : Copyright 2017 Oculus VR, LLC. All Rights reserved.
  3. Licensed under the Oculus VR Rift SDK License Version 3.4.1 (the "License");
  4. you may not use the Oculus VR Rift SDK except in compliance with the License,
  5. which is provided at the time of installation or download, or which
  6. otherwise accompanies this software in either electronic or hard copy form.
  7. You may obtain a copy of the License at
  8. https://developer.oculus.com/licenses/sdk-3.4.1
  9. Unless required by applicable law or agreed to in writing, the Oculus VR SDK
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ************************************************************************************/
  15. using System;
  16. using System.Collections.Generic;
  17. namespace UnityEngine.EventSystems
  18. {
  19. /// <summary>
  20. /// VR extension of PointerInputModule which supports gaze and controller pointing.
  21. /// </summary>
  22. public class OVRInputModule : PointerInputModule
  23. {
  24. [Tooltip("Object which points with Z axis. E.g. CentreEyeAnchor from OVRCameraRig")]
  25. public Transform rayTransform;
  26. [Tooltip("Gamepad button to act as gaze click")]
  27. public OVRInput.Button joyPadClickButton = OVRInput.Button.One;
  28. [Tooltip("Keyboard button to act as gaze click")]
  29. public KeyCode gazeClickKey = KeyCode.Space;
  30. [Header("Physics")]
  31. [Tooltip("Perform an sphere cast to determine correct depth for gaze pointer")]
  32. public bool performSphereCastForGazepointer;
  33. [Tooltip("Match the gaze pointer normal to geometry normal for physics colliders")]
  34. public bool matchNormalOnPhysicsColliders;
  35. [Header("Gamepad Stick Scroll")]
  36. [Tooltip("Enable scrolling with the right stick on a gamepad")]
  37. public bool useRightStickScroll = true;
  38. [Tooltip("Deadzone for right stick to prevent accidental scrolling")]
  39. public float rightStickDeadZone = 0.15f;
  40. [Header("Touchpad Swipe Scroll")]
  41. [Tooltip("Enable scrolling by swiping the GearVR touchpad")]
  42. public bool useSwipeScroll = true;
  43. [Tooltip("Minimum trackpad movement in pixels to start swiping")]
  44. public float swipeDragThreshold = 2;
  45. [Tooltip("Distance scrolled when swipe scroll occurs")]
  46. public float swipeDragScale = 1f;
  47. /* It's debatable which way left and right are on the Gear VR touchpad since it's facing away from you
  48. * the following bool allows this to be swapped*/
  49. [Tooltip("Invert X axis on touchpad")]
  50. public bool InvertSwipeXAxis = false;
  51. // The raycaster that gets to do pointer interaction (e.g. with a mouse), gaze interaction always works
  52. [NonSerialized]
  53. public OVRRaycaster activeGraphicRaycaster;
  54. [Header("Dragging")]
  55. [Tooltip("Minimum pointer movement in degrees to start dragging")]
  56. public float angleDragThreshold = 1;
  57. // The following region contains code exactly the same as the implementation
  58. // of StandaloneInputModule. It is copied here rather than inheriting from StandaloneInputModule
  59. // because most of StandaloneInputModule is private so it isn't possible to easily derive from.
  60. // Future changes from Unity to StandaloneInputModule will make it possible for this class to
  61. // derive from StandaloneInputModule instead of PointerInput module.
  62. //
  63. // The following functions are not present in the following region since they have modified
  64. // versions in the next region:
  65. // Process
  66. // ProcessMouseEvent
  67. // UseMouse
  68. #region StandaloneInputModule code
  69. private float m_NextAction;
  70. private Vector2 m_LastMousePosition;
  71. private Vector2 m_MousePosition;
  72. protected OVRInputModule()
  73. {}
  74. #if UNITY_EDITOR
  75. protected override void Reset()
  76. {
  77. allowActivationOnMobileDevice = true;
  78. }
  79. #endif
  80. [Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
  81. public enum InputMode
  82. {
  83. Mouse,
  84. Buttons
  85. }
  86. [Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
  87. public InputMode inputMode
  88. {
  89. get { return InputMode.Mouse; }
  90. }
  91. [Header("Standalone Input Module")]
  92. [SerializeField]
  93. private string m_HorizontalAxis = "Horizontal";
  94. /// <summary>
  95. /// Name of the vertical axis for movement (if axis events are used).
  96. /// </summary>
  97. [SerializeField]
  98. private string m_VerticalAxis = "Vertical";
  99. /// <summary>
  100. /// Name of the submit button.
  101. /// </summary>
  102. [SerializeField]
  103. private string m_SubmitButton = "Submit";
  104. /// <summary>
  105. /// Name of the submit button.
  106. /// </summary>
  107. [SerializeField]
  108. private string m_CancelButton = "Cancel";
  109. [SerializeField]
  110. private float m_InputActionsPerSecond = 10;
  111. [SerializeField]
  112. private bool m_AllowActivationOnMobileDevice;
  113. public bool allowActivationOnMobileDevice
  114. {
  115. get { return m_AllowActivationOnMobileDevice; }
  116. set { m_AllowActivationOnMobileDevice = value; }
  117. }
  118. public float inputActionsPerSecond
  119. {
  120. get { return m_InputActionsPerSecond; }
  121. set { m_InputActionsPerSecond = value; }
  122. }
  123. /// <summary>
  124. /// Name of the horizontal axis for movement (if axis events are used).
  125. /// </summary>
  126. public string horizontalAxis
  127. {
  128. get { return m_HorizontalAxis; }
  129. set { m_HorizontalAxis = value; }
  130. }
  131. /// <summary>
  132. /// Name of the vertical axis for movement (if axis events are used).
  133. /// </summary>
  134. public string verticalAxis
  135. {
  136. get { return m_VerticalAxis; }
  137. set { m_VerticalAxis = value; }
  138. }
  139. public string submitButton
  140. {
  141. get { return m_SubmitButton; }
  142. set { m_SubmitButton = value; }
  143. }
  144. public string cancelButton
  145. {
  146. get { return m_CancelButton; }
  147. set { m_CancelButton = value; }
  148. }
  149. public override void UpdateModule()
  150. {
  151. m_LastMousePosition = m_MousePosition;
  152. m_MousePosition = Input.mousePosition;
  153. }
  154. public override bool IsModuleSupported()
  155. {
  156. // Check for mouse presence instead of whether touch is supported,
  157. // as you can connect mouse to a tablet and in that case we'd want
  158. // to use StandaloneInputModule for non-touch input events.
  159. return m_AllowActivationOnMobileDevice || Input.mousePresent;
  160. }
  161. public override bool ShouldActivateModule()
  162. {
  163. if (!base.ShouldActivateModule())
  164. return false;
  165. var shouldActivate = Input.GetButtonDown(m_SubmitButton);
  166. shouldActivate |= Input.GetButtonDown(m_CancelButton);
  167. shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_HorizontalAxis), 0.0f);
  168. shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_VerticalAxis), 0.0f);
  169. shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
  170. shouldActivate |= Input.GetMouseButtonDown(0);
  171. return shouldActivate;
  172. }
  173. public override void ActivateModule()
  174. {
  175. base.ActivateModule();
  176. m_MousePosition = Input.mousePosition;
  177. m_LastMousePosition = Input.mousePosition;
  178. var toSelect = eventSystem.currentSelectedGameObject;
  179. if (toSelect == null)
  180. toSelect = eventSystem.firstSelectedGameObject;
  181. eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
  182. }
  183. public override void DeactivateModule()
  184. {
  185. base.DeactivateModule();
  186. ClearSelection();
  187. }
  188. /// <summary>
  189. /// Process submit keys.
  190. /// </summary>
  191. private bool SendSubmitEventToSelectedObject()
  192. {
  193. if (eventSystem.currentSelectedGameObject == null)
  194. return false;
  195. var data = GetBaseEventData();
  196. if (Input.GetButtonDown(m_SubmitButton))
  197. ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
  198. if (Input.GetButtonDown(m_CancelButton))
  199. ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
  200. return data.used;
  201. }
  202. private bool AllowMoveEventProcessing(float time)
  203. {
  204. bool allow = Input.GetButtonDown(m_HorizontalAxis);
  205. allow |= Input.GetButtonDown(m_VerticalAxis);
  206. allow |= (time > m_NextAction);
  207. return allow;
  208. }
  209. private Vector2 GetRawMoveVector()
  210. {
  211. Vector2 move = Vector2.zero;
  212. move.x = Input.GetAxisRaw(m_HorizontalAxis);
  213. move.y = Input.GetAxisRaw(m_VerticalAxis);
  214. if (Input.GetButtonDown(m_HorizontalAxis))
  215. {
  216. if (move.x < 0)
  217. move.x = -1f;
  218. if (move.x > 0)
  219. move.x = 1f;
  220. }
  221. if (Input.GetButtonDown(m_VerticalAxis))
  222. {
  223. if (move.y < 0)
  224. move.y = -1f;
  225. if (move.y > 0)
  226. move.y = 1f;
  227. }
  228. return move;
  229. }
  230. /// <summary>
  231. /// Process keyboard events.
  232. /// </summary>
  233. private bool SendMoveEventToSelectedObject()
  234. {
  235. float time = Time.unscaledTime;
  236. if (!AllowMoveEventProcessing(time))
  237. return false;
  238. Vector2 movement = GetRawMoveVector();
  239. // Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")");
  240. var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
  241. if (!Mathf.Approximately(axisEventData.moveVector.x, 0f)
  242. || !Mathf.Approximately(axisEventData.moveVector.y, 0f))
  243. {
  244. ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
  245. }
  246. m_NextAction = time + 1f / m_InputActionsPerSecond;
  247. return axisEventData.used;
  248. }
  249. private bool SendUpdateEventToSelectedObject()
  250. {
  251. if (eventSystem.currentSelectedGameObject == null)
  252. return false;
  253. var data = GetBaseEventData();
  254. ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
  255. return data.used;
  256. }
  257. /// <summary>
  258. /// Process the current mouse press.
  259. /// </summary>
  260. private void ProcessMousePress(MouseButtonEventData data)
  261. {
  262. var pointerEvent = data.buttonData;
  263. var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
  264. // PointerDown notification
  265. if (data.PressedThisFrame())
  266. {
  267. pointerEvent.eligibleForClick = true;
  268. pointerEvent.delta = Vector2.zero;
  269. pointerEvent.dragging = false;
  270. pointerEvent.useDragThreshold = true;
  271. pointerEvent.pressPosition = pointerEvent.position;
  272. if (pointerEvent.IsVRPointer())
  273. {
  274. pointerEvent.SetSwipeStart(Input.mousePosition);
  275. }
  276. pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
  277. DeselectIfSelectionChanged(currentOverGo, pointerEvent);
  278. // search for the control that will receive the press
  279. // if we can't find a press handler set the press
  280. // handler to be what would receive a click.
  281. var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
  282. // didnt find a press handler... search for a click handler
  283. if (newPressed == null)
  284. newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
  285. // Debug.Log("Pressed: " + newPressed);
  286. float time = Time.unscaledTime;
  287. if (newPressed == pointerEvent.lastPress)
  288. {
  289. var diffTime = time - pointerEvent.clickTime;
  290. if (diffTime < 0.3f)
  291. ++pointerEvent.clickCount;
  292. else
  293. pointerEvent.clickCount = 1;
  294. pointerEvent.clickTime = time;
  295. }
  296. else
  297. {
  298. pointerEvent.clickCount = 1;
  299. }
  300. pointerEvent.pointerPress = newPressed;
  301. pointerEvent.rawPointerPress = currentOverGo;
  302. pointerEvent.clickTime = time;
  303. // Save the drag handler as well
  304. pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
  305. if (pointerEvent.pointerDrag != null)
  306. ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
  307. }
  308. // PointerUp notification
  309. if (data.ReleasedThisFrame())
  310. {
  311. // Debug.Log("Executing pressup on: " + pointer.pointerPress);
  312. ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
  313. // Debug.Log("KeyCode: " + pointer.eventData.keyCode);
  314. // see if we mouse up on the same element that we clicked on...
  315. var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
  316. // PointerClick and Drop events
  317. if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
  318. {
  319. ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
  320. }
  321. else if (pointerEvent.pointerDrag != null)
  322. {
  323. ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
  324. }
  325. pointerEvent.eligibleForClick = false;
  326. pointerEvent.pointerPress = null;
  327. pointerEvent.rawPointerPress = null;
  328. if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
  329. ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
  330. pointerEvent.dragging = false;
  331. pointerEvent.pointerDrag = null;
  332. // redo pointer enter / exit to refresh state
  333. // so that if we moused over somethign that ignored it before
  334. // due to having pressed on something else
  335. // it now gets it.
  336. if (currentOverGo != pointerEvent.pointerEnter)
  337. {
  338. HandlePointerExitAndEnter(pointerEvent, null);
  339. HandlePointerExitAndEnter(pointerEvent, currentOverGo);
  340. }
  341. }
  342. }
  343. #endregion
  344. #region Modified StandaloneInputModule methods
  345. /// <summary>
  346. /// Process all mouse events. This is the same as the StandaloneInputModule version except that
  347. /// it takes MouseState as a parameter, allowing it to be used for both Gaze and Mouse
  348. /// pointerss.
  349. /// </summary>
  350. private void ProcessMouseEvent(MouseState mouseData)
  351. {
  352. var pressed = mouseData.AnyPressesThisFrame();
  353. var released = mouseData.AnyReleasesThisFrame();
  354. var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
  355. if (!UseMouse(pressed, released, leftButtonData.buttonData))
  356. return;
  357. // Process the first mouse button fully
  358. ProcessMousePress(leftButtonData);
  359. ProcessMove(leftButtonData.buttonData);
  360. ProcessDrag(leftButtonData.buttonData);
  361. // Now process right / middle clicks
  362. ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
  363. ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
  364. ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
  365. ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
  366. if (!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
  367. {
  368. var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
  369. ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
  370. }
  371. }
  372. /// <summary>
  373. /// Process this InputModule. Same as the StandaloneInputModule version, except that it calls
  374. /// ProcessMouseEvent twice, once for gaze pointers, and once for mouse pointers.
  375. /// </summary>
  376. public override void Process()
  377. {
  378. bool usedEvent = SendUpdateEventToSelectedObject();
  379. if (eventSystem.sendNavigationEvents)
  380. {
  381. if (!usedEvent)
  382. usedEvent |= SendMoveEventToSelectedObject();
  383. if (!usedEvent)
  384. SendSubmitEventToSelectedObject();
  385. }
  386. ProcessMouseEvent(GetGazePointerData());
  387. #if !UNITY_ANDROID
  388. ProcessMouseEvent(GetCanvasPointerData());
  389. #endif
  390. }
  391. /// <summary>
  392. /// Decide if mouse events need to be processed this frame. Same as StandloneInputModule except
  393. /// that the IsPointerMoving method from this class is used, instead of the method on PointerEventData
  394. /// </summary>
  395. private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData)
  396. {
  397. if (pressed || released || IsPointerMoving(pointerData) || pointerData.IsScrolling())
  398. return true;
  399. return false;
  400. }
  401. #endregion
  402. /// <summary>
  403. /// Convenience function for cloning PointerEventData
  404. /// </summary>
  405. /// <param name="from">Copy this value</param>
  406. /// <param name="to">to this object</param>
  407. protected void CopyFromTo(OVRPointerEventData @from, OVRPointerEventData @to)
  408. {
  409. @to.position = @from.position;
  410. @to.delta = @from.delta;
  411. @to.scrollDelta = @from.scrollDelta;
  412. @to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
  413. @to.pointerEnter = @from.pointerEnter;
  414. @to.worldSpaceRay = @from.worldSpaceRay;
  415. }
  416. /// <summary>
  417. /// Convenience function for cloning PointerEventData
  418. /// </summary>
  419. /// <param name="from">Copy this value</param>
  420. /// <param name="to">to this object</param>
  421. protected new void CopyFromTo(PointerEventData @from, PointerEventData @to)
  422. {
  423. @to.position = @from.position;
  424. @to.delta = @from.delta;
  425. @to.scrollDelta = @from.scrollDelta;
  426. @to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
  427. @to.pointerEnter = @from.pointerEnter;
  428. }
  429. // In the following region we extend the PointerEventData system implemented in PointerInputModule
  430. // We define an additional dictionary for ray(e.g. gaze) based pointers. Mouse pointers still use the dictionary
  431. // in PointerInputModule
  432. #region PointerEventData pool
  433. // Pool for OVRRayPointerEventData for ray based pointers
  434. protected Dictionary<int, OVRPointerEventData> m_VRRayPointerData = new Dictionary<int, OVRPointerEventData>();
  435. protected bool GetPointerData(int id, out OVRPointerEventData data, bool create)
  436. {
  437. if (!m_VRRayPointerData.TryGetValue(id, out data) && create)
  438. {
  439. data = new OVRPointerEventData(eventSystem)
  440. {
  441. pointerId = id,
  442. };
  443. m_VRRayPointerData.Add(id, data);
  444. return true;
  445. }
  446. return false;
  447. }
  448. /// <summary>
  449. /// Clear pointer state for both types of pointer
  450. /// </summary>
  451. protected new void ClearSelection()
  452. {
  453. var baseEventData = GetBaseEventData();
  454. foreach (var pointer in m_PointerData.Values)
  455. {
  456. // clear all selection
  457. HandlePointerExitAndEnter(pointer, null);
  458. }
  459. foreach (var pointer in m_VRRayPointerData.Values)
  460. {
  461. // clear all selection
  462. HandlePointerExitAndEnter(pointer, null);
  463. }
  464. m_PointerData.Clear();
  465. eventSystem.SetSelectedGameObject(null, baseEventData);
  466. }
  467. #endregion
  468. /// <summary>
  469. /// For RectTransform, calculate it's normal in world space
  470. /// </summary>
  471. static Vector3 GetRectTransformNormal(RectTransform rectTransform)
  472. {
  473. Vector3[] corners = new Vector3[4];
  474. rectTransform.GetWorldCorners(corners);
  475. Vector3 BottomEdge = corners[3] - corners[0];
  476. Vector3 LeftEdge = corners[1] - corners[0];
  477. rectTransform.GetWorldCorners(corners);
  478. return Vector3.Cross(BottomEdge, LeftEdge).normalized;
  479. }
  480. private readonly MouseState m_MouseState = new MouseState();
  481. // The following 2 functions are equivalent to PointerInputModule.GetMousePointerEventData but are customized to
  482. // get data for ray pointers and canvas mouse pointers.
  483. /// <summary>
  484. /// State for a pointer controlled by a world space ray. E.g. gaze pointer
  485. /// </summary>
  486. /// <returns></returns>
  487. virtual protected MouseState GetGazePointerData()
  488. {
  489. // Get the OVRRayPointerEventData reference
  490. OVRPointerEventData leftData;
  491. GetPointerData(kMouseLeftId, out leftData, true );
  492. leftData.Reset();
  493. //Now set the world space ray. This ray is what the user uses to point at UI elements
  494. leftData.worldSpaceRay = new Ray(rayTransform.position, rayTransform.forward);
  495. leftData.scrollDelta = GetExtraScrollDelta();
  496. //Populate some default values
  497. leftData.button = PointerEventData.InputButton.Left;
  498. leftData.useDragThreshold = true;
  499. // Perform raycast to find intersections with world
  500. eventSystem.RaycastAll(leftData, m_RaycastResultCache);
  501. var raycast = FindFirstRaycast(m_RaycastResultCache);
  502. leftData.pointerCurrentRaycast = raycast;
  503. m_RaycastResultCache.Clear();
  504. OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
  505. // We're only interested in intersections from OVRRaycasters
  506. if (ovrRaycaster)
  507. {
  508. // The Unity UI system expects event data to have a screen position
  509. // so even though this raycast came from a world space ray we must get a screen
  510. // space position for the camera attached to this raycaster for compatability
  511. leftData.position = ovrRaycaster.GetScreenPosition(raycast);
  512. // Find the world position and normal the Graphic the ray intersected
  513. RectTransform graphicRect = raycast.gameObject.GetComponent<RectTransform>();
  514. if (graphicRect != null)
  515. {
  516. // Set are gaze indicator with this world position and normal
  517. Vector3 worldPos = raycast.worldPosition;
  518. Vector3 normal = GetRectTransformNormal(graphicRect);
  519. OVRGazePointer.instance.SetPosition(worldPos, normal);
  520. // Make sure it's being shown
  521. OVRGazePointer.instance.RequestShow();
  522. }
  523. }
  524. // Now process physical raycast intersections
  525. OVRPhysicsRaycaster physicsRaycaster = raycast.module as OVRPhysicsRaycaster;
  526. if (physicsRaycaster)
  527. {
  528. Vector3 position = raycast.worldPosition;
  529. if (performSphereCastForGazepointer)
  530. {
  531. // Here we cast a sphere into the scene rather than a ray. This gives a more accurate depth
  532. // for positioning a circular gaze pointer
  533. List<RaycastResult> results = new List<RaycastResult>();
  534. physicsRaycaster.Spherecast(leftData, results, OVRGazePointer.instance.GetCurrentRadius());
  535. if (results.Count > 0 && results[0].distance < raycast.distance)
  536. {
  537. position = results[0].worldPosition;
  538. }
  539. }
  540. leftData.position = physicsRaycaster.GetScreenPos(raycast.worldPosition);
  541. // Show the cursor while pointing at an interactable object
  542. OVRGazePointer.instance.RequestShow();
  543. if (matchNormalOnPhysicsColliders)
  544. {
  545. OVRGazePointer.instance.SetPosition(position, raycast.worldNormal);
  546. }
  547. else
  548. {
  549. OVRGazePointer.instance.SetPosition(position);
  550. }
  551. }
  552. // Stick default data values in right and middle slots for compatability
  553. // copy the apropriate data into right and middle slots
  554. OVRPointerEventData rightData;
  555. GetPointerData(kMouseRightId, out rightData, true );
  556. CopyFromTo(leftData, rightData);
  557. rightData.button = PointerEventData.InputButton.Right;
  558. OVRPointerEventData middleData;
  559. GetPointerData(kMouseMiddleId, out middleData, true );
  560. CopyFromTo(leftData, middleData);
  561. middleData.button = PointerEventData.InputButton.Middle;
  562. m_MouseState.SetButtonState(PointerEventData.InputButton.Left, GetGazeButtonState(), leftData);
  563. m_MouseState.SetButtonState(PointerEventData.InputButton.Right, PointerEventData.FramePressState.NotChanged, rightData);
  564. m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, PointerEventData.FramePressState.NotChanged, middleData);
  565. return m_MouseState;
  566. }
  567. /// <summary>
  568. /// Get state for pointer which is a pointer moving in world space across the surface of a world space canvas.
  569. /// </summary>
  570. /// <returns></returns>
  571. protected MouseState GetCanvasPointerData()
  572. {
  573. // Get the OVRRayPointerEventData reference
  574. PointerEventData leftData;
  575. GetPointerData(kMouseLeftId, out leftData, true );
  576. leftData.Reset();
  577. // Setup default values here. Set position to zero because we don't actually know the pointer
  578. // positions. Each canvas knows the position of its canvas pointer.
  579. leftData.position = Vector2.zero;
  580. leftData.scrollDelta = Input.mouseScrollDelta;
  581. leftData.button = PointerEventData.InputButton.Left;
  582. if (activeGraphicRaycaster)
  583. {
  584. // Let the active raycaster find intersections on its canvas
  585. activeGraphicRaycaster.RaycastPointer(leftData, m_RaycastResultCache);
  586. var raycast = FindFirstRaycast(m_RaycastResultCache);
  587. leftData.pointerCurrentRaycast = raycast;
  588. m_RaycastResultCache.Clear();
  589. OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
  590. if (ovrRaycaster) // raycast may not actually contain a result
  591. {
  592. // The Unity UI system expects event data to have a screen position
  593. // so even though this raycast came from a world space ray we must get a screen
  594. // space position for the camera attached to this raycaster for compatability
  595. Vector2 position = ovrRaycaster.GetScreenPosition(raycast);
  596. leftData.delta = position - leftData.position;
  597. leftData.position = position;
  598. }
  599. }
  600. // copy the apropriate data into right and middle slots
  601. PointerEventData rightData;
  602. GetPointerData(kMouseRightId, out rightData, true );
  603. CopyFromTo(leftData, rightData);
  604. rightData.button = PointerEventData.InputButton.Right;
  605. PointerEventData middleData;
  606. GetPointerData(kMouseMiddleId, out middleData, true );
  607. CopyFromTo(leftData, middleData);
  608. middleData.button = PointerEventData.InputButton.Middle;
  609. m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
  610. m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
  611. m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);
  612. return m_MouseState;
  613. }
  614. /// <summary>
  615. /// New version of ShouldStartDrag implemented first in PointerInputModule. This version differs in that
  616. /// for ray based pointers it makes a decision about whether a drag should start based on the angular change
  617. /// the pointer has made so far, as seen from the camera. This also works when the world space ray is
  618. /// translated rather than rotated, since the beginning and end of the movement are considered as angle from
  619. /// the same point.
  620. /// </summary>
  621. private bool ShouldStartDrag(PointerEventData pointerEvent)
  622. {
  623. if (!pointerEvent.useDragThreshold)
  624. return true;
  625. if (!pointerEvent.IsVRPointer())
  626. {
  627. // Same as original behaviour for canvas based pointers
  628. return (pointerEvent.pressPosition - pointerEvent.position).sqrMagnitude >= eventSystem.pixelDragThreshold * eventSystem.pixelDragThreshold;
  629. }
  630. else
  631. {
  632. #if UNITY_ANDROID && !UNITY_EDITOR // On android allow swiping to start drag
  633. if (useSwipeScroll && ((Vector3)pointerEvent.GetSwipeStart() - Input.mousePosition).magnitude > swipeDragThreshold)
  634. {
  635. return true;
  636. }
  637. #endif
  638. // When it's not a screen space pointer we have to look at the angle it moved rather than the pixels distance
  639. // For gaze based pointing screen-space distance moved will always be near 0
  640. Vector3 cameraPos = pointerEvent.pressEventCamera.transform.position;
  641. Vector3 pressDir = (pointerEvent.pointerPressRaycast.worldPosition - cameraPos).normalized;
  642. Vector3 currentDir = (pointerEvent.pointerCurrentRaycast.worldPosition - cameraPos).normalized;
  643. return Vector3.Dot(pressDir, currentDir) < Mathf.Cos(Mathf.Deg2Rad * (angleDragThreshold));
  644. }
  645. }
  646. /// <summary>
  647. /// The purpose of this function is to allow us to switch between using the standard IsPointerMoving
  648. /// method for mouse driven pointers, but to always return true when it's a ray based pointer.
  649. /// All real-world ray-based input devices are always moving so for simplicity we just return true
  650. /// for them.
  651. ///
  652. /// If PointerEventData.IsPointerMoving was virtual we could just override that in
  653. /// OVRRayPointerEventData.
  654. /// </summary>
  655. /// <param name="pointerEvent"></param>
  656. /// <returns></returns>
  657. static bool IsPointerMoving(PointerEventData pointerEvent)
  658. {
  659. if (pointerEvent.IsVRPointer())
  660. return true;
  661. else
  662. return pointerEvent.IsPointerMoving();
  663. }
  664. protected Vector2 SwipeAdjustedPosition(Vector2 originalPosition, PointerEventData pointerEvent)
  665. {
  666. #if UNITY_ANDROID && !UNITY_EDITOR
  667. // On android we use the touchpad position (accessed through Input.mousePosition) to modify
  668. // the effective cursor position for events related to dragging. This allows the user to
  669. // use the touchpad to drag draggable UI elements
  670. if (useSwipeScroll)
  671. {
  672. Vector2 delta = (Vector2)Input.mousePosition - pointerEvent.GetSwipeStart();
  673. if (InvertSwipeXAxis)
  674. delta.x *= -1;
  675. return originalPosition + delta * swipeDragScale;
  676. }
  677. #endif
  678. // If not Gear VR or swipe scroll isn't enabled just return original position
  679. return originalPosition;
  680. }
  681. /// <summary>
  682. /// Exactly the same as the code from PointerInputModule, except that we call our own
  683. /// IsPointerMoving.
  684. ///
  685. /// This would also not be necessary if PointerEventData.IsPointerMoving was virtual
  686. /// </summary>
  687. /// <param name="pointerEvent"></param>
  688. protected override void ProcessDrag(PointerEventData pointerEvent)
  689. {
  690. Vector2 originalPosition = pointerEvent.position;
  691. bool moving = IsPointerMoving(pointerEvent);
  692. if (moving && pointerEvent.pointerDrag != null
  693. && !pointerEvent.dragging
  694. && ShouldStartDrag(pointerEvent))
  695. {
  696. if (pointerEvent.IsVRPointer())
  697. {
  698. //adjust the position used based on swiping action. Allowing the user to
  699. //drag items by swiping on the GearVR touchpad
  700. pointerEvent.position = SwipeAdjustedPosition (originalPosition, pointerEvent);
  701. }
  702. ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.beginDragHandler);
  703. pointerEvent.dragging = true;
  704. }
  705. // Drag notification
  706. if (pointerEvent.dragging && moving && pointerEvent.pointerDrag != null)
  707. {
  708. if (pointerEvent.IsVRPointer())
  709. {
  710. pointerEvent.position = SwipeAdjustedPosition(originalPosition, pointerEvent);
  711. }
  712. // Before doing drag we should cancel any pointer down state
  713. // And clear selection!
  714. if (pointerEvent.pointerPress != pointerEvent.pointerDrag)
  715. {
  716. ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
  717. pointerEvent.eligibleForClick = false;
  718. pointerEvent.pointerPress = null;
  719. pointerEvent.rawPointerPress = null;
  720. }
  721. ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.dragHandler);
  722. }
  723. }
  724. /// <summary>
  725. /// Get state of button corresponding to gaze pointer
  726. /// </summary>
  727. /// <returns></returns>
  728. virtual protected PointerEventData.FramePressState GetGazeButtonState()
  729. {
  730. var pressed = Input.GetKeyDown(gazeClickKey) || OVRInput.GetDown(joyPadClickButton);
  731. var released = Input.GetKeyUp(gazeClickKey) || OVRInput.GetUp(joyPadClickButton);
  732. #if UNITY_ANDROID && !UNITY_EDITOR
  733. // On Gear VR the mouse button events correspond to touch pad events. We only use these as gaze pointer clicks
  734. // on Gear VR because on PC the mouse clicks are used for actual mouse pointer interactions.
  735. pressed |= Input.GetMouseButtonDown(0);
  736. released |= Input.GetMouseButtonUp(0);
  737. #endif
  738. if (pressed && released)
  739. return PointerEventData.FramePressState.PressedAndReleased;
  740. if (pressed)
  741. return PointerEventData.FramePressState.Pressed;
  742. if (released)
  743. return PointerEventData.FramePressState.Released;
  744. return PointerEventData.FramePressState.NotChanged;
  745. }
  746. /// <summary>
  747. /// Get extra scroll delta from gamepad
  748. /// </summary>
  749. protected Vector2 GetExtraScrollDelta()
  750. {
  751. Vector2 scrollDelta = new Vector2();
  752. if (useRightStickScroll)
  753. {
  754. Vector2 s = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
  755. if (Mathf.Abs(s.x) < rightStickDeadZone) s.x = 0;
  756. if (Mathf.Abs(s.y) < rightStickDeadZone) s.y = 0;
  757. scrollDelta = s;
  758. }
  759. return scrollDelta;
  760. }
  761. };
  762. }