Assignment for RMIT Mixed Reality in 2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

417 lines
14 KiB

  1. /************************************************************************************
  2. Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
  3. Licensed under the Oculus Utilities SDK License Version 1.31 (the "License"); you may not use
  4. the Utilities SDK except in compliance with the License, which is provided at the time of installation
  5. or download, or which otherwise accompanies this software in either electronic or hard copy form.
  6. You may obtain a copy of the License at
  7. https://developer.oculus.com/licenses/utilities-1.31
  8. Unless required by applicable law or agreed to in writing, the Utilities SDK distributed
  9. under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  10. ANY KIND, either express or implied. See the License for the specific language governing
  11. permissions and limitations under the License.
  12. ************************************************************************************/
  13. using System.Collections.Generic;
  14. using UnityEngine;
  15. /// <summary>
  16. /// Allows grabbing and throwing of objects with the OVRGrabbable component on them.
  17. /// </summary>
  18. [RequireComponent(typeof(Rigidbody))]
  19. public class OVRGrabber : MonoBehaviour
  20. {
  21. // Grip trigger thresholds for picking up objects, with some hysteresis.
  22. public float grabBegin = 0.55f;
  23. public float grabEnd = 0.35f;
  24. bool alreadyUpdated = false;
  25. // Demonstrates parenting the held object to the hand's transform when grabbed.
  26. // When false, the grabbed object is moved every FixedUpdate using MovePosition.
  27. // Note that MovePosition is required for proper physics simulation. If you set this to true, you can
  28. // easily observe broken physics simulation by, for example, moving the bottom cube of a stacked
  29. // tower and noting a complete loss of friction.
  30. [SerializeField]
  31. protected bool m_parentHeldObject = false;
  32. // If true, this script will move the hand to the transform specified by m_parentTransform, using MovePosition in
  33. // FixedUpdate. This allows correct physics behavior, at the cost of some latency. In this usage scenario, you
  34. // should NOT parent the hand to the hand anchor.
  35. // (If m_moveHandPosition is false, this script will NOT update the game object's position.
  36. // The hand gameObject can simply be attached to the hand anchor, which updates position in LateUpdate,
  37. // gaining us a few ms of reduced latency.)
  38. [SerializeField]
  39. protected bool m_moveHandPosition = false;
  40. // Child/attached transforms of the grabber, indicating where to snap held objects to (if you snap them).
  41. // Also used for ranking grab targets in case of multiple candidates.
  42. [SerializeField]
  43. protected Transform m_gripTransform = null;
  44. // Child/attached Colliders to detect candidate grabbable objects.
  45. [SerializeField]
  46. protected Collider[] m_grabVolumes = null;
  47. // Should be OVRInput.Controller.LTouch or OVRInput.Controller.RTouch.
  48. [SerializeField]
  49. protected OVRInput.Controller m_controller;
  50. // You can set this explicitly in the inspector if you're using m_moveHandPosition.
  51. // Otherwise, you should typically leave this null and simply parent the hand to the hand anchor
  52. // in your scene, using Unity's inspector.
  53. [SerializeField]
  54. protected Transform m_parentTransform;
  55. [SerializeField]
  56. protected GameObject m_player;
  57. protected bool m_grabVolumeEnabled = true;
  58. protected Vector3 m_lastPos;
  59. protected Quaternion m_lastRot;
  60. protected Quaternion m_anchorOffsetRotation;
  61. protected Vector3 m_anchorOffsetPosition;
  62. protected float m_prevFlex;
  63. protected OVRGrabbable m_grabbedObj = null;
  64. protected Vector3 m_grabbedObjectPosOff;
  65. protected Quaternion m_grabbedObjectRotOff;
  66. protected Dictionary<OVRGrabbable, int> m_grabCandidates = new Dictionary<OVRGrabbable, int>();
  67. protected bool m_operatingWithoutOVRCameraRig = true;
  68. /// <summary>
  69. /// The currently grabbed object.
  70. /// </summary>
  71. public OVRGrabbable grabbedObject
  72. {
  73. get { return m_grabbedObj; }
  74. }
  75. public void ForceRelease(OVRGrabbable grabbable)
  76. {
  77. bool canRelease = (
  78. (m_grabbedObj != null) &&
  79. (m_grabbedObj == grabbable)
  80. );
  81. if (canRelease)
  82. {
  83. GrabEnd();
  84. }
  85. }
  86. protected virtual void Awake()
  87. {
  88. m_anchorOffsetPosition = transform.localPosition;
  89. m_anchorOffsetRotation = transform.localRotation;
  90. if(!m_moveHandPosition)
  91. {
  92. // If we are being used with an OVRCameraRig, let it drive input updates, which may come from Update or FixedUpdate.
  93. OVRCameraRig rig = transform.GetComponentInParent<OVRCameraRig>();
  94. if (rig != null)
  95. {
  96. rig.UpdatedAnchors += (r) => {OnUpdatedAnchors();};
  97. m_operatingWithoutOVRCameraRig = false;
  98. }
  99. }
  100. }
  101. protected virtual void Start()
  102. {
  103. m_lastPos = transform.position;
  104. m_lastRot = transform.rotation;
  105. if(m_parentTransform == null)
  106. {
  107. m_parentTransform = gameObject.transform;
  108. }
  109. // We're going to setup the player collision to ignore the hand collision.
  110. SetPlayerIgnoreCollision(gameObject, true);
  111. }
  112. virtual public void Update()
  113. {
  114. alreadyUpdated = false;
  115. }
  116. virtual public void FixedUpdate()
  117. {
  118. if (m_operatingWithoutOVRCameraRig)
  119. {
  120. OnUpdatedAnchors();
  121. }
  122. }
  123. // Hands follow the touch anchors by calling MovePosition each frame to reach the anchor.
  124. // This is done instead of parenting to achieve workable physics. If you don't require physics on
  125. // your hands or held objects, you may wish to switch to parenting.
  126. void OnUpdatedAnchors()
  127. {
  128. // Don't want to MovePosition multiple times in a frame, as it causes high judder in conjunction
  129. // with the hand position prediction in the runtime.
  130. if (alreadyUpdated) return;
  131. alreadyUpdated = true;
  132. Vector3 destPos = m_parentTransform.TransformPoint(m_anchorOffsetPosition);
  133. Quaternion destRot = m_parentTransform.rotation * m_anchorOffsetRotation;
  134. if (m_moveHandPosition)
  135. {
  136. GetComponent<Rigidbody>().MovePosition(destPos);
  137. GetComponent<Rigidbody>().MoveRotation(destRot);
  138. }
  139. if (!m_parentHeldObject)
  140. {
  141. MoveGrabbedObject(destPos, destRot);
  142. }
  143. m_lastPos = transform.position;
  144. m_lastRot = transform.rotation;
  145. float prevFlex = m_prevFlex;
  146. // Update values from inputs
  147. m_prevFlex = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, m_controller);
  148. CheckForGrabOrRelease(prevFlex);
  149. }
  150. void OnDestroy()
  151. {
  152. if (m_grabbedObj != null)
  153. {
  154. GrabEnd();
  155. }
  156. }
  157. void OnTriggerEnter(Collider otherCollider)
  158. {
  159. // Get the grab trigger
  160. OVRGrabbable grabbable = otherCollider.GetComponent<OVRGrabbable>() ?? otherCollider.GetComponentInParent<OVRGrabbable>();
  161. if (grabbable == null) return;
  162. // Add the grabbable
  163. int refCount = 0;
  164. m_grabCandidates.TryGetValue(grabbable, out refCount);
  165. m_grabCandidates[grabbable] = refCount + 1;
  166. }
  167. void OnTriggerExit(Collider otherCollider)
  168. {
  169. OVRGrabbable grabbable = otherCollider.GetComponent<OVRGrabbable>() ?? otherCollider.GetComponentInParent<OVRGrabbable>();
  170. if (grabbable == null) return;
  171. // Remove the grabbable
  172. int refCount = 0;
  173. bool found = m_grabCandidates.TryGetValue(grabbable, out refCount);
  174. if (!found)
  175. {
  176. return;
  177. }
  178. if (refCount > 1)
  179. {
  180. m_grabCandidates[grabbable] = refCount - 1;
  181. }
  182. else
  183. {
  184. m_grabCandidates.Remove(grabbable);
  185. }
  186. }
  187. protected void CheckForGrabOrRelease(float prevFlex)
  188. {
  189. if ((m_prevFlex >= grabBegin) && (prevFlex < grabBegin))
  190. {
  191. GrabBegin();
  192. }
  193. else if ((m_prevFlex <= grabEnd) && (prevFlex > grabEnd))
  194. {
  195. GrabEnd();
  196. }
  197. }
  198. protected virtual void GrabBegin()
  199. {
  200. float closestMagSq = float.MaxValue;
  201. OVRGrabbable closestGrabbable = null;
  202. Collider closestGrabbableCollider = null;
  203. // Iterate grab candidates and find the closest grabbable candidate
  204. foreach (OVRGrabbable grabbable in m_grabCandidates.Keys)
  205. {
  206. bool canGrab = !(grabbable.isGrabbed && !grabbable.allowOffhandGrab);
  207. if (!canGrab)
  208. {
  209. continue;
  210. }
  211. for (int j = 0; j < grabbable.grabPoints.Length; ++j)
  212. {
  213. Collider grabbableCollider = grabbable.grabPoints[j];
  214. // Store the closest grabbable
  215. Vector3 closestPointOnBounds = grabbableCollider.ClosestPointOnBounds(m_gripTransform.position);
  216. float grabbableMagSq = (m_gripTransform.position - closestPointOnBounds).sqrMagnitude;
  217. if (grabbableMagSq < closestMagSq)
  218. {
  219. closestMagSq = grabbableMagSq;
  220. closestGrabbable = grabbable;
  221. closestGrabbableCollider = grabbableCollider;
  222. }
  223. }
  224. }
  225. // Disable grab volumes to prevent overlaps
  226. GrabVolumeEnable(false);
  227. if (closestGrabbable != null)
  228. {
  229. if (closestGrabbable.isGrabbed)
  230. {
  231. closestGrabbable.grabbedBy.OffhandGrabbed(closestGrabbable);
  232. }
  233. m_grabbedObj = closestGrabbable;
  234. m_grabbedObj.GrabBegin(this, closestGrabbableCollider);
  235. m_lastPos = transform.position;
  236. m_lastRot = transform.rotation;
  237. // Set up offsets for grabbed object desired position relative to hand.
  238. if(m_grabbedObj.snapPosition)
  239. {
  240. m_grabbedObjectPosOff = m_gripTransform.localPosition;
  241. if(m_grabbedObj.snapOffset)
  242. {
  243. Vector3 snapOffset = m_grabbedObj.snapOffset.position;
  244. if (m_controller == OVRInput.Controller.LTouch) snapOffset.x = -snapOffset.x;
  245. m_grabbedObjectPosOff += snapOffset;
  246. }
  247. }
  248. else
  249. {
  250. Vector3 relPos = m_grabbedObj.transform.position - transform.position;
  251. relPos = Quaternion.Inverse(transform.rotation) * relPos;
  252. m_grabbedObjectPosOff = relPos;
  253. }
  254. if (m_grabbedObj.snapOrientation)
  255. {
  256. m_grabbedObjectRotOff = m_gripTransform.localRotation;
  257. if(m_grabbedObj.snapOffset)
  258. {
  259. m_grabbedObjectRotOff = m_grabbedObj.snapOffset.rotation * m_grabbedObjectRotOff;
  260. }
  261. }
  262. else
  263. {
  264. Quaternion relOri = Quaternion.Inverse(transform.rotation) * m_grabbedObj.transform.rotation;
  265. m_grabbedObjectRotOff = relOri;
  266. }
  267. // Note: force teleport on grab, to avoid high-speed travel to dest which hits a lot of other objects at high
  268. // speed and sends them flying. The grabbed object may still teleport inside of other objects, but fixing that
  269. // is beyond the scope of this demo.
  270. MoveGrabbedObject(m_lastPos, m_lastRot, true);
  271. SetPlayerIgnoreCollision(m_grabbedObj.gameObject, true);
  272. if (m_parentHeldObject)
  273. {
  274. m_grabbedObj.transform.parent = transform;
  275. }
  276. }
  277. }
  278. protected virtual void MoveGrabbedObject(Vector3 pos, Quaternion rot, bool forceTeleport = false)
  279. {
  280. if (m_grabbedObj == null)
  281. {
  282. return;
  283. }
  284. Rigidbody grabbedRigidbody = m_grabbedObj.grabbedRigidbody;
  285. Vector3 grabbablePosition = pos + rot * m_grabbedObjectPosOff;
  286. Quaternion grabbableRotation = rot * m_grabbedObjectRotOff;
  287. if (forceTeleport)
  288. {
  289. grabbedRigidbody.transform.position = grabbablePosition;
  290. grabbedRigidbody.transform.rotation = grabbableRotation;
  291. }
  292. else
  293. {
  294. grabbedRigidbody.MovePosition(grabbablePosition);
  295. grabbedRigidbody.MoveRotation(grabbableRotation);
  296. }
  297. }
  298. protected void GrabEnd()
  299. {
  300. if (m_grabbedObj != null)
  301. {
  302. OVRPose localPose = new OVRPose { position = OVRInput.GetLocalControllerPosition(m_controller), orientation = OVRInput.GetLocalControllerRotation(m_controller) };
  303. OVRPose offsetPose = new OVRPose { position = m_anchorOffsetPosition, orientation = m_anchorOffsetRotation };
  304. localPose = localPose * offsetPose;
  305. OVRPose trackingSpace = transform.ToOVRPose() * localPose.Inverse();
  306. Vector3 linearVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerVelocity(m_controller);
  307. Vector3 angularVelocity = trackingSpace.orientation * OVRInput.GetLocalControllerAngularVelocity(m_controller);
  308. GrabbableRelease(linearVelocity, angularVelocity);
  309. }
  310. // Re-enable grab volumes to allow overlap events
  311. GrabVolumeEnable(true);
  312. }
  313. protected void GrabbableRelease(Vector3 linearVelocity, Vector3 angularVelocity)
  314. {
  315. m_grabbedObj.GrabEnd(linearVelocity, angularVelocity);
  316. if(m_parentHeldObject) m_grabbedObj.transform.parent = null;
  317. SetPlayerIgnoreCollision(m_grabbedObj.gameObject, false);
  318. m_grabbedObj = null;
  319. }
  320. protected virtual void GrabVolumeEnable(bool enabled)
  321. {
  322. if (m_grabVolumeEnabled == enabled)
  323. {
  324. return;
  325. }
  326. m_grabVolumeEnabled = enabled;
  327. for (int i = 0; i < m_grabVolumes.Length; ++i)
  328. {
  329. Collider grabVolume = m_grabVolumes[i];
  330. grabVolume.enabled = m_grabVolumeEnabled;
  331. }
  332. if (!m_grabVolumeEnabled)
  333. {
  334. m_grabCandidates.Clear();
  335. }
  336. }
  337. protected virtual void OffhandGrabbed(OVRGrabbable grabbable)
  338. {
  339. if (m_grabbedObj == grabbable)
  340. {
  341. GrabbableRelease(Vector3.zero, Vector3.zero);
  342. }
  343. }
  344. protected void SetPlayerIgnoreCollision(GameObject grabbable, bool ignore)
  345. {
  346. if (m_player != null)
  347. {
  348. Collider[] playerColliders = m_player.GetComponentsInChildren<Collider>();
  349. foreach (Collider pc in playerColliders)
  350. {
  351. Collider[] colliders = grabbable.GetComponentsInChildren<Collider>();
  352. foreach (Collider c in colliders)
  353. {
  354. Physics.IgnoreCollision(c, pc, ignore);
  355. }
  356. }
  357. }
  358. }
  359. }