Hand.cs 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  1. //======= Copyright (c) Valve Corporation, All rights reserved. ===============
  2. //
  3. // Purpose: The hands used by the player in the vr interaction system
  4. //
  5. //=============================================================================
  6. using UnityEngine;
  7. using System;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Collections.ObjectModel;
  11. using UnityEngine.Events;
  12. using System.Threading;
  13. namespace Valve.VR.InteractionSystem
  14. {
  15. //-------------------------------------------------------------------------
  16. // Links with an appropriate SteamVR controller and facilitates
  17. // interactions with objects in the virtual world.
  18. //-------------------------------------------------------------------------
  19. public class Hand : MonoBehaviour
  20. {
  21. // The flags used to determine how an object is attached to the hand.
  22. [Flags]
  23. public enum AttachmentFlags
  24. {
  25. SnapOnAttach = 1 << 0, // The object should snap to the position of the specified attachment point on the hand.
  26. DetachOthers = 1 << 1, // Other objects attached to this hand will be detached.
  27. DetachFromOtherHand = 1 << 2, // This object will be detached from the other hand.
  28. ParentToHand = 1 << 3, // The object will be parented to the hand.
  29. VelocityMovement = 1 << 4, // The object will attempt to move to match the position and rotation of the hand.
  30. TurnOnKinematic = 1 << 5, // The object will not respond to external physics.
  31. TurnOffGravity = 1 << 6, // The object will not respond to external physics.
  32. AllowSidegrade = 1 << 7, // The object is able to switch from a pinch grab to a grip grab. Decreases likelyhood of a good throw but also decreases likelyhood of accidental drop
  33. };
  34. public const AttachmentFlags defaultAttachmentFlags = AttachmentFlags.ParentToHand |
  35. AttachmentFlags.DetachOthers |
  36. AttachmentFlags.DetachFromOtherHand |
  37. AttachmentFlags.TurnOnKinematic |
  38. AttachmentFlags.SnapOnAttach;
  39. public Hand otherHand;
  40. public SteamVR_Input_Sources handType;
  41. public SteamVR_Behaviour_Pose trackedObject;
  42. public SteamVR_Action_Boolean grabPinchAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("GrabPinch");
  43. public SteamVR_Action_Boolean grabGripAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("GrabGrip");
  44. public SteamVR_Action_Vibration hapticAction = SteamVR_Input.GetAction<SteamVR_Action_Vibration>("Haptic");
  45. public SteamVR_Action_Boolean uiInteractAction = SteamVR_Input.GetAction<SteamVR_Action_Boolean>("InteractUI");
  46. public bool useHoverSphere = true;
  47. public Transform hoverSphereTransform;
  48. public float hoverSphereRadius = 0.05f;
  49. public LayerMask hoverLayerMask = -1;
  50. public float hoverUpdateInterval = 0.1f;
  51. public bool useControllerHoverComponent = true;
  52. public string controllerHoverComponent = "tip";
  53. public float controllerHoverRadius = 0.075f;
  54. public bool useFingerJointHover = true;
  55. public SteamVR_Skeleton_JointIndexEnum fingerJointHover = SteamVR_Skeleton_JointIndexEnum.indexTip;
  56. public float fingerJointHoverRadius = 0.025f;
  57. [Tooltip("A transform on the hand to center attached objects on")]
  58. public Transform objectAttachmentPoint;
  59. public Camera noSteamVRFallbackCamera;
  60. public float noSteamVRFallbackMaxDistanceNoItem = 10.0f;
  61. public float noSteamVRFallbackMaxDistanceWithItem = 0.5f;
  62. private float noSteamVRFallbackInteractorDistance = -1.0f;
  63. public GameObject renderModelPrefab;
  64. [HideInInspector]
  65. public List<RenderModel> renderModels = new List<RenderModel>();
  66. [HideInInspector]
  67. public RenderModel mainRenderModel;
  68. [HideInInspector]
  69. public RenderModel hoverhighlightRenderModel;
  70. public bool showDebugText = false;
  71. public bool spewDebugText = false;
  72. public bool showDebugInteractables = false;
  73. public struct AttachedObject
  74. {
  75. public GameObject attachedObject;
  76. public Interactable interactable;
  77. public Rigidbody attachedRigidbody;
  78. public CollisionDetectionMode collisionDetectionMode;
  79. public bool attachedRigidbodyWasKinematic;
  80. public bool attachedRigidbodyUsedGravity;
  81. public GameObject originalParent;
  82. public bool isParentedToHand;
  83. public GrabTypes grabbedWithType;
  84. public AttachmentFlags attachmentFlags;
  85. public Vector3 initialPositionalOffset;
  86. public Quaternion initialRotationalOffset;
  87. public Transform attachedOffsetTransform;
  88. public Transform handAttachmentPointTransform;
  89. public Vector3 easeSourcePosition;
  90. public Quaternion easeSourceRotation;
  91. public float attachTime;
  92. public AllowTeleportWhileAttachedToHand allowTeleportWhileAttachedToHand;
  93. public bool HasAttachFlag(AttachmentFlags flag)
  94. {
  95. return (attachmentFlags & flag) == flag;
  96. }
  97. }
  98. private List<AttachedObject> attachedObjects = new List<AttachedObject>();
  99. public ReadOnlyCollection<AttachedObject> AttachedObjects
  100. {
  101. get { return attachedObjects.AsReadOnly(); }
  102. }
  103. public bool hoverLocked { get; private set; }
  104. private Interactable _hoveringInteractable;
  105. private TextMesh debugText;
  106. private int prevOverlappingColliders = 0;
  107. private const int ColliderArraySize = 32;
  108. private Collider[] overlappingColliders;
  109. private Player playerInstance;
  110. private GameObject applicationLostFocusObject;
  111. private SteamVR_Events.Action inputFocusAction;
  112. public bool isActive
  113. {
  114. get
  115. {
  116. if (trackedObject != null)
  117. return trackedObject.isActive;
  118. return this.gameObject.activeInHierarchy;
  119. }
  120. }
  121. public bool isPoseValid
  122. {
  123. get
  124. {
  125. return trackedObject.isValid;
  126. }
  127. }
  128. //-------------------------------------------------
  129. // The Interactable object this Hand is currently hovering over
  130. //-------------------------------------------------
  131. public Interactable hoveringInteractable
  132. {
  133. get { return _hoveringInteractable; }
  134. set
  135. {
  136. if (_hoveringInteractable != value)
  137. {
  138. if (_hoveringInteractable != null)
  139. {
  140. if (spewDebugText)
  141. HandDebugLog("HoverEnd " + _hoveringInteractable.gameObject);
  142. _hoveringInteractable.SendMessage("OnHandHoverEnd", this, SendMessageOptions.DontRequireReceiver);
  143. //Note: The _hoveringInteractable can change after sending the OnHandHoverEnd message so we need to check it again before broadcasting this message
  144. if (_hoveringInteractable != null)
  145. {
  146. this.BroadcastMessage("OnParentHandHoverEnd", _hoveringInteractable, SendMessageOptions.DontRequireReceiver); // let objects attached to the hand know that a hover has ended
  147. }
  148. }
  149. _hoveringInteractable = value;
  150. if (_hoveringInteractable != null)
  151. {
  152. if (spewDebugText)
  153. HandDebugLog("HoverBegin " + _hoveringInteractable.gameObject);
  154. _hoveringInteractable.SendMessage("OnHandHoverBegin", this, SendMessageOptions.DontRequireReceiver);
  155. //Note: The _hoveringInteractable can change after sending the OnHandHoverBegin message so we need to check it again before broadcasting this message
  156. if (_hoveringInteractable != null)
  157. {
  158. this.BroadcastMessage("OnParentHandHoverBegin", _hoveringInteractable, SendMessageOptions.DontRequireReceiver); // let objects attached to the hand know that a hover has begun
  159. }
  160. }
  161. }
  162. }
  163. }
  164. //-------------------------------------------------
  165. // Active GameObject attached to this Hand
  166. //-------------------------------------------------
  167. public GameObject currentAttachedObject
  168. {
  169. get
  170. {
  171. CleanUpAttachedObjectStack();
  172. if (attachedObjects.Count > 0)
  173. {
  174. return attachedObjects[attachedObjects.Count - 1].attachedObject;
  175. }
  176. return null;
  177. }
  178. }
  179. public AttachedObject? currentAttachedObjectInfo
  180. {
  181. get
  182. {
  183. CleanUpAttachedObjectStack();
  184. if (attachedObjects.Count > 0)
  185. {
  186. return attachedObjects[attachedObjects.Count - 1];
  187. }
  188. return null;
  189. }
  190. }
  191. public AllowTeleportWhileAttachedToHand currentAttachedTeleportManager
  192. {
  193. get
  194. {
  195. if (currentAttachedObjectInfo.HasValue)
  196. return currentAttachedObjectInfo.Value.allowTeleportWhileAttachedToHand;
  197. return null;
  198. }
  199. }
  200. public SteamVR_Behaviour_Skeleton skeleton
  201. {
  202. get
  203. {
  204. if (mainRenderModel != null)
  205. return mainRenderModel.GetSkeleton();
  206. return null;
  207. }
  208. }
  209. public void ShowController(bool permanent = false)
  210. {
  211. if (mainRenderModel != null)
  212. mainRenderModel.SetControllerVisibility(true, permanent);
  213. if (hoverhighlightRenderModel != null)
  214. hoverhighlightRenderModel.SetControllerVisibility(true, permanent);
  215. }
  216. public void HideController(bool permanent = false)
  217. {
  218. if (mainRenderModel != null)
  219. mainRenderModel.SetControllerVisibility(false, permanent);
  220. if (hoverhighlightRenderModel != null)
  221. hoverhighlightRenderModel.SetControllerVisibility(false, permanent);
  222. }
  223. public void ShowSkeleton(bool permanent = false)
  224. {
  225. if (mainRenderModel != null)
  226. mainRenderModel.SetHandVisibility(true, permanent);
  227. if (hoverhighlightRenderModel != null)
  228. hoverhighlightRenderModel.SetHandVisibility(true, permanent);
  229. }
  230. public void HideSkeleton(bool permanent = false)
  231. {
  232. if (mainRenderModel != null)
  233. mainRenderModel.SetHandVisibility(false, permanent);
  234. if (hoverhighlightRenderModel != null)
  235. hoverhighlightRenderModel.SetHandVisibility(false, permanent);
  236. }
  237. public bool HasSkeleton()
  238. {
  239. return mainRenderModel != null && mainRenderModel.GetSkeleton() != null;
  240. }
  241. public void Show()
  242. {
  243. SetVisibility(true);
  244. }
  245. public void Hide()
  246. {
  247. SetVisibility(false);
  248. }
  249. public void SetVisibility(bool visible)
  250. {
  251. if (mainRenderModel != null)
  252. mainRenderModel.SetVisibility(visible);
  253. }
  254. public void SetSkeletonRangeOfMotion(EVRSkeletalMotionRange newRangeOfMotion, float blendOverSeconds = 0.1f)
  255. {
  256. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  257. {
  258. renderModels[renderModelIndex].SetSkeletonRangeOfMotion(newRangeOfMotion, blendOverSeconds);
  259. }
  260. }
  261. public void SetTemporarySkeletonRangeOfMotion(SkeletalMotionRangeChange temporaryRangeOfMotionChange, float blendOverSeconds = 0.1f)
  262. {
  263. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  264. {
  265. renderModels[renderModelIndex].SetTemporarySkeletonRangeOfMotion(temporaryRangeOfMotionChange, blendOverSeconds);
  266. }
  267. }
  268. public void ResetTemporarySkeletonRangeOfMotion(float blendOverSeconds = 0.1f)
  269. {
  270. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  271. {
  272. renderModels[renderModelIndex].ResetTemporarySkeletonRangeOfMotion(blendOverSeconds);
  273. }
  274. }
  275. public void SetAnimationState(int stateValue)
  276. {
  277. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  278. {
  279. renderModels[renderModelIndex].SetAnimationState(stateValue);
  280. }
  281. }
  282. public void StopAnimation()
  283. {
  284. for (int renderModelIndex = 0; renderModelIndex < renderModels.Count; renderModelIndex++)
  285. {
  286. renderModels[renderModelIndex].StopAnimation();
  287. }
  288. }
  289. //-------------------------------------------------
  290. // Attach a GameObject to this GameObject
  291. //
  292. // objectToAttach - The GameObject to attach
  293. // flags - The flags to use for attaching the object
  294. // attachmentPoint - Name of the GameObject in the hierarchy of this Hand which should act as the attachment point for this GameObject
  295. //-------------------------------------------------
  296. public void AttachObject(GameObject objectToAttach, GrabTypes grabbedWithType, AttachmentFlags flags = defaultAttachmentFlags, Transform attachmentOffset = null)
  297. {
  298. AttachedObject attachedObject = new AttachedObject();
  299. attachedObject.attachmentFlags = flags;
  300. attachedObject.attachedOffsetTransform = attachmentOffset;
  301. attachedObject.attachTime = Time.time;
  302. if (flags == 0)
  303. {
  304. flags = defaultAttachmentFlags;
  305. }
  306. //Make sure top object on stack is non-null
  307. CleanUpAttachedObjectStack();
  308. //Detach the object if it is already attached so that it can get re-attached at the top of the stack
  309. if (ObjectIsAttached(objectToAttach))
  310. DetachObject(objectToAttach);
  311. //Detach from the other hand if requested
  312. if (attachedObject.HasAttachFlag(AttachmentFlags.DetachFromOtherHand))
  313. {
  314. if (otherHand != null)
  315. otherHand.DetachObject(objectToAttach);
  316. }
  317. if (attachedObject.HasAttachFlag(AttachmentFlags.DetachOthers))
  318. {
  319. //Detach all the objects from the stack
  320. while (attachedObjects.Count > 0)
  321. {
  322. DetachObject(attachedObjects[0].attachedObject);
  323. }
  324. }
  325. if (currentAttachedObject)
  326. {
  327. currentAttachedObject.SendMessage("OnHandFocusLost", this, SendMessageOptions.DontRequireReceiver);
  328. }
  329. attachedObject.attachedObject = objectToAttach;
  330. attachedObject.interactable = objectToAttach.GetComponent<Interactable>();
  331. attachedObject.allowTeleportWhileAttachedToHand = objectToAttach.GetComponent<AllowTeleportWhileAttachedToHand>();
  332. attachedObject.handAttachmentPointTransform = this.transform;
  333. if (attachedObject.interactable != null)
  334. {
  335. if (attachedObject.interactable.attachEaseIn)
  336. {
  337. attachedObject.easeSourcePosition = attachedObject.attachedObject.transform.position;
  338. attachedObject.easeSourceRotation = attachedObject.attachedObject.transform.rotation;
  339. attachedObject.interactable.snapAttachEaseInCompleted = false;
  340. }
  341. if (attachedObject.interactable.useHandObjectAttachmentPoint)
  342. attachedObject.handAttachmentPointTransform = objectAttachmentPoint;
  343. if (attachedObject.interactable.hideHandOnAttach)
  344. Hide();
  345. if (attachedObject.interactable.hideSkeletonOnAttach && mainRenderModel != null && mainRenderModel.displayHandByDefault)
  346. HideSkeleton();
  347. if (attachedObject.interactable.hideControllerOnAttach && mainRenderModel != null && mainRenderModel.displayControllerByDefault)
  348. HideController();
  349. if (attachedObject.interactable.handAnimationOnPickup != 0)
  350. SetAnimationState(attachedObject.interactable.handAnimationOnPickup);
  351. if (attachedObject.interactable.setRangeOfMotionOnPickup != SkeletalMotionRangeChange.None)
  352. SetTemporarySkeletonRangeOfMotion(attachedObject.interactable.setRangeOfMotionOnPickup);
  353. }
  354. attachedObject.originalParent = objectToAttach.transform.parent != null ? objectToAttach.transform.parent.gameObject : null;
  355. attachedObject.attachedRigidbody = objectToAttach.GetComponent<Rigidbody>();
  356. if (attachedObject.attachedRigidbody != null)
  357. {
  358. if (attachedObject.interactable.attachedToHand != null) //already attached to another hand
  359. {
  360. //if it was attached to another hand, get the flags from that hand
  361. for (int attachedIndex = 0; attachedIndex < attachedObject.interactable.attachedToHand.attachedObjects.Count; attachedIndex++)
  362. {
  363. AttachedObject attachedObjectInList = attachedObject.interactable.attachedToHand.attachedObjects[attachedIndex];
  364. if (attachedObjectInList.interactable == attachedObject.interactable)
  365. {
  366. attachedObject.attachedRigidbodyWasKinematic = attachedObjectInList.attachedRigidbodyWasKinematic;
  367. attachedObject.attachedRigidbodyUsedGravity = attachedObjectInList.attachedRigidbodyUsedGravity;
  368. attachedObject.originalParent = attachedObjectInList.originalParent;
  369. }
  370. }
  371. }
  372. else
  373. {
  374. attachedObject.attachedRigidbodyWasKinematic = attachedObject.attachedRigidbody.isKinematic;
  375. attachedObject.attachedRigidbodyUsedGravity = attachedObject.attachedRigidbody.useGravity;
  376. }
  377. }
  378. attachedObject.grabbedWithType = grabbedWithType;
  379. if (attachedObject.HasAttachFlag(AttachmentFlags.ParentToHand))
  380. {
  381. //Parent the object to the hand
  382. objectToAttach.transform.parent = this.transform;
  383. attachedObject.isParentedToHand = true;
  384. }
  385. else
  386. {
  387. attachedObject.isParentedToHand = false;
  388. }
  389. if (attachedObject.HasAttachFlag(AttachmentFlags.SnapOnAttach))
  390. {
  391. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  392. {
  393. SteamVR_Skeleton_PoseSnapshot pose = attachedObject.interactable.skeletonPoser.GetBlendedPose(skeleton);
  394. //snap the object to the center of the attach point
  395. objectToAttach.transform.position = this.transform.TransformPoint(pose.position);
  396. objectToAttach.transform.rotation = this.transform.rotation * pose.rotation;
  397. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(objectToAttach.transform.position);
  398. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * objectToAttach.transform.rotation;
  399. }
  400. else
  401. {
  402. if (attachmentOffset != null)
  403. {
  404. //offset the object from the hand by the positional and rotational difference between the offset transform and the attached object
  405. Quaternion rotDiff = Quaternion.Inverse(attachmentOffset.transform.rotation) * objectToAttach.transform.rotation;
  406. objectToAttach.transform.rotation = attachedObject.handAttachmentPointTransform.rotation * rotDiff;
  407. Vector3 posDiff = objectToAttach.transform.position - attachmentOffset.transform.position;
  408. objectToAttach.transform.position = attachedObject.handAttachmentPointTransform.position + posDiff;
  409. }
  410. else
  411. {
  412. //snap the object to the center of the attach point
  413. objectToAttach.transform.rotation = attachedObject.handAttachmentPointTransform.rotation;
  414. objectToAttach.transform.position = attachedObject.handAttachmentPointTransform.position;
  415. }
  416. Transform followPoint = objectToAttach.transform;
  417. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(followPoint.position);
  418. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * followPoint.rotation;
  419. }
  420. }
  421. else
  422. {
  423. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  424. {
  425. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(objectToAttach.transform.position);
  426. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * objectToAttach.transform.rotation;
  427. }
  428. else
  429. {
  430. if (attachmentOffset != null)
  431. {
  432. //get the initial positional and rotational offsets between the hand and the offset transform
  433. Quaternion rotDiff = Quaternion.Inverse(attachmentOffset.transform.rotation) * objectToAttach.transform.rotation;
  434. Quaternion targetRotation = attachedObject.handAttachmentPointTransform.rotation * rotDiff;
  435. Quaternion rotationPositionBy = targetRotation * Quaternion.Inverse(objectToAttach.transform.rotation);
  436. Vector3 posDiff = (rotationPositionBy * objectToAttach.transform.position) - (rotationPositionBy * attachmentOffset.transform.position);
  437. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(attachedObject.handAttachmentPointTransform.position + posDiff);
  438. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * (attachedObject.handAttachmentPointTransform.rotation * rotDiff);
  439. }
  440. else
  441. {
  442. attachedObject.initialPositionalOffset = attachedObject.handAttachmentPointTransform.InverseTransformPoint(objectToAttach.transform.position);
  443. attachedObject.initialRotationalOffset = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * objectToAttach.transform.rotation;
  444. }
  445. }
  446. }
  447. if (attachedObject.HasAttachFlag(AttachmentFlags.TurnOnKinematic))
  448. {
  449. if (attachedObject.attachedRigidbody != null)
  450. {
  451. attachedObject.collisionDetectionMode = attachedObject.attachedRigidbody.collisionDetectionMode;
  452. if (attachedObject.collisionDetectionMode == CollisionDetectionMode.Continuous)
  453. attachedObject.attachedRigidbody.collisionDetectionMode = CollisionDetectionMode.Discrete;
  454. attachedObject.attachedRigidbody.isKinematic = true;
  455. }
  456. }
  457. if (attachedObject.HasAttachFlag(AttachmentFlags.TurnOffGravity))
  458. {
  459. if (attachedObject.attachedRigidbody != null)
  460. {
  461. attachedObject.attachedRigidbody.useGravity = false;
  462. }
  463. }
  464. if (attachedObject.interactable != null && attachedObject.interactable.attachEaseIn)
  465. {
  466. attachedObject.attachedObject.transform.position = attachedObject.easeSourcePosition;
  467. attachedObject.attachedObject.transform.rotation = attachedObject.easeSourceRotation;
  468. }
  469. attachedObjects.Add(attachedObject);
  470. UpdateHovering();
  471. if (spewDebugText)
  472. HandDebugLog("AttachObject " + objectToAttach);
  473. objectToAttach.SendMessage("OnAttachedToHand", this, SendMessageOptions.DontRequireReceiver);
  474. }
  475. public bool ObjectIsAttached(GameObject go)
  476. {
  477. for (int attachedIndex = 0; attachedIndex < attachedObjects.Count; attachedIndex++)
  478. {
  479. if (attachedObjects[attachedIndex].attachedObject == go)
  480. return true;
  481. }
  482. return false;
  483. }
  484. public void ForceHoverUnlock()
  485. {
  486. hoverLocked = false;
  487. }
  488. //-------------------------------------------------
  489. // Detach this GameObject from the attached object stack of this Hand
  490. //
  491. // objectToDetach - The GameObject to detach from this Hand
  492. //-------------------------------------------------
  493. public void DetachObject(GameObject objectToDetach, bool restoreOriginalParent = true)
  494. {
  495. int index = attachedObjects.FindIndex(l => l.attachedObject == objectToDetach);
  496. if (index != -1)
  497. {
  498. if (spewDebugText)
  499. HandDebugLog("DetachObject " + objectToDetach);
  500. GameObject prevTopObject = currentAttachedObject;
  501. if (attachedObjects[index].interactable != null)
  502. {
  503. if (attachedObjects[index].interactable.hideHandOnAttach)
  504. Show();
  505. if (attachedObjects[index].interactable.hideSkeletonOnAttach && mainRenderModel != null && mainRenderModel.displayHandByDefault)
  506. ShowSkeleton();
  507. if (attachedObjects[index].interactable.hideControllerOnAttach && mainRenderModel != null && mainRenderModel.displayControllerByDefault)
  508. ShowController();
  509. if (attachedObjects[index].interactable.handAnimationOnPickup != 0)
  510. StopAnimation();
  511. if (attachedObjects[index].interactable.setRangeOfMotionOnPickup != SkeletalMotionRangeChange.None)
  512. ResetTemporarySkeletonRangeOfMotion();
  513. }
  514. Transform parentTransform = null;
  515. if (attachedObjects[index].isParentedToHand)
  516. {
  517. if (restoreOriginalParent && (attachedObjects[index].originalParent != null))
  518. {
  519. parentTransform = attachedObjects[index].originalParent.transform;
  520. }
  521. if (attachedObjects[index].attachedObject != null)
  522. {
  523. attachedObjects[index].attachedObject.transform.parent = parentTransform;
  524. }
  525. }
  526. if (attachedObjects[index].HasAttachFlag(AttachmentFlags.TurnOnKinematic))
  527. {
  528. if (attachedObjects[index].attachedRigidbody != null)
  529. {
  530. attachedObjects[index].attachedRigidbody.isKinematic = attachedObjects[index].attachedRigidbodyWasKinematic;
  531. attachedObjects[index].attachedRigidbody.collisionDetectionMode = attachedObjects[index].collisionDetectionMode;
  532. }
  533. }
  534. if (attachedObjects[index].HasAttachFlag(AttachmentFlags.TurnOffGravity))
  535. {
  536. if (attachedObjects[index].attachedObject != null)
  537. {
  538. if (attachedObjects[index].attachedRigidbody != null)
  539. attachedObjects[index].attachedRigidbody.useGravity = attachedObjects[index].attachedRigidbodyUsedGravity;
  540. }
  541. }
  542. if (attachedObjects[index].interactable != null && attachedObjects[index].interactable.handFollowTransform && HasSkeleton())
  543. {
  544. skeleton.transform.localPosition = Vector3.zero;
  545. skeleton.transform.localRotation = Quaternion.identity;
  546. }
  547. if (attachedObjects[index].attachedObject != null)
  548. {
  549. if (attachedObjects[index].interactable == null || (attachedObjects[index].interactable != null && attachedObjects[index].interactable.isDestroying == false))
  550. attachedObjects[index].attachedObject.SetActive(true);
  551. attachedObjects[index].attachedObject.SendMessage("OnDetachedFromHand", this, SendMessageOptions.DontRequireReceiver);
  552. }
  553. attachedObjects.RemoveAt(index);
  554. CleanUpAttachedObjectStack();
  555. GameObject newTopObject = currentAttachedObject;
  556. hoverLocked = false;
  557. //Give focus to the top most object on the stack if it changed
  558. if (newTopObject != null && newTopObject != prevTopObject)
  559. {
  560. newTopObject.SetActive(true);
  561. newTopObject.SendMessage("OnHandFocusAcquired", this, SendMessageOptions.DontRequireReceiver);
  562. }
  563. }
  564. CleanUpAttachedObjectStack();
  565. if (mainRenderModel != null)
  566. mainRenderModel.MatchHandToTransform(mainRenderModel.transform);
  567. if (hoverhighlightRenderModel != null)
  568. hoverhighlightRenderModel.MatchHandToTransform(hoverhighlightRenderModel.transform);
  569. }
  570. //-------------------------------------------------
  571. // Get the world velocity of the VR Hand.
  572. //-------------------------------------------------
  573. public Vector3 GetTrackedObjectVelocity(float timeOffset = 0)
  574. {
  575. if (trackedObject == null)
  576. {
  577. Vector3 velocityTarget, angularTarget;
  578. GetUpdatedAttachedVelocities(currentAttachedObjectInfo.Value, out velocityTarget, out angularTarget);
  579. return velocityTarget;
  580. }
  581. if (isActive)
  582. {
  583. if (timeOffset == 0)
  584. return Player.instance.trackingOriginTransform.TransformVector(trackedObject.GetVelocity());
  585. else
  586. {
  587. Vector3 velocity;
  588. Vector3 angularVelocity;
  589. trackedObject.GetVelocitiesAtTimeOffset(timeOffset, out velocity, out angularVelocity);
  590. return Player.instance.trackingOriginTransform.TransformVector(velocity);
  591. }
  592. }
  593. return Vector3.zero;
  594. }
  595. //-------------------------------------------------
  596. // Get the world space angular velocity of the VR Hand.
  597. //-------------------------------------------------
  598. public Vector3 GetTrackedObjectAngularVelocity(float timeOffset = 0)
  599. {
  600. if (trackedObject == null)
  601. {
  602. Vector3 velocityTarget, angularTarget;
  603. GetUpdatedAttachedVelocities(currentAttachedObjectInfo.Value, out velocityTarget, out angularTarget);
  604. return angularTarget;
  605. }
  606. if (isActive)
  607. {
  608. if (timeOffset == 0)
  609. return Player.instance.trackingOriginTransform.TransformDirection(trackedObject.GetAngularVelocity());
  610. else
  611. {
  612. Vector3 velocity;
  613. Vector3 angularVelocity;
  614. trackedObject.GetVelocitiesAtTimeOffset(timeOffset, out velocity, out angularVelocity);
  615. return Player.instance.trackingOriginTransform.TransformDirection(angularVelocity);
  616. }
  617. }
  618. return Vector3.zero;
  619. }
  620. public void GetEstimatedPeakVelocities(out Vector3 velocity, out Vector3 angularVelocity)
  621. {
  622. trackedObject.GetEstimatedPeakVelocities(out velocity, out angularVelocity);
  623. velocity = Player.instance.trackingOriginTransform.TransformVector(velocity);
  624. angularVelocity = Player.instance.trackingOriginTransform.TransformDirection(angularVelocity);
  625. }
  626. //-------------------------------------------------
  627. private void CleanUpAttachedObjectStack()
  628. {
  629. attachedObjects.RemoveAll(l => l.attachedObject == null);
  630. }
  631. //-------------------------------------------------
  632. protected virtual void Awake()
  633. {
  634. inputFocusAction = SteamVR_Events.InputFocusAction(OnInputFocus);
  635. if (hoverSphereTransform == null)
  636. hoverSphereTransform = this.transform;
  637. if (objectAttachmentPoint == null)
  638. objectAttachmentPoint = this.transform;
  639. applicationLostFocusObject = new GameObject("_application_lost_focus");
  640. applicationLostFocusObject.transform.parent = transform;
  641. applicationLostFocusObject.SetActive(false);
  642. if (trackedObject == null)
  643. {
  644. trackedObject = this.gameObject.GetComponent<SteamVR_Behaviour_Pose>();
  645. if (trackedObject != null)
  646. trackedObject.onTransformUpdatedEvent += OnTransformUpdated;
  647. }
  648. }
  649. protected virtual void OnDestroy()
  650. {
  651. if (trackedObject != null)
  652. {
  653. trackedObject.onTransformUpdatedEvent -= OnTransformUpdated;
  654. }
  655. }
  656. protected virtual void OnTransformUpdated(SteamVR_Behaviour_Pose updatedPose, SteamVR_Input_Sources updatedSource)
  657. {
  658. HandFollowUpdate();
  659. }
  660. //-------------------------------------------------
  661. protected virtual IEnumerator Start()
  662. {
  663. // save off player instance
  664. playerInstance = Player.instance;
  665. if (!playerInstance)
  666. {
  667. Debug.LogError("<b>[SteamVR Interaction]</b> No player instance found in Hand Start()", this);
  668. }
  669. if (this.gameObject.layer == 0)
  670. Debug.LogWarning("<b>[SteamVR Interaction]</b> Hand is on default layer. This puts unnecessary strain on hover checks as it is always true for hand colliders (which are then ignored).", this);
  671. else
  672. hoverLayerMask &= ~(1 << this.gameObject.layer); //ignore self for hovering
  673. // allocate array for colliders
  674. overlappingColliders = new Collider[ColliderArraySize];
  675. // We are a "no SteamVR fallback hand" if we have this camera set
  676. // we'll use the right mouse to look around and left mouse to interact
  677. // - don't need to find the device
  678. if (noSteamVRFallbackCamera)
  679. {
  680. yield break;
  681. }
  682. //Debug.Log( "<b>[SteamVR Interaction]</b> Hand - initializing connection routine" );
  683. while (true)
  684. {
  685. if (isPoseValid)
  686. {
  687. InitController();
  688. break;
  689. }
  690. yield return null;
  691. }
  692. }
  693. //-------------------------------------------------
  694. protected virtual void UpdateHovering()
  695. {
  696. if ((noSteamVRFallbackCamera == null) && (isActive == false))
  697. {
  698. return;
  699. }
  700. if (hoverLocked)
  701. return;
  702. if (applicationLostFocusObject.activeSelf)
  703. return;
  704. float closestDistance = float.MaxValue;
  705. Interactable closestInteractable = null;
  706. if (useHoverSphere)
  707. {
  708. float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
  709. CheckHoveringForTransform(hoverSphereTransform.position, scaledHoverRadius, ref closestDistance, ref closestInteractable, Color.green);
  710. }
  711. if (useControllerHoverComponent && mainRenderModel != null && mainRenderModel.IsControllerVisibile())
  712. {
  713. float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  714. CheckHoveringForTransform(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.blue);
  715. }
  716. if (useFingerJointHover && mainRenderModel != null && mainRenderModel.IsHandVisibile())
  717. {
  718. float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  719. CheckHoveringForTransform(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2f, ref closestDistance, ref closestInteractable, Color.yellow);
  720. }
  721. // Hover on this one
  722. hoveringInteractable = closestInteractable;
  723. }
  724. protected virtual bool CheckHoveringForTransform(Vector3 hoverPosition, float hoverRadius, ref float closestDistance, ref Interactable closestInteractable, Color debugColor)
  725. {
  726. bool foundCloser = false;
  727. // null out old vals
  728. for (int i = 0; i < overlappingColliders.Length; ++i)
  729. {
  730. overlappingColliders[i] = null;
  731. }
  732. int numColliding = Physics.OverlapSphereNonAlloc(hoverPosition, hoverRadius, overlappingColliders, hoverLayerMask.value);
  733. if (numColliding >= ColliderArraySize)
  734. Debug.LogWarning("<b>[SteamVR Interaction]</b> This hand is overlapping the max number of colliders: " + ColliderArraySize + ". Some collisions may be missed. Increase ColliderArraySize on Hand.cs");
  735. // DebugVar
  736. int iActualColliderCount = 0;
  737. // Pick the closest hovering
  738. for (int colliderIndex = 0; colliderIndex < overlappingColliders.Length; colliderIndex++)
  739. {
  740. Collider collider = overlappingColliders[colliderIndex];
  741. if (collider == null)
  742. continue;
  743. Interactable contacting = collider.GetComponentInParent<Interactable>();
  744. // Yeah, it's null, skip
  745. if (contacting == null)
  746. continue;
  747. // Ignore this collider for hovering
  748. IgnoreHovering ignore = collider.GetComponent<IgnoreHovering>();
  749. if (ignore != null)
  750. {
  751. if (ignore.onlyIgnoreHand == null || ignore.onlyIgnoreHand == this)
  752. {
  753. continue;
  754. }
  755. }
  756. // Can't hover over the object if it's attached
  757. bool hoveringOverAttached = false;
  758. for (int attachedIndex = 0; attachedIndex < attachedObjects.Count; attachedIndex++)
  759. {
  760. if (attachedObjects[attachedIndex].attachedObject == contacting.gameObject)
  761. {
  762. hoveringOverAttached = true;
  763. break;
  764. }
  765. }
  766. if (hoveringOverAttached)
  767. continue;
  768. // Best candidate so far...
  769. float distance = Vector3.Distance(contacting.transform.position, hoverPosition);
  770. //float distance = Vector3.Distance(collider.bounds.center, hoverPosition);
  771. bool lowerPriority = false;
  772. if (closestInteractable != null)
  773. { // compare to closest interactable to check priority
  774. lowerPriority = contacting.hoverPriority < closestInteractable.hoverPriority;
  775. }
  776. bool isCloser = (distance < closestDistance);
  777. if (isCloser && !lowerPriority)
  778. {
  779. closestDistance = distance;
  780. closestInteractable = contacting;
  781. foundCloser = true;
  782. }
  783. iActualColliderCount++;
  784. }
  785. if (showDebugInteractables && foundCloser)
  786. {
  787. Debug.DrawLine(hoverPosition, closestInteractable.transform.position, debugColor, .05f, false);
  788. }
  789. if (iActualColliderCount > 0 && iActualColliderCount != prevOverlappingColliders)
  790. {
  791. prevOverlappingColliders = iActualColliderCount;
  792. if (spewDebugText)
  793. HandDebugLog("Found " + iActualColliderCount + " overlapping colliders.");
  794. }
  795. return foundCloser;
  796. }
  797. //-------------------------------------------------
  798. protected virtual void UpdateNoSteamVRFallback()
  799. {
  800. if (noSteamVRFallbackCamera)
  801. {
  802. Ray ray = noSteamVRFallbackCamera.ScreenPointToRay(Input.mousePosition);
  803. if (attachedObjects.Count > 0)
  804. {
  805. // Holding down the mouse:
  806. // move around a fixed distance from the camera
  807. transform.position = ray.origin + noSteamVRFallbackInteractorDistance * ray.direction;
  808. }
  809. else
  810. {
  811. // Not holding down the mouse:
  812. // cast out a ray to see what we should mouse over
  813. // Don't want to hit the hand and anything underneath it
  814. // So move it back behind the camera when we do the raycast
  815. Vector3 oldPosition = transform.position;
  816. transform.position = noSteamVRFallbackCamera.transform.forward * (-1000.0f);
  817. RaycastHit raycastHit;
  818. if (Physics.Raycast(ray, out raycastHit, noSteamVRFallbackMaxDistanceNoItem))
  819. {
  820. transform.position = raycastHit.point;
  821. // Remember this distance in case we click and drag the mouse
  822. noSteamVRFallbackInteractorDistance = Mathf.Min(noSteamVRFallbackMaxDistanceNoItem, raycastHit.distance);
  823. }
  824. else if (noSteamVRFallbackInteractorDistance > 0.0f)
  825. {
  826. // Move it around at the distance we last had a hit
  827. transform.position = ray.origin + Mathf.Min(noSteamVRFallbackMaxDistanceNoItem, noSteamVRFallbackInteractorDistance) * ray.direction;
  828. }
  829. else
  830. {
  831. // Didn't hit, just leave it where it was
  832. transform.position = oldPosition;
  833. }
  834. }
  835. }
  836. }
  837. //-------------------------------------------------
  838. private void UpdateDebugText()
  839. {
  840. if (showDebugText)
  841. {
  842. if (debugText == null)
  843. {
  844. debugText = new GameObject("_debug_text").AddComponent<TextMesh>();
  845. debugText.fontSize = 120;
  846. debugText.characterSize = 0.001f;
  847. debugText.transform.parent = transform;
  848. debugText.transform.localRotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);
  849. }
  850. if (handType == SteamVR_Input_Sources.RightHand)
  851. {
  852. debugText.transform.localPosition = new Vector3(-0.05f, 0.0f, 0.0f);
  853. debugText.alignment = TextAlignment.Right;
  854. debugText.anchor = TextAnchor.UpperRight;
  855. }
  856. else
  857. {
  858. debugText.transform.localPosition = new Vector3(0.05f, 0.0f, 0.0f);
  859. debugText.alignment = TextAlignment.Left;
  860. debugText.anchor = TextAnchor.UpperLeft;
  861. }
  862. debugText.text = string.Format(
  863. "Hovering: {0}\n" +
  864. "Hover Lock: {1}\n" +
  865. "Attached: {2}\n" +
  866. "Total Attached: {3}\n" +
  867. "Type: {4}\n",
  868. (hoveringInteractable ? hoveringInteractable.gameObject.name : "null"),
  869. hoverLocked,
  870. (currentAttachedObject ? currentAttachedObject.name : "null"),
  871. attachedObjects.Count,
  872. handType.ToString());
  873. }
  874. else
  875. {
  876. if (debugText != null)
  877. {
  878. Destroy(debugText.gameObject);
  879. }
  880. }
  881. }
  882. //-------------------------------------------------
  883. protected virtual void OnEnable()
  884. {
  885. inputFocusAction.enabled = true;
  886. // Stagger updates between hands
  887. float hoverUpdateBegin = ((otherHand != null) && (otherHand.GetInstanceID() < GetInstanceID())) ? (0.5f * hoverUpdateInterval) : (0.0f);
  888. InvokeRepeating("UpdateHovering", hoverUpdateBegin, hoverUpdateInterval);
  889. InvokeRepeating("UpdateDebugText", hoverUpdateBegin, hoverUpdateInterval);
  890. }
  891. //-------------------------------------------------
  892. protected virtual void OnDisable()
  893. {
  894. inputFocusAction.enabled = false;
  895. CancelInvoke();
  896. }
  897. //-------------------------------------------------
  898. protected virtual void Update()
  899. {
  900. UpdateNoSteamVRFallback();
  901. GameObject attachedObject = currentAttachedObject;
  902. if (attachedObject != null)
  903. {
  904. attachedObject.SendMessage("HandAttachedUpdate", this, SendMessageOptions.DontRequireReceiver);
  905. }
  906. if (hoveringInteractable)
  907. {
  908. hoveringInteractable.SendMessage("HandHoverUpdate", this, SendMessageOptions.DontRequireReceiver);
  909. }
  910. }
  911. /// <summary>
  912. /// Returns true when the hand is currently hovering over the interactable passed in
  913. /// </summary>
  914. public bool IsStillHovering(Interactable interactable)
  915. {
  916. return hoveringInteractable == interactable;
  917. }
  918. protected virtual void HandFollowUpdate()
  919. {
  920. GameObject attachedObject = currentAttachedObject;
  921. if (attachedObject != null)
  922. {
  923. if (currentAttachedObjectInfo.Value.interactable != null)
  924. {
  925. SteamVR_Skeleton_PoseSnapshot pose = null;
  926. if (currentAttachedObjectInfo.Value.interactable.skeletonPoser != null && HasSkeleton())
  927. {
  928. pose = currentAttachedObjectInfo.Value.interactable.skeletonPoser.GetBlendedPose(skeleton);
  929. }
  930. if (currentAttachedObjectInfo.Value.interactable.handFollowTransform)
  931. {
  932. Quaternion targetHandRotation;
  933. Vector3 targetHandPosition;
  934. if (pose == null)
  935. {
  936. Quaternion offset = Quaternion.Inverse(this.transform.rotation) * currentAttachedObjectInfo.Value.handAttachmentPointTransform.rotation;
  937. targetHandRotation = currentAttachedObjectInfo.Value.interactable.transform.rotation * Quaternion.Inverse(offset);
  938. Vector3 worldOffset = (this.transform.position - currentAttachedObjectInfo.Value.handAttachmentPointTransform.position);
  939. Quaternion rotationDiff = mainRenderModel.GetHandRotation() * Quaternion.Inverse(this.transform.rotation);
  940. Vector3 localOffset = rotationDiff * worldOffset;
  941. targetHandPosition = currentAttachedObjectInfo.Value.interactable.transform.position + localOffset;
  942. }
  943. else
  944. {
  945. Transform objectT = currentAttachedObjectInfo.Value.attachedObject.transform;
  946. Vector3 oldItemPos = objectT.position;
  947. Quaternion oldItemRot = objectT.transform.rotation;
  948. objectT.position = TargetItemPosition(currentAttachedObjectInfo.Value);
  949. objectT.rotation = TargetItemRotation(currentAttachedObjectInfo.Value);
  950. Vector3 localSkelePos = objectT.InverseTransformPoint(transform.position);
  951. Quaternion localSkeleRot = Quaternion.Inverse(objectT.rotation) * transform.rotation;
  952. objectT.position = oldItemPos;
  953. objectT.rotation = oldItemRot;
  954. targetHandPosition = objectT.TransformPoint(localSkelePos);
  955. targetHandRotation = objectT.rotation * localSkeleRot;
  956. }
  957. if (mainRenderModel != null)
  958. mainRenderModel.SetHandRotation(targetHandRotation);
  959. if (hoverhighlightRenderModel != null)
  960. hoverhighlightRenderModel.SetHandRotation(targetHandRotation);
  961. if (mainRenderModel != null)
  962. mainRenderModel.SetHandPosition(targetHandPosition);
  963. if (hoverhighlightRenderModel != null)
  964. hoverhighlightRenderModel.SetHandPosition(targetHandPosition);
  965. }
  966. }
  967. }
  968. }
  969. protected virtual void FixedUpdate()
  970. {
  971. if (currentAttachedObject != null)
  972. {
  973. AttachedObject attachedInfo = currentAttachedObjectInfo.Value;
  974. if (attachedInfo.attachedObject != null)
  975. {
  976. if (attachedInfo.HasAttachFlag(AttachmentFlags.VelocityMovement))
  977. {
  978. if (attachedInfo.interactable.attachEaseIn == false || attachedInfo.interactable.snapAttachEaseInCompleted)
  979. UpdateAttachedVelocity(attachedInfo);
  980. /*if (attachedInfo.interactable.handFollowTransformPosition)
  981. {
  982. skeleton.transform.position = TargetSkeletonPosition(attachedInfo);
  983. skeleton.transform.rotation = attachedInfo.attachedObject.transform.rotation * attachedInfo.skeletonLockRotation;
  984. }*/
  985. }
  986. else
  987. {
  988. if (attachedInfo.HasAttachFlag(AttachmentFlags.ParentToHand))
  989. {
  990. attachedInfo.attachedObject.transform.position = TargetItemPosition(attachedInfo);
  991. attachedInfo.attachedObject.transform.rotation = TargetItemRotation(attachedInfo);
  992. }
  993. }
  994. if (attachedInfo.interactable.attachEaseIn)
  995. {
  996. float t = Util.RemapNumberClamped(Time.time, attachedInfo.attachTime, attachedInfo.attachTime + attachedInfo.interactable.snapAttachEaseInTime, 0.0f, 1.0f);
  997. if (t < 1.0f)
  998. {
  999. if (attachedInfo.HasAttachFlag(AttachmentFlags.VelocityMovement))
  1000. {
  1001. attachedInfo.attachedRigidbody.velocity = Vector3.zero;
  1002. attachedInfo.attachedRigidbody.angularVelocity = Vector3.zero;
  1003. }
  1004. t = attachedInfo.interactable.snapAttachEaseInCurve.Evaluate(t);
  1005. attachedInfo.attachedObject.transform.position = Vector3.Lerp(attachedInfo.easeSourcePosition, TargetItemPosition(attachedInfo), t);
  1006. attachedInfo.attachedObject.transform.rotation = Quaternion.Lerp(attachedInfo.easeSourceRotation, TargetItemRotation(attachedInfo), t);
  1007. }
  1008. else if (!attachedInfo.interactable.snapAttachEaseInCompleted)
  1009. {
  1010. attachedInfo.interactable.gameObject.SendMessage("OnThrowableAttachEaseInCompleted", this, SendMessageOptions.DontRequireReceiver);
  1011. attachedInfo.interactable.snapAttachEaseInCompleted = true;
  1012. }
  1013. }
  1014. }
  1015. }
  1016. }
  1017. protected const float MaxVelocityChange = 10f;
  1018. protected const float VelocityMagic = 6000f;
  1019. protected const float AngularVelocityMagic = 50f;
  1020. protected const float MaxAngularVelocityChange = 20f;
  1021. protected void UpdateAttachedVelocity(AttachedObject attachedObjectInfo)
  1022. {
  1023. Vector3 velocityTarget, angularTarget;
  1024. bool success = GetUpdatedAttachedVelocities(attachedObjectInfo, out velocityTarget, out angularTarget);
  1025. if (success)
  1026. {
  1027. float scale = SteamVR_Utils.GetLossyScale(currentAttachedObjectInfo.Value.handAttachmentPointTransform);
  1028. float maxAngularVelocityChange = MaxAngularVelocityChange * scale;
  1029. float maxVelocityChange = MaxVelocityChange * scale;
  1030. attachedObjectInfo.attachedRigidbody.velocity = Vector3.MoveTowards(attachedObjectInfo.attachedRigidbody.velocity, velocityTarget, maxVelocityChange);
  1031. attachedObjectInfo.attachedRigidbody.angularVelocity = Vector3.MoveTowards(attachedObjectInfo.attachedRigidbody.angularVelocity, angularTarget, maxAngularVelocityChange);
  1032. }
  1033. }
  1034. /// <summary>
  1035. /// Snap an attached object to its target position and rotation. Good for error correction.
  1036. /// </summary>
  1037. public void ResetAttachedTransform(AttachedObject attachedObject)
  1038. {
  1039. attachedObject.attachedObject.transform.position = TargetItemPosition(attachedObject);
  1040. attachedObject.attachedObject.transform.rotation = TargetItemRotation(attachedObject);
  1041. }
  1042. protected Vector3 TargetItemPosition(AttachedObject attachedObject)
  1043. {
  1044. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  1045. {
  1046. Vector3 tp = attachedObject.handAttachmentPointTransform.InverseTransformPoint(transform.TransformPoint(attachedObject.interactable.skeletonPoser.GetBlendedPose(skeleton).position));
  1047. //tp.x *= -1;
  1048. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.TransformPoint(tp);
  1049. }
  1050. else
  1051. {
  1052. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.TransformPoint(attachedObject.initialPositionalOffset);
  1053. }
  1054. }
  1055. protected Quaternion TargetItemRotation(AttachedObject attachedObject)
  1056. {
  1057. if (attachedObject.interactable != null && attachedObject.interactable.skeletonPoser != null && HasSkeleton())
  1058. {
  1059. Quaternion tr = Quaternion.Inverse(attachedObject.handAttachmentPointTransform.rotation) * (transform.rotation * attachedObject.interactable.skeletonPoser.GetBlendedPose(skeleton).rotation);
  1060. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.rotation * tr;
  1061. }
  1062. else
  1063. {
  1064. return currentAttachedObjectInfo.Value.handAttachmentPointTransform.rotation * attachedObject.initialRotationalOffset;
  1065. }
  1066. }
  1067. protected bool GetUpdatedAttachedVelocities(AttachedObject attachedObjectInfo, out Vector3 velocityTarget, out Vector3 angularTarget)
  1068. {
  1069. bool realNumbers = false;
  1070. float velocityMagic = VelocityMagic;
  1071. float angularVelocityMagic = AngularVelocityMagic;
  1072. Vector3 targetItemPosition = TargetItemPosition(attachedObjectInfo);
  1073. Vector3 positionDelta = (targetItemPosition - attachedObjectInfo.attachedRigidbody.position);
  1074. velocityTarget = (positionDelta * velocityMagic * Time.deltaTime);
  1075. if (float.IsNaN(velocityTarget.x) == false && float.IsInfinity(velocityTarget.x) == false)
  1076. {
  1077. if (noSteamVRFallbackCamera)
  1078. velocityTarget /= 10; //hacky fix for fallback
  1079. realNumbers = true;
  1080. }
  1081. else
  1082. velocityTarget = Vector3.zero;
  1083. Quaternion targetItemRotation = TargetItemRotation(attachedObjectInfo);
  1084. Quaternion rotationDelta = targetItemRotation * Quaternion.Inverse(attachedObjectInfo.attachedObject.transform.rotation);
  1085. float angle;
  1086. Vector3 axis;
  1087. rotationDelta.ToAngleAxis(out angle, out axis);
  1088. if (angle > 180)
  1089. angle -= 360;
  1090. if (angle != 0 && float.IsNaN(axis.x) == false && float.IsInfinity(axis.x) == false)
  1091. {
  1092. angularTarget = angle * axis * angularVelocityMagic * Time.deltaTime;
  1093. if (noSteamVRFallbackCamera)
  1094. angularTarget /= 10; //hacky fix for fallback
  1095. realNumbers &= true;
  1096. }
  1097. else
  1098. angularTarget = Vector3.zero;
  1099. return realNumbers;
  1100. }
  1101. //-------------------------------------------------
  1102. protected virtual void OnInputFocus(bool hasFocus)
  1103. {
  1104. if (hasFocus)
  1105. {
  1106. DetachObject(applicationLostFocusObject, true);
  1107. applicationLostFocusObject.SetActive(false);
  1108. UpdateHovering();
  1109. BroadcastMessage("OnParentHandInputFocusAcquired", SendMessageOptions.DontRequireReceiver);
  1110. }
  1111. else
  1112. {
  1113. applicationLostFocusObject.SetActive(true);
  1114. AttachObject(applicationLostFocusObject, GrabTypes.Scripted, AttachmentFlags.ParentToHand);
  1115. BroadcastMessage("OnParentHandInputFocusLost", SendMessageOptions.DontRequireReceiver);
  1116. }
  1117. }
  1118. //-------------------------------------------------
  1119. protected virtual void OnDrawGizmos()
  1120. {
  1121. if (useHoverSphere && hoverSphereTransform != null)
  1122. {
  1123. Gizmos.color = Color.green;
  1124. float scaledHoverRadius = hoverSphereRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(hoverSphereTransform));
  1125. Gizmos.DrawWireSphere(hoverSphereTransform.position, scaledHoverRadius / 2);
  1126. }
  1127. if (useControllerHoverComponent && mainRenderModel != null && mainRenderModel.IsControllerVisibile())
  1128. {
  1129. Gizmos.color = Color.blue;
  1130. float scaledHoverRadius = controllerHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  1131. Gizmos.DrawWireSphere(mainRenderModel.GetControllerPosition(controllerHoverComponent), scaledHoverRadius / 2);
  1132. }
  1133. if (useFingerJointHover && mainRenderModel != null && mainRenderModel.IsHandVisibile())
  1134. {
  1135. Gizmos.color = Color.yellow;
  1136. float scaledHoverRadius = fingerJointHoverRadius * Mathf.Abs(SteamVR_Utils.GetLossyScale(this.transform));
  1137. Gizmos.DrawWireSphere(mainRenderModel.GetBonePosition((int)fingerJointHover), scaledHoverRadius / 2);
  1138. }
  1139. }
  1140. //-------------------------------------------------
  1141. private void HandDebugLog(string msg)
  1142. {
  1143. if (spewDebugText)
  1144. {
  1145. Debug.Log("<b>[SteamVR Interaction]</b> Hand (" + this.name + "): " + msg);
  1146. }
  1147. }
  1148. //-------------------------------------------------
  1149. // Continue to hover over this object indefinitely, whether or not the Hand moves out of its interaction trigger volume.
  1150. //
  1151. // interactable - The Interactable to hover over indefinitely.
  1152. //-------------------------------------------------
  1153. public void HoverLock(Interactable interactable)
  1154. {
  1155. if (spewDebugText)
  1156. HandDebugLog("HoverLock " + interactable);
  1157. hoverLocked = true;
  1158. hoveringInteractable = interactable;
  1159. }
  1160. //-------------------------------------------------
  1161. // Stop hovering over this object indefinitely.
  1162. //
  1163. // interactable - The hover-locked Interactable to stop hovering over indefinitely.
  1164. //-------------------------------------------------
  1165. public void HoverUnlock(Interactable interactable)
  1166. {
  1167. if (spewDebugText)
  1168. HandDebugLog("HoverUnlock " + interactable);
  1169. if (hoveringInteractable == interactable)
  1170. {
  1171. hoverLocked = false;
  1172. }
  1173. }
  1174. public void TriggerHapticPulse(ushort microSecondsDuration)
  1175. {
  1176. float seconds = (float)microSecondsDuration / 1000000f;
  1177. hapticAction.Execute(0, seconds, 1f / seconds, 1, handType);
  1178. }
  1179. public void TriggerHapticPulse(float duration, float frequency, float amplitude)
  1180. {
  1181. hapticAction.Execute(0, duration, frequency, amplitude, handType);
  1182. }
  1183. public void ShowGrabHint()
  1184. {
  1185. ControllerButtonHints.ShowButtonHint(this, grabGripAction); //todo: assess
  1186. }
  1187. public void HideGrabHint()
  1188. {
  1189. ControllerButtonHints.HideButtonHint(this, grabGripAction); //todo: assess
  1190. }
  1191. public void ShowGrabHint(string text)
  1192. {
  1193. ControllerButtonHints.ShowTextHint(this, grabGripAction, text);
  1194. }
  1195. public GrabTypes GetGrabStarting(GrabTypes explicitType = GrabTypes.None)
  1196. {
  1197. if (explicitType != GrabTypes.None)
  1198. {
  1199. if (noSteamVRFallbackCamera)
  1200. {
  1201. if (Input.GetMouseButtonDown(0))
  1202. return explicitType;
  1203. else
  1204. return GrabTypes.None;
  1205. }
  1206. if (explicitType == GrabTypes.Pinch && grabPinchAction.GetStateDown(handType))
  1207. {
  1208. return GrabTypes.Pinch;
  1209. }
  1210. if (explicitType == GrabTypes.Grip && grabGripAction.GetStateDown(handType))
  1211. {
  1212. return GrabTypes.Grip;
  1213. }
  1214. }
  1215. else
  1216. {
  1217. if (noSteamVRFallbackCamera)
  1218. {
  1219. if (Input.GetMouseButtonDown(0))
  1220. return GrabTypes.Grip;
  1221. else
  1222. return GrabTypes.None;
  1223. }
  1224. if (grabPinchAction != null && grabPinchAction.GetStateDown(handType))
  1225. return GrabTypes.Pinch;
  1226. if (grabGripAction != null && grabGripAction.GetStateDown(handType))
  1227. return GrabTypes.Grip;
  1228. }
  1229. return GrabTypes.None;
  1230. }
  1231. public GrabTypes GetGrabEnding(GrabTypes explicitType = GrabTypes.None)
  1232. {
  1233. if (explicitType != GrabTypes.None)
  1234. {
  1235. if (noSteamVRFallbackCamera)
  1236. {
  1237. if (Input.GetMouseButtonUp(0))
  1238. return explicitType;
  1239. else
  1240. return GrabTypes.None;
  1241. }
  1242. if (explicitType == GrabTypes.Pinch && grabPinchAction.GetStateUp(handType))
  1243. return GrabTypes.Pinch;
  1244. if (explicitType == GrabTypes.Grip && grabGripAction.GetStateUp(handType))
  1245. return GrabTypes.Grip;
  1246. }
  1247. else
  1248. {
  1249. if (noSteamVRFallbackCamera)
  1250. {
  1251. if (Input.GetMouseButtonUp(0))
  1252. return GrabTypes.Grip;
  1253. else
  1254. return GrabTypes.None;
  1255. }
  1256. if (grabPinchAction.GetStateUp(handType))
  1257. return GrabTypes.Pinch;
  1258. if (grabGripAction.GetStateUp(handType))
  1259. return GrabTypes.Grip;
  1260. }
  1261. return GrabTypes.None;
  1262. }
  1263. public bool IsGrabEnding(GameObject attachedObject)
  1264. {
  1265. for (int attachedObjectIndex = 0; attachedObjectIndex < attachedObjects.Count; attachedObjectIndex++)
  1266. {
  1267. if (attachedObjects[attachedObjectIndex].attachedObject == attachedObject)
  1268. {
  1269. return IsGrabbingWithType(attachedObjects[attachedObjectIndex].grabbedWithType) == false;
  1270. }
  1271. }
  1272. return false;
  1273. }
  1274. public bool IsGrabbingWithType(GrabTypes type)
  1275. {
  1276. if (noSteamVRFallbackCamera)
  1277. {
  1278. if (Input.GetMouseButton(0))
  1279. return true;
  1280. else
  1281. return false;
  1282. }
  1283. switch (type)
  1284. {
  1285. case GrabTypes.Pinch:
  1286. return grabPinchAction.GetState(handType);
  1287. case GrabTypes.Grip:
  1288. return grabGripAction.GetState(handType);
  1289. default:
  1290. return false;
  1291. }
  1292. }
  1293. public bool IsGrabbingWithOppositeType(GrabTypes type)
  1294. {
  1295. if (noSteamVRFallbackCamera)
  1296. {
  1297. if (Input.GetMouseButton(0))
  1298. return true;
  1299. else
  1300. return false;
  1301. }
  1302. switch (type)
  1303. {
  1304. case GrabTypes.Pinch:
  1305. return grabGripAction.GetState(handType);
  1306. case GrabTypes.Grip:
  1307. return grabPinchAction.GetState(handType);
  1308. default:
  1309. return false;
  1310. }
  1311. }
  1312. public GrabTypes GetBestGrabbingType()
  1313. {
  1314. return GetBestGrabbingType(GrabTypes.None);
  1315. }
  1316. public GrabTypes GetBestGrabbingType(GrabTypes preferred, bool forcePreference = false)
  1317. {
  1318. if (noSteamVRFallbackCamera)
  1319. {
  1320. if (Input.GetMouseButton(0))
  1321. return preferred;
  1322. else
  1323. return GrabTypes.None;
  1324. }
  1325. if (preferred == GrabTypes.Pinch)
  1326. {
  1327. if (grabPinchAction.GetState(handType))
  1328. return GrabTypes.Pinch;
  1329. else if (forcePreference)
  1330. return GrabTypes.None;
  1331. }
  1332. if (preferred == GrabTypes.Grip)
  1333. {
  1334. if (grabGripAction.GetState(handType))
  1335. return GrabTypes.Grip;
  1336. else if (forcePreference)
  1337. return GrabTypes.None;
  1338. }
  1339. if (grabPinchAction.GetState(handType))
  1340. return GrabTypes.Pinch;
  1341. if (grabGripAction.GetState(handType))
  1342. return GrabTypes.Grip;
  1343. return GrabTypes.None;
  1344. }
  1345. //-------------------------------------------------
  1346. private void InitController()
  1347. {
  1348. if (spewDebugText)
  1349. HandDebugLog("Hand " + name + " connected with type " + handType.ToString());
  1350. bool hadOldRendermodel = mainRenderModel != null;
  1351. EVRSkeletalMotionRange oldRM_rom = EVRSkeletalMotionRange.WithController;
  1352. if (hadOldRendermodel)
  1353. oldRM_rom = mainRenderModel.GetSkeletonRangeOfMotion;
  1354. foreach (RenderModel r in renderModels)
  1355. {
  1356. if (r != null)
  1357. Destroy(r.gameObject);
  1358. }
  1359. renderModels.Clear();
  1360. GameObject renderModelInstance = GameObject.Instantiate(renderModelPrefab);
  1361. renderModelInstance.layer = gameObject.layer;
  1362. renderModelInstance.tag = gameObject.tag;
  1363. renderModelInstance.transform.parent = this.transform;
  1364. renderModelInstance.transform.localPosition = Vector3.zero;
  1365. renderModelInstance.transform.localRotation = Quaternion.identity;
  1366. renderModelInstance.transform.localScale = renderModelPrefab.transform.localScale;
  1367. //TriggerHapticPulse(800); //pulse on controller init
  1368. int deviceIndex = trackedObject.GetDeviceIndex();
  1369. mainRenderModel = renderModelInstance.GetComponent<RenderModel>();
  1370. renderModels.Add(mainRenderModel);
  1371. if (hadOldRendermodel)
  1372. mainRenderModel.SetSkeletonRangeOfMotion(oldRM_rom);
  1373. this.BroadcastMessage("SetInputSource", handType, SendMessageOptions.DontRequireReceiver); // let child objects know we've initialized
  1374. this.BroadcastMessage("OnHandInitialized", deviceIndex, SendMessageOptions.DontRequireReceiver); // let child objects know we've initialized
  1375. }
  1376. public void SetRenderModel(GameObject prefab)
  1377. {
  1378. renderModelPrefab = prefab;
  1379. if (mainRenderModel != null && isPoseValid)
  1380. InitController();
  1381. }
  1382. public void SetHoverRenderModel(RenderModel hoverRenderModel)
  1383. {
  1384. hoverhighlightRenderModel = hoverRenderModel;
  1385. renderModels.Add(hoverRenderModel);
  1386. }
  1387. public int GetDeviceIndex()
  1388. {
  1389. return trackedObject.GetDeviceIndex();
  1390. }
  1391. }
  1392. [System.Serializable]
  1393. public class HandEvent : UnityEvent<Hand> { }
  1394. }