SW 중심대학 OSS GIT 서버 박건태, 이승준, 고기완, 이준호 새로운 배포
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.

340 lines
12 KiB

4 years ago
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.Serialization;
  4. // ReSharper disable UnusedMember.Global
  5. namespace ARLocation
  6. {
  7. using Utils;
  8. /// <summary>
  9. /// This component, when attached to a GameObject, makes it traverse a
  10. /// path that interpolates a given set of geographical locations.
  11. /// </summary>
  12. [AddComponentMenu("AR+GPS/Move Along Path")]
  13. [HelpURL("https://http://docs.unity-ar-gps-location.com/guide/#movealongpath")]
  14. [DisallowMultipleComponent]
  15. public class MoveAlongPath : MonoBehaviour
  16. {
  17. [Serializable]
  18. public class PathSettingsData
  19. {
  20. /// <summary>
  21. /// The LocationPath describing the path to be traversed.
  22. /// </summary>
  23. [Tooltip("The LocationPath describing the path to be traversed.")]
  24. public LocationPath LocationPath;
  25. /// <summary>
  26. /// The number of points-per-segment used to calculate the spline.
  27. /// </summary>
  28. [Tooltip("The number of points-per-segment used to calculate the spline.")]
  29. public int SplineSampleCount = 250;
  30. /// <summary>
  31. /// If present, renders the spline in the scene using the given line renderer.
  32. /// </summary>
  33. [FormerlySerializedAs("lineRenderer")] [Tooltip("If present, renders the spline in the scene using the given line renderer.")]
  34. public LineRenderer LineRenderer;
  35. }
  36. [Serializable]
  37. public class PlaybackSettingsData
  38. {
  39. /// <summary>
  40. /// The speed along the path.
  41. /// </summary>
  42. [Tooltip("The speed along the path.")]
  43. public float Speed = 0f;
  44. /// <summary>
  45. /// The up direction to be used for orientation along the path.
  46. /// </summary>
  47. [Tooltip("The up direction to be used for orientation along the path.")]
  48. public Vector3 Up = Vector3.up;
  49. /// <summary>
  50. /// If true, play the path traversal in a loop.
  51. /// </summary>
  52. [Tooltip("If true, play the path traversal in a loop.")]
  53. public bool Loop = true;
  54. /// <summary>
  55. /// If true, start playing automatically.
  56. /// </summary>
  57. [Tooltip("If true, start playing automatically.")]
  58. public bool AutoPlay = true;
  59. [FormerlySerializedAs("offset")] [Tooltip("The parameters offset; marks the initial position of the object along the curve.")]
  60. public float Offset;
  61. }
  62. [Serializable]
  63. public class PlacementSettingsData
  64. {
  65. [Tooltip("The altitude mode. The altitude modes of the individual path locations are ignored, and this will be used instead.")]
  66. public AltitudeMode AltitudeMode = AltitudeMode.DeviceRelative;
  67. [Tooltip(
  68. "The maximum number of times this object will be affected by GPS location updates. Zero means no limits are imposed.")]
  69. public uint MaxNumberOfLocationUpdates = 4;
  70. }
  71. [Serializable]
  72. public class StateData
  73. {
  74. public uint UpdateCount;
  75. public Vector3[] Points;
  76. public int PointCount;
  77. public bool Playing;
  78. public Spline Spline;
  79. public Vector3 Translation;
  80. public float Speed;
  81. }
  82. public PathSettingsData PathSettings = new PathSettingsData();
  83. public PlaybackSettingsData PlaybackSettings = new PlaybackSettingsData();
  84. public PlacementSettingsData PlacementSettings = new PlacementSettingsData();
  85. public float Speed
  86. {
  87. get => state.Speed;
  88. set => state.Speed = value;
  89. }
  90. [Space(4.0f)]
  91. [Header("Debug")]
  92. [Tooltip("When debug mode is enabled, this component will print relevant messages to the console. Filter by 'MoveAlongPath' in the log output to see the messages.")]
  93. public bool DebugMode;
  94. [Space(4.0f)]
  95. private StateData state = new StateData();
  96. private ARLocationProvider locationProvider;
  97. private float u;
  98. private GameObject arLocationRoot;
  99. private Transform mainCameraTransform;
  100. private bool useLineRenderer;
  101. private bool hasInitialized;
  102. private GroundHeight groundHeight;
  103. private bool HeightRelativeToDevice => PlacementSettings.AltitudeMode == AltitudeMode.DeviceRelative;
  104. private bool HeightGroundRelative => PlacementSettings.AltitudeMode == AltitudeMode.GroundRelative;
  105. /// <summary>
  106. /// Change the `LocationPath` the GameObject will traverse.
  107. /// </summary>
  108. /// <param name="path"></param>
  109. public void SetLocationPath(LocationPath path)
  110. {
  111. PathSettings.LocationPath = path;
  112. state.PointCount = PathSettings.LocationPath.Locations.Length;
  113. state.Points = new Vector3[state.PointCount];
  114. BuildSpline(locationProvider.CurrentLocation.ToLocation());
  115. }
  116. void Start()
  117. {
  118. if (PathSettings.LocationPath == null)
  119. {
  120. throw new NullReferenceException("[AR+GPS][MoveAlongPath]: Null Path! Please set the 'LocationPath' property!");
  121. }
  122. locationProvider = ARLocationProvider.Instance;
  123. locationProvider.OnLocationUpdatedEvent(LocationUpdated);
  124. mainCameraTransform = ARLocationManager.Instance.MainCamera.transform;
  125. arLocationRoot = ARLocationManager.Instance.gameObject; // Misc.FindAndLogError("ARLocationRoot", "[ARLocationMoveAlongPath]: ARLocationRoot GameObject not found.");
  126. Initialize();
  127. hasInitialized = true;
  128. }
  129. private void Initialize()
  130. {
  131. state.PointCount = PathSettings.LocationPath.Locations.Length;
  132. state.Points = new Vector3[state.PointCount];
  133. state.Speed = PlaybackSettings.Speed;
  134. useLineRenderer = PathSettings.LineRenderer != null;
  135. transform.SetParent(arLocationRoot.transform);
  136. state.Playing = PlaybackSettings.AutoPlay;
  137. u += PlaybackSettings.Offset;
  138. groundHeight = GetComponent<GroundHeight>();
  139. if (PlacementSettings.AltitudeMode == AltitudeMode.GroundRelative)
  140. {
  141. if (!groundHeight)
  142. {
  143. groundHeight = gameObject.AddComponent<GroundHeight>();
  144. groundHeight.Settings.DisableUpdate = true;
  145. }
  146. }
  147. else
  148. {
  149. if (groundHeight)
  150. {
  151. Destroy(groundHeight);
  152. groundHeight = null;
  153. }
  154. }
  155. if (!hasInitialized)
  156. {
  157. locationProvider.OnProviderRestartEvent(ProviderRestarted);
  158. }
  159. if (locationProvider.IsEnabled)
  160. {
  161. LocationUpdated(locationProvider.CurrentLocation, locationProvider.LastLocation);
  162. }
  163. }
  164. private void ProviderRestarted()
  165. {
  166. state.UpdateCount = 0;
  167. }
  168. public void Restart()
  169. {
  170. state = new StateData();
  171. Initialize();
  172. }
  173. /// <summary>
  174. /// Starts playing or resumes the playback.
  175. /// </summary>
  176. public void Play()
  177. {
  178. state.Playing = true;
  179. }
  180. /// <summary>
  181. /// Moves the object to the spline point corresponding
  182. /// to the given parameter.
  183. /// </summary>
  184. /// <param name="t">Between 0 and 1</param>
  185. public void GoTo(float t)
  186. {
  187. u = Mathf.Clamp(t, 0, 1);
  188. }
  189. /// <summary>
  190. /// Pauses the movement along the path.
  191. /// </summary>
  192. public void Pause()
  193. {
  194. state.Playing = false;
  195. }
  196. /// <summary>
  197. /// Stops the movement along the path.
  198. /// </summary>
  199. public void Stop()
  200. {
  201. state.Playing = false;
  202. u = 0;
  203. }
  204. private void BuildSpline(Location location)
  205. {
  206. for (var i = 0; i < state.PointCount; i++)
  207. {
  208. var loc = PathSettings.LocationPath.Locations[i];
  209. state.Points[i] = Location.GetGameObjectPositionForLocation(arLocationRoot.transform,
  210. mainCameraTransform, location, loc, HeightRelativeToDevice || HeightGroundRelative);
  211. Logger.LogFromMethod("MoveAlongPath", "BuildSpline", $"({gameObject.name}): Points[{i}] = {state.Points[i]}, geo-location = {loc}", DebugMode);
  212. }
  213. state.Spline = Misc.BuildSpline(PathSettings.LocationPath.SplineType, state.Points, PathSettings.SplineSampleCount, PathSettings.LocationPath.Alpha);
  214. }
  215. private void LocationUpdated(LocationReading location, LocationReading _)
  216. {
  217. Logger.LogFromMethod("MoveAlongPath", "LocationUpdated", $"({gameObject.name}): New device location {location}", DebugMode);
  218. if (PlacementSettings.MaxNumberOfLocationUpdates > 0 && state.UpdateCount > PlacementSettings.MaxNumberOfLocationUpdates)
  219. {
  220. Logger.LogFromMethod("MoveAlongPath", "LocationUpdated", $"({gameObject.name}): Max number of updates reached! returning", DebugMode);
  221. return;
  222. }
  223. BuildSpline(location.ToLocation());
  224. state.Translation = new Vector3(0, 0, 0);
  225. state.UpdateCount++;
  226. }
  227. private void Update()
  228. {
  229. if (!state.Playing)
  230. {
  231. return;
  232. }
  233. // If there is no location provider, or spline, do nothing
  234. if (state.Spline == null || !locationProvider.IsEnabled)
  235. {
  236. return;
  237. }
  238. // Get spline point at current parameter
  239. var s = state.Spline.Length * u;
  240. var data = state.Spline.GetPointAndTangentAtArcLength(s);
  241. var tan = arLocationRoot.transform.InverseTransformVector(data.tangent);
  242. transform.position = data.point;
  243. var groundY = 0.0f;
  244. if (groundHeight)
  245. {
  246. var position = transform.position;
  247. groundY = groundHeight.CurrentGroundY;
  248. position = MathUtils.SetY(position, position.y + groundY);
  249. transform.position = position;
  250. }
  251. // Set orientation
  252. transform.localRotation = Quaternion.LookRotation(tan, PlaybackSettings.Up);
  253. // Check if we reached the end of the spline
  254. u = u + (state.Speed * Time.deltaTime) / state.Spline.Length;
  255. if (u >= 1 && !PlaybackSettings.Loop)
  256. {
  257. u = 0;
  258. state.Playing = false;
  259. }
  260. else
  261. {
  262. u = u % 1.0f;
  263. }
  264. // If there is a line renderer, render the path
  265. if (useLineRenderer)
  266. {
  267. PathSettings.LineRenderer.useWorldSpace = true;
  268. var t = arLocationRoot.transform;
  269. state.Spline.DrawCurveWithLineRenderer(PathSettings.LineRenderer,
  270. p => MathUtils.SetY(p, p.y + groundY)); //t.TransformVector(p - state.Translation));
  271. }
  272. }
  273. private void OnDestroy()
  274. {
  275. locationProvider.OnLocationUpdatedDelegate -= LocationUpdated;
  276. locationProvider.OnRestartDelegate -= ProviderRestarted;
  277. }
  278. }
  279. }