NxrReticle.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // Copyright 2016 Nibiru. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  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. using UnityEngine;
  15. using UnityEngine.UI;
  16. /// Draws a circular reticle in front of any object that the user gazes at.
  17. /// The circle dilates if the object is clickable.
  18. namespace Nxr.Internal
  19. {
  20. [AddComponentMenu("NXR/UI/NxrReticle")]
  21. [RequireComponent(typeof(Renderer))]
  22. public class NxrReticle : MonoBehaviour, INxrGazePointer
  23. {
  24. /// Number of segments making the reticle circle.20
  25. private int reticleSegments = 20;
  26. /// Growth speed multiplier for the reticle/
  27. public float reticleGrowthSpeed = 10.0f;
  28. /// Show reticle or not ,if show the material's alpha is 1,else is 0.
  29. private bool showReticle = true;
  30. // Private members
  31. private Material materialComp;
  32. // private GameObject targetObj;
  33. // Current inner angle of the reticle (in degrees).
  34. private float reticleInnerAngle = 0.0f;
  35. // Current outer angle of the reticle (in degrees).
  36. private float reticleOuterAngle = 0.25f;
  37. // Current distance of the reticle (in meters).
  38. private float reticleDistanceInMeters = 50.0f;
  39. // Minimum inner angle of the reticle (in degrees).
  40. private const float kReticleMinInnerAngle = 0.0f;
  41. // Minimum outer angle of the reticle (in degrees).
  42. protected float kReticleMinOuterAngle = 0.25f;
  43. // Angle at which to expand the reticle when intersecting with an object
  44. // (in degrees).
  45. private const float kReticleGrowthAngle = 0.4f;
  46. // Minimum distance of the reticle (in meters).
  47. private const float kReticleDistanceMin = 0.45f;
  48. // Maximum distance of the reticle (in meters).
  49. private const float kReticleDistanceMax = 50.0f;
  50. // Current inner and outer diameters of the reticle,
  51. // before distance multiplication.
  52. private float reticleInnerDiameter = 0.0f;
  53. private float reticleOuterDiameter = 0.0f;
  54. /// Sorting order to use for the reticle's renderer.
  55. /// Range values come from https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html.
  56. /// Default value 32767 ensures gaze reticle is always rendered on top.
  57. [Range(-32767, 32767)]
  58. public int reticleSortingOrder = 32767;
  59. GameObject reticlePointer;
  60. Transform cacheTransform;
  61. Color tempColor;
  62. private void Awake()
  63. {
  64. cacheTransform = transform;
  65. reticlePointer = new GameObject("Pointer");
  66. reticlePointer.transform.parent = cacheTransform;
  67. reticlePointer.transform.localPosition = Vector3.zero;
  68. reticlePointer.transform.localRotation = Quaternion.identity;
  69. }
  70. void Start()
  71. {
  72. CreateReticleVertices();
  73. Renderer rendererComponent = GetComponent<Renderer>();
  74. rendererComponent.sortingOrder = reticleSortingOrder;
  75. materialComp = rendererComponent.material;
  76. tempColor = new Color(materialComp.color.r, materialComp.color.g, materialComp.color.b, alphaValue);
  77. }
  78. public GameObject GetReticlePointer()
  79. {
  80. return reticlePointer;
  81. }
  82. void OnEnable()
  83. {
  84. GazeInputModule.gazePointer = this;
  85. Debug.Log("NxrReticle OnEnable");
  86. }
  87. void OnDisable()
  88. {
  89. Debug.Log("NxrReticle OnDisable");
  90. if (GazeInputModule.gazePointer == this)
  91. {
  92. GazeInputModule.gazePointer = null;
  93. showReticle = false;
  94. }
  95. if (headControl != null)
  96. {
  97. Destroy(headControl);
  98. headControl = null;
  99. }
  100. }
  101. private float alphaValue = -1.0f;
  102. // Only call device.UpdateState() once per frame.
  103. private int updatedToFrame = 0;
  104. private void Update()
  105. {
  106. if(GazeInputModule.gazePointer == null && !showReticle)
  107. {
  108. UpdateStatus();
  109. }
  110. }
  111. public void UpdateStatus()
  112. {
  113. if (updatedToFrame == Time.frameCount) return;
  114. updatedToFrame = Time.frameCount;
  115. if (showReticle)
  116. {
  117. UpdateDiameters();
  118. }
  119. float valueTmp = showReticle ? 1.0f : 0.0f;
  120. if (valueTmp != alphaValue)
  121. {
  122. alphaValue = valueTmp;
  123. tempColor.r = materialComp.color.r;
  124. tempColor.g = materialComp.color.g;
  125. tempColor.b = materialComp.color.b;
  126. tempColor.a = alphaValue;
  127. materialComp.color = tempColor;
  128. }
  129. }
  130. /// This is called when the 'BaseInputModule' system should be enabled.
  131. public void OnGazeEnabled()
  132. {
  133. }
  134. /// This is called when the 'BaseInputModule' system should be disabled.
  135. public void OnGazeDisabled()
  136. {
  137. }
  138. /// Called when the user is looking on a valid GameObject. This can be a 3D
  139. /// or UI element.
  140. ///
  141. /// The camera is the event camera, the target is the object
  142. /// the user is looking at, and the intersectionPosition is the intersection
  143. /// point of the ray sent from the camera on the object.
  144. public void OnGazeStart(Camera camera, GameObject targetObject, Vector3 intersectionPosition,
  145. bool isInteractive)
  146. {
  147. bool IsHoverMode = NxrViewer.Instance != null && NxrViewer.Instance.HeadControl == HeadControl.Hover;
  148. SetGazeTarget(intersectionPosition, isInteractive);
  149. if (headControl != null && isInteractive)
  150. {
  151. if(IsHoverMode)
  152. {
  153. NxrHeadControl mNxrHeadControl = headControl.GetComponent<NxrHeadControl>();
  154. mNxrHeadControl.Show();
  155. mNxrHeadControl.HandleDown();
  156. NxrHeadControl.eventGameObject = targetObject;
  157. }
  158. }
  159. }
  160. /// Called every frame the user is still looking at a valid GameObject. This
  161. /// can be a 3D or UI element.
  162. ///
  163. /// The camera is the event camera, the target is the object the user is
  164. /// looking at, and the intersectionPosition is the intersection point of the
  165. /// ray sent from the camera on the object.
  166. public void OnGazeStay(Camera camera, GameObject targetObject, Vector3 intersectionPosition,
  167. bool isInteractive)
  168. {
  169. SetGazeTarget(intersectionPosition, isInteractive);
  170. }
  171. /// Called when the user's look no longer intersects an object previously
  172. /// intersected with a ray projected from the camera.
  173. /// This is also called just before **OnGazeDisabled** and may have have any of
  174. /// the values set as **null**.
  175. ///
  176. /// The camera is the event camera and the target is the object the user
  177. /// previously looked at.
  178. public void OnGazeExit(Camera camera, GameObject targetObject)
  179. {
  180. reticleDistanceInMeters = kReticleDistanceMax;
  181. reticleInnerAngle = kReticleMinInnerAngle;
  182. reticleOuterAngle = kReticleMinOuterAngle;
  183. bool IsHoverMode = NxrViewer.Instance != null && NxrViewer.Instance.HeadControl == HeadControl.Hover;
  184. if (headControl != null)
  185. {
  186. if(IsHoverMode)
  187. {
  188. headControl.GetComponent<NxrHeadControl>().HandleUp();
  189. // this.gameObject.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  190. // headControl.transform.localPosition = new Vector3(0, 0, 0);
  191. }
  192. }
  193. }
  194. /// Called when a trigger event is initiated. This is practically when
  195. /// the user begins pressing the trigger.
  196. public void OnGazeTriggerStart(Camera camera)
  197. {
  198. // Put your reticle trigger start logic here :)
  199. }
  200. /// Called when a trigger event is finished. This is practically when
  201. /// the user releases the trigger.
  202. public void OnGazeTriggerEnd(Camera camera)
  203. {
  204. // Put your reticle trigger end logic here :)
  205. }
  206. public void GetPointerRadius(out float innerRadius, out float outerRadius)
  207. {
  208. float min_inner_angle_radians = Mathf.Deg2Rad * kReticleMinInnerAngle;
  209. float max_inner_angle_radians = Mathf.Deg2Rad * (kReticleMinInnerAngle + kReticleGrowthAngle);
  210. innerRadius = 2.0f * Mathf.Tan(min_inner_angle_radians);
  211. outerRadius = 2.0f * Mathf.Tan(max_inner_angle_radians);
  212. }
  213. private void CreateReticleVertices()
  214. {
  215. Mesh mesh = new Mesh();
  216. gameObject.AddComponent<MeshFilter>();
  217. GetComponent<MeshFilter>().mesh = mesh;
  218. int segments_count = reticleSegments;
  219. int vertex_count = (segments_count + 1) * 2;
  220. #region Vertices
  221. Vector3[] vertices = new Vector3[vertex_count];
  222. const float kTwoPi = Mathf.PI * 2.0f;
  223. int vi = 0;
  224. for (int si = 0; si <= segments_count; ++si)
  225. {
  226. // Add two vertices for every circle segment: one at the beginning of the
  227. // prism, and one at the end of the prism.
  228. float angle = (float)si / (float)(segments_count) * kTwoPi;
  229. float x = Mathf.Sin(angle);
  230. float y = Mathf.Cos(angle);
  231. vertices[vi++] = new Vector3(x, y, 0.0f); // Outer vertex.
  232. vertices[vi++] = new Vector3(x, y, 1.0f); // Inner vertex.
  233. }
  234. #endregion
  235. #region Triangles
  236. int indices_count = (segments_count + 1) * 3 * 2;
  237. int[] indices = new int[indices_count];
  238. int vert = 0;
  239. int idx = 0;
  240. for (int si = 0; si < segments_count; ++si)
  241. {
  242. indices[idx++] = vert + 1;
  243. indices[idx++] = vert;
  244. indices[idx++] = vert + 2;
  245. indices[idx++] = vert + 1;
  246. indices[idx++] = vert + 2;
  247. indices[idx++] = vert + 3;
  248. vert += 2;
  249. }
  250. #endregion
  251. mesh.vertices = vertices;
  252. mesh.triangles = indices;
  253. mesh.RecalculateBounds();
  254. //mesh.Optimize();
  255. }
  256. private void UpdateDiameters()
  257. {
  258. reticleDistanceInMeters =
  259. Mathf.Clamp(reticleDistanceInMeters, kReticleDistanceMin, kReticleDistanceMax);
  260. if (reticleInnerAngle < kReticleMinInnerAngle)
  261. {
  262. reticleInnerAngle = kReticleMinInnerAngle;
  263. }
  264. if (reticleOuterAngle < kReticleMinOuterAngle)
  265. {
  266. reticleOuterAngle = kReticleMinOuterAngle;
  267. }
  268. float inner_half_angle_radians = Mathf.Deg2Rad * reticleInnerAngle * 0.5f;
  269. float outer_half_angle_radians = Mathf.Deg2Rad * reticleOuterAngle * 0.5f;
  270. float inner_diameter = 2.0f * Mathf.Tan(inner_half_angle_radians);
  271. float outer_diameter = 2.0f * Mathf.Tan(outer_half_angle_radians);
  272. reticleInnerDiameter =
  273. Mathf.Lerp(reticleInnerDiameter, inner_diameter, Time.deltaTime * reticleGrowthSpeed);
  274. reticleOuterDiameter =
  275. Mathf.Lerp(reticleOuterDiameter, outer_diameter, Time.deltaTime * reticleGrowthSpeed);
  276. materialComp.SetFloat("_InnerDiameter", reticleInnerDiameter * reticleDistanceInMeters);
  277. materialComp.SetFloat("_OuterDiameter", reticleOuterDiameter * reticleDistanceInMeters);
  278. materialComp.SetFloat("_DistanceInMeters", reticleDistanceInMeters);
  279. }
  280. internal void Show()
  281. {
  282. if (materialComp != null)
  283. {
  284. tempColor.r = materialComp.color.r;
  285. tempColor.g = materialComp.color.g;
  286. tempColor.b = materialComp.color.b;
  287. tempColor.a = 1;
  288. materialComp.color = tempColor;
  289. }
  290. showReticle = true;
  291. // Debug.LogError("Reticle-Show");
  292. }
  293. public bool IsShowing()
  294. {
  295. return showReticle;
  296. }
  297. private GameObject headControl;
  298. private Transform headCtrlCanvasTrans;
  299. public void HeadShow()
  300. {
  301. if (headControl == null)
  302. {
  303. headControl = (GameObject)Instantiate(Resources.Load<GameObject>("Reticle/NarHeadControl"), gameObject.transform);
  304. headCtrlCanvasTrans = headControl.GetComponent<Canvas>().transform;
  305. }
  306. else
  307. {
  308. //headControl.GetComponentInChildren<Image>().color = new Color(255, 255, 255, 1);
  309. headControl.GetComponent<NxrHeadControl>().Show();
  310. }
  311. headControl.transform.localRotation = Quaternion.identity;
  312. Debug.Log("HeadShow");
  313. }
  314. public void HeadDismiss()
  315. {
  316. if (headControl != null)
  317. {
  318. //headControl.GetComponentInChildren<Image>().color = new Color(255, 255, 255, 0);
  319. headControl.GetComponent<NxrHeadControl>().Hide();
  320. Debug.Log("HeadDismiss");
  321. }
  322. }
  323. public void Dismiss()
  324. {
  325. if (materialComp != null)
  326. {
  327. tempColor.r = materialComp.color.r;
  328. tempColor.g = materialComp.color.g;
  329. tempColor.b = materialComp.color.b;
  330. tempColor.a = 0;
  331. materialComp.color = tempColor;
  332. }
  333. showReticle = false;
  334. // Debug.LogError("Reticle-Dismiss");
  335. }
  336. private void SetGazeTarget(Vector3 target, bool interactive)
  337. {
  338. Vector3 targetLocalPosition = cacheTransform.InverseTransformPoint(target);
  339. reticlePointer.transform.localPosition = new Vector3(0, 0, targetLocalPosition.z - 0.02f);
  340. reticleDistanceInMeters =
  341. Mathf.Clamp(targetLocalPosition.z, kReticleDistanceMin, kReticleDistanceMax);
  342. bool IsHoverMode = NxrViewer.Instance != null && NxrViewer.Instance.HeadControl == HeadControl.Hover;
  343. if (IsHoverMode)
  344. {
  345. //this.gameObject.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.ShadowsOnly;
  346. headControl.transform.localPosition = new Vector3(0, 0, reticleDistanceInMeters - 0.02f);
  347. headCtrlCanvasTrans.rotation = Quaternion.identity;
  348. headControl.GetComponent<NxrHeadControl>().HandleGazeStay();
  349. Dismiss();
  350. }
  351. else
  352. {
  353. reticleInnerAngle = kReticleMinInnerAngle + (interactive ? kReticleGrowthAngle : 0);
  354. reticleOuterAngle = kReticleMinOuterAngle + (interactive ? kReticleGrowthAngle : 0);
  355. }
  356. }
  357. public void UpdateColor(Color color)
  358. {
  359. if(materialComp != null)
  360. {
  361. float alpha = materialComp.color.a;
  362. alphaValue = alpha;
  363. tempColor.r = color.r;
  364. tempColor.g = color.g;
  365. tempColor.b = color.b;
  366. tempColor.a = alphaValue;
  367. materialComp.color = tempColor;
  368. }
  369. }
  370. public void UpdateSize(float size)
  371. {
  372. kReticleMinOuterAngle = size;
  373. }
  374. public float GetSize()
  375. {
  376. return kReticleMinOuterAngle;
  377. }
  378. }
  379. }