NRInputModule.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal
  10. {
  11. using System;
  12. using System.Collections;
  13. using System.Collections.Generic;
  14. using UnityEngine;
  15. using UnityEngine.EventSystems;
  16. /// <summary> A nr input module. </summary>
  17. public class NRInputModule : BaseInputModule
  18. {
  19. /// <summary> The processed frame. </summary>
  20. private int m_processedFrame;
  21. /// <summary> The raycasters. </summary>
  22. private static readonly List<NRPointerRaycaster> raycasters = new List<NRPointerRaycaster>();
  23. /// <summary> Gets a value indicating whether the active. </summary>
  24. /// <value> True if active, false if not. </value>
  25. public static bool Active { get { return m_Instance != null; } }
  26. /// <summary> Gets the screen center point. </summary>
  27. /// <value> The screen center point. </value>
  28. public static Vector2 ScreenCenterPoint { get { return new Vector2(Screen.width * 0.5f, Screen.height * 0.5f); } }
  29. /// <summary> True if is application quitting, false if not. </summary>
  30. private static bool isApplicationQuitting = false;
  31. /// <summary> The instance. </summary>
  32. private static NRInputModule m_Instance;
  33. /// <summary> Gets the instance. </summary>
  34. /// <value> The instance. </value>
  35. public static NRInputModule Instance
  36. {
  37. get
  38. {
  39. Initialize();
  40. return m_Instance;
  41. }
  42. }
  43. /// <summary> <para>Update the internal state of the Module.</para> </summary>
  44. public override void UpdateModule()
  45. {
  46. Initialize();
  47. if (isActiveAndEnabled && EventSystem.current.currentInputModule != this)
  48. {
  49. ProcessRaycast();
  50. }
  51. }
  52. /// <summary> Process the raycast. </summary>
  53. protected virtual void ProcessRaycast()
  54. {
  55. if (m_processedFrame == Time.frameCount)
  56. return;
  57. m_processedFrame = Time.frameCount;
  58. RaycastAll();
  59. }
  60. /// <summary> Raycast all. </summary>
  61. private void RaycastAll()
  62. {
  63. for (int i = 0; i < raycasters.Count; i++)
  64. {
  65. var raycaster = raycasters[i];
  66. if (raycaster == null)
  67. continue;
  68. raycaster.Raycast();
  69. var result = raycaster.FirstRaycastResult();
  70. var scrollDelta = raycaster.GetScrollDelta();
  71. var raycasterPos = raycaster.BreakPoints[0];
  72. var raycasterRot = raycaster.transform.rotation;
  73. var hoverEventData = raycaster.HoverEventData;
  74. if (hoverEventData == null)
  75. continue;
  76. hoverEventData.Reset();
  77. hoverEventData.delta = Vector2.zero;
  78. hoverEventData.scrollDelta = scrollDelta;
  79. hoverEventData.position = ScreenCenterPoint;
  80. hoverEventData.pointerCurrentRaycast = result;
  81. hoverEventData.position3DDelta = raycasterPos - hoverEventData.position3D;
  82. hoverEventData.position3D = raycasterPos;
  83. hoverEventData.rotationDelta = Quaternion.Inverse(hoverEventData.rotation) * raycasterRot;
  84. hoverEventData.rotation = raycasterRot;
  85. for (int j = 0, jmax = raycaster.ButtonEventDataList.Count; j < jmax; ++j)
  86. {
  87. var buttonEventData = raycaster.ButtonEventDataList[j];
  88. if (buttonEventData == null || buttonEventData == hoverEventData)
  89. continue;
  90. buttonEventData.Reset();
  91. buttonEventData.delta = Vector2.zero;
  92. buttonEventData.scrollDelta = scrollDelta;
  93. buttonEventData.position = ScreenCenterPoint;
  94. buttonEventData.pointerCurrentRaycast = result;
  95. buttonEventData.position3DDelta = hoverEventData.position3DDelta;
  96. buttonEventData.position3D = hoverEventData.position3D;
  97. buttonEventData.rotationDelta = hoverEventData.rotationDelta;
  98. buttonEventData.rotation = hoverEventData.rotation;
  99. }
  100. ProcessPress(hoverEventData);
  101. ProcessMove(hoverEventData);
  102. ProcessDrag(hoverEventData);
  103. for (int j = 1, jmax = raycaster.ButtonEventDataList.Count; j < jmax; ++j)
  104. {
  105. var buttonEventData = raycaster.ButtonEventDataList[j];
  106. if (buttonEventData == null || buttonEventData == hoverEventData)
  107. continue;
  108. buttonEventData.pointerEnter = hoverEventData.pointerEnter;
  109. ProcessPress(buttonEventData);
  110. ProcessDrag(buttonEventData);
  111. }
  112. }
  113. }
  114. /// <summary> Initializes this object. </summary>
  115. public static void Initialize()
  116. {
  117. if (Active || isApplicationQuitting)
  118. return;
  119. var instances = FindObjectsOfType<NRInputModule>();
  120. if (instances.Length > 0)
  121. {
  122. m_Instance = instances[0];
  123. if (instances.Length > 1)
  124. {
  125. NRDebugger.Warning("Multiple NRInputModule not supported!");
  126. }
  127. }
  128. if (!Active)
  129. {
  130. EventSystem eventSystem = EventSystem.current;
  131. if (eventSystem == null)
  132. {
  133. eventSystem = FindObjectOfType<EventSystem>();
  134. }
  135. if (eventSystem == null)
  136. {
  137. eventSystem = new GameObject("[EventSystem]").AddComponent<EventSystem>();
  138. }
  139. if (eventSystem == null)
  140. {
  141. NRDebugger.Warning("EventSystem not found or create fail!");
  142. return;
  143. }
  144. m_Instance = eventSystem.gameObject.AddComponent<NRInputModule>();
  145. DontDestroyOnLoad(eventSystem.gameObject);
  146. }
  147. }
  148. /// <summary> <para>Process the current tick for the module.</para> </summary>
  149. public override void Process()
  150. {
  151. Initialize();
  152. if (isActiveAndEnabled)
  153. {
  154. ProcessRaycast();
  155. }
  156. }
  157. /// <summary> Executes the 'application quit' action. </summary>
  158. private void OnApplicationQuit()
  159. {
  160. isApplicationQuitting = true;
  161. }
  162. /// <summary> Adds a raycaster. </summary>
  163. /// <param name="raycaster"> The raycaster.</param>
  164. public static void AddRaycaster(NRPointerRaycaster raycaster)
  165. {
  166. if (raycaster == null)
  167. return;
  168. Initialize();
  169. raycasters.Add(raycaster);
  170. }
  171. /// <summary> Removes the raycaster described by raycaster. </summary>
  172. /// <param name="raycaster"> The raycaster.</param>
  173. public static void RemoveRaycaster(NRPointerRaycaster raycaster)
  174. {
  175. if (m_Instance)
  176. {
  177. m_Instance.ProcessRaycast();
  178. }
  179. raycasters.Remove(raycaster);
  180. }
  181. /// <summary> The default raycast comparer. </summary>
  182. public static readonly Comparison<RaycastResult> defaultRaycastComparer = RaycastComparer;
  183. /// <summary> Raycast comparer. </summary>
  184. /// <param name="lhs"> The left hand side.</param>
  185. /// <param name="rhs"> The right hand side.</param>
  186. /// <returns> An int. </returns>
  187. private static int RaycastComparer(RaycastResult lhs, RaycastResult rhs)
  188. {
  189. if (lhs.module != rhs.module)
  190. {
  191. if (lhs.module.eventCamera != null && rhs.module.eventCamera != null && lhs.module.eventCamera.depth != rhs.module.eventCamera.depth)
  192. {
  193. if (lhs.module.eventCamera.depth < rhs.module.eventCamera.depth) { return 1; }
  194. if (lhs.module.eventCamera.depth == rhs.module.eventCamera.depth) { return 0; }
  195. return -1;
  196. }
  197. if (lhs.module.sortOrderPriority != rhs.module.sortOrderPriority)
  198. {
  199. return rhs.module.sortOrderPriority.CompareTo(lhs.module.sortOrderPriority);
  200. }
  201. if (lhs.module.renderOrderPriority != rhs.module.renderOrderPriority)
  202. {
  203. return rhs.module.renderOrderPriority.CompareTo(lhs.module.renderOrderPriority);
  204. }
  205. }
  206. if (lhs.sortingLayer != rhs.sortingLayer)
  207. {
  208. var rid = SortingLayer.GetLayerValueFromID(rhs.sortingLayer);
  209. var lid = SortingLayer.GetLayerValueFromID(lhs.sortingLayer);
  210. return rid.CompareTo(lid);
  211. }
  212. if (lhs.sortingOrder != rhs.sortingOrder)
  213. {
  214. return rhs.sortingOrder.CompareTo(lhs.sortingOrder);
  215. }
  216. if (!Mathf.Approximately(lhs.distance, rhs.distance))
  217. {
  218. return lhs.distance.CompareTo(rhs.distance);
  219. }
  220. if (lhs.depth != rhs.depth)
  221. {
  222. return rhs.depth.CompareTo(lhs.depth);
  223. }
  224. return lhs.index.CompareTo(rhs.index);
  225. }
  226. /// <summary> Process the move described by eventData. </summary>
  227. /// <param name="eventData"> Information describing the event.</param>
  228. protected virtual void ProcessMove(PointerEventData eventData)
  229. {
  230. var hoverGO = eventData.pointerCurrentRaycast.gameObject;
  231. if (eventData.pointerEnter != hoverGO)
  232. {
  233. HandlePointerExitAndEnter(eventData, hoverGO);
  234. }
  235. }
  236. /// <summary> Process the press described by eventData. </summary>
  237. /// <param name="eventData"> Information describing the event.</param>
  238. protected virtual void ProcessPress(NRPointerEventData eventData)
  239. {
  240. if (eventData.GetPress())
  241. {
  242. if (!eventData.pressPrecessed)
  243. {
  244. ProcessPressDown(eventData);
  245. }
  246. HandlePressExitAndEnter(eventData, eventData.pointerCurrentRaycast.gameObject);
  247. }
  248. else if (eventData.pressPrecessed)
  249. {
  250. ProcessPressUp(eventData);
  251. HandlePressExitAndEnter(eventData, null);
  252. }
  253. }
  254. /// <summary> Process the press down described by eventData. </summary>
  255. /// <param name="eventData"> Information describing the event.</param>
  256. protected void ProcessPressDown(NRPointerEventData eventData)
  257. {
  258. var currentOverGo = eventData.pointerCurrentRaycast.gameObject;
  259. eventData.pressPrecessed = true;
  260. eventData.eligibleForClick = true;
  261. eventData.delta = Vector2.zero;
  262. eventData.dragging = false;
  263. eventData.useDragThreshold = true;
  264. eventData.pressPosition = eventData.position;
  265. eventData.pressPosition3D = eventData.position3D;
  266. eventData.pressRotation = eventData.rotation;
  267. eventData.pressDistance = eventData.pointerCurrentRaycast.distance;
  268. eventData.pointerPressRaycast = eventData.pointerCurrentRaycast;
  269. DeselectIfSelectionChanged(currentOverGo, eventData);
  270. var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, eventData, ExecuteEvents.pointerDownHandler);
  271. if (newPressed == null)
  272. {
  273. newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
  274. }
  275. var time = Time.unscaledTime;
  276. if (newPressed == eventData.lastPress)
  277. {
  278. if (eventData.raycaster != null && time < (eventData.clickTime + NRInput.ClickInterval))
  279. {
  280. ++eventData.clickCount;
  281. }
  282. else
  283. {
  284. eventData.clickCount = 1;
  285. }
  286. eventData.clickTime = time;
  287. }
  288. else
  289. {
  290. eventData.clickCount = 1;
  291. }
  292. eventData.pointerPress = newPressed;
  293. eventData.rawPointerPress = currentOverGo;
  294. eventData.clickTime = time;
  295. eventData.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
  296. if (eventData.pointerDrag != null)
  297. {
  298. ExecuteEvents.Execute(eventData.pointerDrag, eventData, ExecuteEvents.initializePotentialDrag);
  299. }
  300. }
  301. /// <summary> Process the press up described by eventData. </summary>
  302. /// <param name="eventData"> Information describing the event.</param>
  303. protected void ProcessPressUp(NRPointerEventData eventData)
  304. {
  305. var currentOverGo = eventData.pointerCurrentRaycast.gameObject;
  306. ExecuteEvents.Execute(eventData.pointerPress, eventData, ExecuteEvents.pointerUpHandler);
  307. var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
  308. if (eventData.pointerPress == pointerUpHandler && eventData.eligibleForClick)
  309. {
  310. ExecuteEvents.Execute(eventData.pointerPress, eventData, ExecuteEvents.pointerClickHandler);
  311. }
  312. else if (eventData.pointerDrag != null && eventData.dragging)
  313. {
  314. ExecuteEvents.ExecuteHierarchy(currentOverGo, eventData, ExecuteEvents.dropHandler);
  315. }
  316. eventData.pressPrecessed = false;
  317. eventData.eligibleForClick = false;
  318. eventData.pointerPress = null;
  319. eventData.rawPointerPress = null;
  320. if (eventData.pointerDrag != null && eventData.dragging)
  321. {
  322. ExecuteEvents.Execute(eventData.pointerDrag, eventData, ExecuteEvents.endDragHandler);
  323. }
  324. eventData.dragging = false;
  325. eventData.pointerDrag = null;
  326. if (currentOverGo != eventData.pointerEnter)
  327. {
  328. HandlePointerExitAndEnter(eventData, null);
  329. HandlePointerExitAndEnter(eventData, currentOverGo);
  330. }
  331. }
  332. /// <summary> Determine if we should start drag. </summary>
  333. /// <param name="eventData"> Information describing the event.</param>
  334. /// <returns> True if it succeeds, false if it fails. </returns>
  335. protected bool ShouldStartDrag(NRPointerEventData eventData)
  336. {
  337. if (!eventData.useDragThreshold || eventData.raycaster == null)
  338. {
  339. return true;
  340. }
  341. var currentPos = eventData.position3D + (eventData.rotation * Vector3.forward) * eventData.pressDistance;
  342. var pressPos = eventData.pressPosition3D + (eventData.pressRotation * Vector3.forward) * eventData.pressDistance;
  343. var threshold = NRInput.DragThreshold;
  344. return (currentPos - pressPos).sqrMagnitude >= threshold * threshold;
  345. }
  346. /// <summary> Process the drag described by eventData. </summary>
  347. /// <param name="eventData"> Information describing the event.</param>
  348. protected void ProcessDrag(NRPointerEventData eventData)
  349. {
  350. var moving = !Mathf.Approximately(eventData.position3DDelta.sqrMagnitude, 0f) || !Mathf.Approximately(Quaternion.Angle(Quaternion.identity, eventData.rotationDelta), 0f);
  351. if (moving && eventData.pointerDrag != null && !eventData.dragging && ShouldStartDrag(eventData))
  352. {
  353. ExecuteEvents.Execute(eventData.pointerDrag, eventData, ExecuteEvents.beginDragHandler);
  354. eventData.dragging = true;
  355. }
  356. if (eventData.dragging && moving && eventData.pointerDrag != null)
  357. {
  358. if (eventData.pointerPress != eventData.pointerDrag)
  359. {
  360. ExecuteEvents.Execute(eventData.pointerPress, eventData, ExecuteEvents.pointerUpHandler);
  361. eventData.eligibleForClick = false;
  362. eventData.pointerPress = null;
  363. eventData.rawPointerPress = null;
  364. }
  365. ExecuteEvents.Execute(eventData.pointerDrag, eventData, ExecuteEvents.dragHandler);
  366. }
  367. }
  368. /// <summary> Handles the press exit and enter. </summary>
  369. /// <param name="eventData"> Information describing the event.</param>
  370. /// <param name="newEnterTarget"> The new enter target.</param>
  371. protected static void HandlePressExitAndEnter(NRPointerEventData eventData, GameObject newEnterTarget)
  372. {
  373. if (eventData.pressEnter == newEnterTarget)
  374. return;
  375. var oldTarget = eventData.pressEnter == null ? null : eventData.pressEnter.transform;
  376. var newTarget = newEnterTarget == null ? null : newEnterTarget.transform;
  377. var commonRoot = default(Transform);
  378. for (var t = oldTarget; t != null; t = t.parent)
  379. {
  380. if (newTarget != null && newTarget.IsChildOf(t))
  381. {
  382. commonRoot = t;
  383. break;
  384. }
  385. else
  386. {
  387. ExecuteEvents.Execute(t.gameObject, eventData, NRExecutePointerEvents.PressExitHandler);
  388. }
  389. }
  390. eventData.pressEnter = newEnterTarget;
  391. for (var t = newTarget; t != commonRoot; t = t.parent)
  392. {
  393. ExecuteEvents.Execute(t.gameObject, eventData, NRExecutePointerEvents.PressEnterHandler);
  394. }
  395. }
  396. /// <summary> Deselect if selection changed. </summary>
  397. /// <param name="currentOverGo"> The current over go.</param>
  398. /// <param name="pointerEvent"> The pointer event.</param>
  399. protected void DeselectIfSelectionChanged(GameObject currentOverGo, BaseEventData pointerEvent)
  400. {
  401. var selectHandlerGO = ExecuteEvents.GetEventHandler<ISelectHandler>(currentOverGo);
  402. if (eventSystem != null && selectHandlerGO != eventSystem.currentSelectedGameObject)
  403. {
  404. eventSystem.SetSelectedGameObject(null, pointerEvent);
  405. }
  406. }
  407. }
  408. }