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.

396 lines
19 KiB

  1. // Bezier Pointer Renderer|PointerRenderers|10030
  2. namespace VRTK
  3. {
  4. using UnityEngine;
  5. /// <summary>
  6. /// A visual pointer representation of a curved beam made from multiple objects with an optional cursor at the end.
  7. /// </summary>
  8. /// <remarks>
  9. /// > The bezier curve generation code is in another script located at `VRTK/Source/Scripts/Internal/VRTK_CurveGenerator.cs` and was heavily inspired by the tutorial and code from [Catlike Coding](http://catlikecoding.com/unity/tutorials/curves-and-splines/).
  10. ///
  11. /// **Optional Components:**
  12. /// * `VRTK_PlayAreaCursor` - A Play Area Cursor that will track the position of the pointer cursor.
  13. /// * `VRTK_PointerDirectionIndicator` - A Pointer Direction Indicator that will track the position of the pointer cursor.
  14. ///
  15. /// **Script Usage:**
  16. /// * Place the `VRTK_BezierPointerRenderer` script on the same GameObject as the Pointer script it is linked to.
  17. /// * Link this Pointer Renderer script to the `Pointer Renderer` parameter on the required Pointer script.
  18. ///
  19. /// **Script Dependencies:**
  20. /// * A Pointer script to control the activation of this Pointer Renderer script.
  21. /// </remarks>
  22. /// <example>
  23. /// `VRTK/Examples/009_Controller_BezierPointer` is used in conjunction with the Height Adjust Teleporter shows how it is possible to traverse different height objects using the curved pointer without needing to see the top of the object.
  24. ///
  25. /// `VRTK/Examples/036_Controller_CustomCompoundPointer' shows how to display an object (a teleport beam) only if the teleport location is valid, and can create an animated trail along the tracer curve.
  26. /// </example>
  27. [AddComponentMenu("VRTK/Scripts/Pointers/Pointer Renderers/VRTK_BezierPointerRenderer")]
  28. public class VRTK_BezierPointerRenderer : VRTK_BasePointerRenderer
  29. {
  30. [Header("Bezier Pointer Appearance Settings")]
  31. [Tooltip("The maximum length of the projected beam. The x value is the length of the forward beam, the y value is the length of the downward beam.")]
  32. public Vector2 maximumLength = new Vector2(10f, float.PositiveInfinity);
  33. [Tooltip("The number of items to render in the bezier curve tracer beam. A high number here will most likely have a negative impact of game performance due to large number of rendered objects.")]
  34. public int tracerDensity = 10;
  35. [Tooltip("The size of the ground cursor. This number also affects the size of the objects in the bezier curve tracer beam. The larger the radius, the larger the objects will be.")]
  36. public float cursorRadius = 0.5f;
  37. [Header("Bezier Pointer Render Settings")]
  38. [Tooltip("The maximum angle in degrees of the origin before the beam curve height is restricted. A lower angle setting will prevent the beam being projected high into the sky and curving back down.")]
  39. [Range(1, 100)]
  40. public float heightLimitAngle = 100f;
  41. [Tooltip("The amount of height offset to apply to the projected beam to generate a smoother curve even when the beam is pointing straight.")]
  42. public float curveOffset = 1f;
  43. [Tooltip("Rescale each tracer element according to the length of the Bezier curve.")]
  44. public bool rescaleTracer = false;
  45. [Tooltip("The cursor will be rotated to match the angle of the target surface if this is true, if it is false then the pointer cursor will always be horizontal.")]
  46. public bool cursorMatchTargetRotation = false;
  47. [Tooltip("The number of points along the bezier curve to check for an early beam collision. Useful if the bezier curve is appearing to clip through teleport locations. 0 won't make any checks and it will be capped at `Pointer Density`. The higher the number, the more CPU intensive the checks become.")]
  48. public int collisionCheckFrequency = 0;
  49. [Header("Bezier Pointer Custom Appearance Settings")]
  50. [Tooltip("A custom game object to use as the appearance for the pointer tracer. If this is empty then a collection of Sphere primitives will be created and used.")]
  51. public GameObject customTracer;
  52. [Tooltip("A custom game object to use as the appearance for the pointer cursor. If this is empty then a Cylinder primitive will be created and used.")]
  53. public GameObject customCursor;
  54. [Tooltip("A custom game object can be applied here to appear only if the location is valid.")]
  55. public GameObject validLocationObject = null;
  56. [Tooltip("A custom game object can be applied here to appear only if the location is invalid.")]
  57. public GameObject invalidLocationObject = null;
  58. protected VRTK_CurveGenerator actualTracer;
  59. protected GameObject actualContainer;
  60. protected GameObject actualCursor;
  61. protected GameObject actualValidLocationObject = null;
  62. protected GameObject actualInvalidLocationObject = null;
  63. protected Vector3 fixedForwardBeamForward;
  64. /// <summary>
  65. /// The UpdateRenderer method is used to run an Update routine on the pointer.
  66. /// </summary>
  67. public override void UpdateRenderer()
  68. {
  69. if ((controllingPointer != null && (controllingPointer.IsPointerActive()) || IsVisible()))
  70. {
  71. Vector3 jointPosition = ProjectForwardBeam();
  72. Vector3 downPosition = ProjectDownBeam(jointPosition);
  73. AdjustForEarlyCollisions(jointPosition, downPosition);
  74. MakeRenderersVisible();
  75. }
  76. base.UpdateRenderer();
  77. }
  78. /// <summary>
  79. /// The GetPointerObjects returns an array of the auto generated GameObjects associated with the pointer.
  80. /// </summary>
  81. /// <returns>An array of pointer auto generated GameObjects.</returns>
  82. public override GameObject[] GetPointerObjects()
  83. {
  84. return new GameObject[] { actualContainer, actualCursor };
  85. }
  86. protected override void ToggleRenderer(bool pointerState, bool actualState)
  87. {
  88. TogglePointerCursor(pointerState, actualState);
  89. TogglePointerTracer(pointerState, actualState);
  90. if (actualTracer != null && actualState && tracerVisibility != VisibilityStates.AlwaysOn)
  91. {
  92. ToggleRendererVisibility(actualTracer.gameObject, false);
  93. AddVisibleRenderer(actualTracer.gameObject);
  94. }
  95. }
  96. protected override void CreatePointerObjects()
  97. {
  98. actualContainer = new GameObject(VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "BezierPointerRenderer_Container"));
  99. VRTK_PlayerObject.SetPlayerObject(actualContainer, VRTK_PlayerObject.ObjectTypes.Pointer);
  100. actualContainer.SetActive(false);
  101. CreateTracer();
  102. CreateCursor();
  103. Toggle(false, false);
  104. if (controllingPointer != null)
  105. {
  106. controllingPointer.ResetActivationTimer(true);
  107. controllingPointer.ResetSelectionTimer(true);
  108. }
  109. }
  110. protected override void DestroyPointerObjects()
  111. {
  112. if (actualCursor != null)
  113. {
  114. Destroy(actualCursor);
  115. }
  116. if (actualTracer != null)
  117. {
  118. Destroy(actualTracer);
  119. }
  120. if (actualContainer != null)
  121. {
  122. Destroy(actualContainer);
  123. }
  124. }
  125. protected override void UpdateObjectInteractor()
  126. {
  127. base.UpdateObjectInteractor();
  128. //if the object interactor is too far from the pointer tip then set it to the pointer tip position to prevent glitching.
  129. if (objectInteractor != null && actualCursor != null && Vector3.Distance(objectInteractor.transform.position, actualCursor.transform.position) > 0f)
  130. {
  131. objectInteractor.transform.position = actualCursor.transform.position;
  132. }
  133. }
  134. protected override void ChangeMaterial(Color givenColor)
  135. {
  136. base.ChangeMaterial(givenColor);
  137. ChangeMaterialColor(actualCursor, givenColor);
  138. }
  139. protected virtual void CreateTracer()
  140. {
  141. actualTracer = actualContainer.gameObject.AddComponent<VRTK_CurveGenerator>();
  142. actualTracer.transform.SetParent(null);
  143. actualTracer.Create(tracerDensity, cursorRadius, customTracer, rescaleTracer);
  144. }
  145. protected virtual GameObject CreateCursorObject()
  146. {
  147. float cursorYOffset = 0.02f;
  148. GameObject createdCursor = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
  149. MeshRenderer createdCursorRenderer = createdCursor.GetComponent<MeshRenderer>();
  150. createdCursor.transform.localScale = new Vector3(cursorRadius, cursorYOffset, cursorRadius);
  151. createdCursorRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
  152. createdCursorRenderer.receiveShadows = false;
  153. createdCursorRenderer.material = defaultMaterial;
  154. Destroy(createdCursor.GetComponent<CapsuleCollider>());
  155. return createdCursor;
  156. }
  157. protected virtual void CreateCursorLocations()
  158. {
  159. if (validLocationObject != null)
  160. {
  161. actualValidLocationObject = Instantiate(validLocationObject);
  162. actualValidLocationObject.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "BezierPointerRenderer_ValidLocation");
  163. actualValidLocationObject.transform.SetParent(actualCursor.transform);
  164. actualValidLocationObject.layer = LayerMask.NameToLayer("Ignore Raycast");
  165. actualValidLocationObject.SetActive(false);
  166. }
  167. if (invalidLocationObject != null)
  168. {
  169. actualInvalidLocationObject = Instantiate(invalidLocationObject);
  170. actualInvalidLocationObject.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "BezierPointerRenderer_InvalidLocation");
  171. actualInvalidLocationObject.transform.SetParent(actualCursor.transform);
  172. actualInvalidLocationObject.layer = LayerMask.NameToLayer("Ignore Raycast");
  173. actualInvalidLocationObject.SetActive(false);
  174. }
  175. }
  176. protected virtual void CreateCursor()
  177. {
  178. actualCursor = (customCursor != null ? Instantiate(customCursor) : CreateCursorObject());
  179. CreateCursorLocations();
  180. actualCursor.name = VRTK_SharedMethods.GenerateVRTKObjectName(true, gameObject.name, "BezierPointerRenderer_Cursor");
  181. VRTK_PlayerObject.SetPlayerObject(actualCursor, VRTK_PlayerObject.ObjectTypes.Pointer);
  182. actualCursor.layer = LayerMask.NameToLayer("Ignore Raycast");
  183. actualCursor.SetActive(false);
  184. }
  185. protected virtual Vector3 ProjectForwardBeam()
  186. {
  187. Transform origin = GetOrigin();
  188. float attachedRotation = Vector3.Dot(Vector3.up, origin.forward.normalized);
  189. float calculatedLength = maximumLength.x;
  190. Vector3 useForward = origin.forward;
  191. if ((attachedRotation * 100f) > heightLimitAngle)
  192. {
  193. useForward = new Vector3(useForward.x, fixedForwardBeamForward.y, useForward.z);
  194. float controllerRotationOffset = 1f - (attachedRotation - (heightLimitAngle / 100f));
  195. calculatedLength = (maximumLength.x * controllerRotationOffset) * controllerRotationOffset;
  196. }
  197. else
  198. {
  199. fixedForwardBeamForward = origin.forward;
  200. }
  201. float actualLength = calculatedLength;
  202. Ray pointerRaycast = new Ray(origin.position, useForward);
  203. RaycastHit collidedWith;
  204. bool hasRayHit = VRTK_CustomRaycast.Raycast(customRaycast, pointerRaycast, out collidedWith, defaultIgnoreLayer, calculatedLength);
  205. float contactDistance = 0f;
  206. //reset if beam not hitting or hitting new target
  207. if (!hasRayHit || (destinationHit.collider && destinationHit.collider != collidedWith.collider))
  208. {
  209. contactDistance = 0f;
  210. }
  211. //check if beam has hit a new target
  212. if (hasRayHit)
  213. {
  214. contactDistance = collidedWith.distance;
  215. }
  216. //adjust beam length if something is blocking it
  217. if (hasRayHit && contactDistance < calculatedLength)
  218. {
  219. actualLength = contactDistance;
  220. }
  221. //Use BEAM_ADJUST_OFFSET to move point back and up a bit to prevent beam clipping at collision point
  222. return (pointerRaycast.GetPoint(actualLength - BEAM_ADJUST_OFFSET) + (Vector3.up * BEAM_ADJUST_OFFSET));
  223. }
  224. protected virtual Vector3 ProjectDownBeam(Vector3 jointPosition)
  225. {
  226. Vector3 downPosition = Vector3.zero;
  227. Ray projectedBeamDownRaycast = new Ray(jointPosition, Vector3.down);
  228. RaycastHit collidedWith;
  229. bool downRayHit = VRTK_CustomRaycast.Raycast(customRaycast, projectedBeamDownRaycast, out collidedWith, defaultIgnoreLayer, maximumLength.y);
  230. if (!downRayHit || (destinationHit.collider && destinationHit.collider != collidedWith.collider))
  231. {
  232. if (destinationHit.collider != null)
  233. {
  234. PointerExit(destinationHit);
  235. }
  236. destinationHit = new RaycastHit();
  237. downPosition = projectedBeamDownRaycast.GetPoint(0f);
  238. }
  239. if (downRayHit)
  240. {
  241. downPosition = projectedBeamDownRaycast.GetPoint(collidedWith.distance);
  242. PointerEnter(collidedWith);
  243. destinationHit = collidedWith;
  244. }
  245. return downPosition;
  246. }
  247. protected virtual void AdjustForEarlyCollisions(Vector3 jointPosition, Vector3 downPosition)
  248. {
  249. Vector3 newDownPosition = downPosition;
  250. Vector3 newJointPosition = jointPosition;
  251. if (collisionCheckFrequency > 0 && actualTracer != null)
  252. {
  253. collisionCheckFrequency = Mathf.Clamp(collisionCheckFrequency, 0, tracerDensity);
  254. Vector3[] beamPoints = new Vector3[]
  255. {
  256. GetOrigin().position,
  257. jointPosition + new Vector3(0f, curveOffset, 0f),
  258. downPosition,
  259. downPosition,
  260. };
  261. Vector3[] checkPoints = actualTracer.GetPoints(beamPoints);
  262. int checkFrequency = tracerDensity / collisionCheckFrequency;
  263. for (int i = 0; i < tracerDensity - checkFrequency; i += checkFrequency)
  264. {
  265. Vector3 currentPoint = checkPoints[i];
  266. Vector3 nextPoint = (i + checkFrequency < checkPoints.Length ? checkPoints[i + checkFrequency] : checkPoints[checkPoints.Length - 1]);
  267. Vector3 nextPointDirection = (nextPoint - currentPoint).normalized;
  268. float nextPointDistance = Vector3.Distance(currentPoint, nextPoint);
  269. Ray checkCollisionRay = new Ray(currentPoint, nextPointDirection);
  270. RaycastHit checkCollisionHit;
  271. if (VRTK_CustomRaycast.Raycast(customRaycast, checkCollisionRay, out checkCollisionHit, defaultIgnoreLayer, nextPointDistance))
  272. {
  273. Vector3 collisionPoint = checkCollisionRay.GetPoint(checkCollisionHit.distance);
  274. Ray downwardCheckRay = new Ray(collisionPoint + (Vector3.up * 0.01f), Vector3.down);
  275. RaycastHit downwardCheckHit;
  276. if (VRTK_CustomRaycast.Raycast(customRaycast, downwardCheckRay, out downwardCheckHit, defaultIgnoreLayer, float.PositiveInfinity))
  277. {
  278. destinationHit = downwardCheckHit;
  279. newDownPosition = downwardCheckRay.GetPoint(downwardCheckHit.distance); ;
  280. newJointPosition = (newDownPosition.y < jointPosition.y ? new Vector3(newDownPosition.x, jointPosition.y, newDownPosition.z) : jointPosition);
  281. break;
  282. }
  283. }
  284. }
  285. }
  286. DisplayCurvedBeam(newJointPosition, newDownPosition);
  287. SetPointerCursor();
  288. }
  289. protected virtual void DisplayCurvedBeam(Vector3 jointPosition, Vector3 downPosition)
  290. {
  291. if (actualTracer != null)
  292. {
  293. Vector3[] beamPoints = new Vector3[]
  294. {
  295. GetOrigin(false).position,
  296. jointPosition + new Vector3(0f, curveOffset, 0f),
  297. downPosition,
  298. downPosition,
  299. };
  300. Material tracerMaterial = (customTracer != null ? null : defaultMaterial);
  301. actualTracer.SetPoints(beamPoints, tracerMaterial, currentColor);
  302. if (tracerVisibility == VisibilityStates.AlwaysOff)
  303. {
  304. TogglePointerTracer(false, false);
  305. }
  306. else if (controllingPointer != null)
  307. {
  308. TogglePointerTracer(controllingPointer.IsPointerActive(), controllingPointer.IsPointerActive());
  309. }
  310. }
  311. }
  312. protected virtual void TogglePointerCursor(bool pointerState, bool actualState)
  313. {
  314. ToggleElement(actualCursor, pointerState, actualState, cursorVisibility, ref cursorVisible);
  315. }
  316. protected virtual void TogglePointerTracer(bool pointerState, bool actualState)
  317. {
  318. tracerVisible = (tracerVisibility == VisibilityStates.AlwaysOn ? true : pointerState);
  319. if (actualTracer != null)
  320. {
  321. actualTracer.TogglePoints(tracerVisible);
  322. }
  323. }
  324. protected virtual void SetPointerCursor()
  325. {
  326. if (controllingPointer != null && destinationHit.transform)
  327. {
  328. TogglePointerCursor(controllingPointer.IsPointerActive(), controllingPointer.IsPointerActive());
  329. actualCursor.transform.position = destinationHit.point;
  330. if (cursorMatchTargetRotation)
  331. {
  332. actualCursor.transform.rotation = Quaternion.FromToRotation(Vector3.up, destinationHit.normal);
  333. }
  334. base.UpdateDependencies(actualCursor.transform.position);
  335. ChangeColor(validCollisionColor);
  336. if (actualValidLocationObject != null)
  337. {
  338. actualValidLocationObject.SetActive(ValidDestination() && IsValidCollision());
  339. }
  340. if (actualInvalidLocationObject != null)
  341. {
  342. actualInvalidLocationObject.SetActive(!ValidDestination() || !IsValidCollision());
  343. }
  344. }
  345. else
  346. {
  347. TogglePointerCursor(false, false);
  348. ChangeColor(invalidCollisionColor);
  349. }
  350. }
  351. }
  352. }