LocalizerBase.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /*===============================================================================
  2. Copyright (C) 2022 Immersal - Part of Hexagon. All Rights Reserved.
  3. This file is part of the Immersal SDK.
  4. The Immersal SDK cannot be copied, distributed, or made available to
  5. third-parties for commercial purposes without written permission of Immersal Ltd.
  6. Contact sdk@immersal.com for licensing requests.
  7. ===============================================================================*/
  8. using UnityEngine;
  9. using System;
  10. using System.Collections;
  11. using System.Collections.Generic;
  12. using Immersal.REST;
  13. namespace Immersal.AR
  14. {
  15. public class LocalizerStats
  16. {
  17. public int localizationAttemptCount = 0;
  18. public int localizationSuccessCount = 0;
  19. }
  20. public struct LocalizerPose
  21. {
  22. public bool valid;
  23. public double[] mapToEcef;
  24. public Matrix4x4 matrix;
  25. public Pose lastUpdatedPose;
  26. public double vLatitude;
  27. public double vLongitude;
  28. public double vAltitude;
  29. }
  30. public abstract class LocalizerBase : MonoBehaviour
  31. {
  32. [Tooltip("Start localizing at app startup")]
  33. [SerializeField]
  34. protected bool m_AutoStart = true;
  35. [Tooltip("Time between localization requests in seconds")]
  36. public float localizationInterval = 2.0f;
  37. [Tooltip("Filter localizer poses for smoother results")]
  38. [SerializeField]
  39. protected bool m_UseFiltering = true;
  40. [Tooltip("Reset localizer filtering when relocalized against a different map than the previous time")]
  41. [SerializeField]
  42. protected bool m_ResetOnMapChange = false;
  43. [Tooltip("Try to localize at maximum speed at app startup / resume")]
  44. [SerializeField]
  45. protected bool m_BurstMode = true;
  46. [Tooltip("Use the on-server GeoPose localizer")]
  47. [SerializeField]
  48. protected bool m_UseGeoPoseLocalizer = false;
  49. [Tooltip("Use the on-server localizer")]
  50. [SerializeField]
  51. protected bool m_UseServerLocalizer = false;
  52. [Tooltip("Optional server map IDs when the on-server localizer is used")]
  53. [SerializeField]
  54. protected SDKMapId[] m_MapIds = new SDKMapId[] { };
  55. public LocalizerStats stats { get; protected set; } = new LocalizerStats();
  56. public int lastLocalizedMapId { get; protected set; }
  57. public LocalizerPose lastLocalizedPose = default;
  58. public bool isTracking { get; protected set; }
  59. public bool isLocalizing { get; protected set; }
  60. public Action<LocalizerPose> OnPoseFound;
  61. public Action<int> OnMapChanged;
  62. public Action OnReset;
  63. protected ImmersalSDK m_Sdk = null;
  64. protected IntPtr m_PixelBuffer = IntPtr.Zero;
  65. protected float m_LastLocalizeTime = 0.0f;
  66. protected float m_BurstStartTime = 0.0f;
  67. protected bool m_BurstModeActive = false;
  68. protected bool m_LocalizeContinuously = false;
  69. protected Camera m_Cam = null;
  70. protected float m_WarpThresholdDistSq = 5.0f * 5.0f;
  71. protected float m_WarpThresholdCosAngle = Mathf.Cos(20.0f * Mathf.PI / 180.0f);
  72. public bool burstMode
  73. {
  74. get { return m_BurstMode; }
  75. set
  76. {
  77. SetBurstMode(value);
  78. }
  79. }
  80. public bool useFiltering
  81. {
  82. get { return m_UseFiltering; }
  83. set { m_UseFiltering = value; }
  84. }
  85. public bool resetOnMapChange
  86. {
  87. get { return m_ResetOnMapChange; }
  88. set { m_ResetOnMapChange = value; }
  89. }
  90. public bool autoStart
  91. {
  92. get { return m_AutoStart; }
  93. set
  94. {
  95. m_AutoStart = value;
  96. SetContinuousLocalization(value);
  97. }
  98. }
  99. public bool useServerLocalizer
  100. {
  101. get { return m_UseServerLocalizer; }
  102. set { m_UseServerLocalizer = value; }
  103. }
  104. public bool useGeoPoseLocalizer
  105. {
  106. get { return m_UseGeoPoseLocalizer; }
  107. set { m_UseGeoPoseLocalizer = value; }
  108. }
  109. public SDKMapId[] mapIds
  110. {
  111. get { return m_MapIds; }
  112. set { m_MapIds = value; }
  113. }
  114. public virtual void Start()
  115. {
  116. m_Sdk = ImmersalSDK.Instance;
  117. lastLocalizedMapId = -1;
  118. SetBurstMode(burstMode);
  119. SetContinuousLocalization(autoStart);
  120. }
  121. #region Virtual methods
  122. public virtual void OnEnable()
  123. {
  124. m_Cam = Camera.main;
  125. }
  126. public virtual void OnDisable()
  127. {
  128. isTracking = false;
  129. }
  130. public virtual void OnDestroy()
  131. {
  132. m_PixelBuffer = IntPtr.Zero;
  133. }
  134. public virtual void OnApplicationPause(bool pauseStatus)
  135. {
  136. Reset();
  137. if (!pauseStatus)
  138. SetBurstMode(burstMode);
  139. }
  140. public virtual void Localize()
  141. {
  142. Debug.Log(string.Format("Successful localizations: {0}/{1}", stats.localizationSuccessCount, stats.localizationAttemptCount));
  143. isLocalizing = false;
  144. }
  145. public virtual void LocalizeServer(SDKMapId[] mapIds)
  146. {
  147. Debug.Log(string.Format("Successful localizations: {0}/{1}", stats.localizationSuccessCount, stats.localizationAttemptCount));
  148. isLocalizing = false;
  149. }
  150. public virtual void LocalizeGeoPose(SDKMapId[] mapIds)
  151. {
  152. Debug.Log(string.Format("Successful localizations: {0}/{1}", stats.localizationSuccessCount, stats.localizationAttemptCount));
  153. isLocalizing = false;
  154. }
  155. public virtual void Reset()
  156. {
  157. lastLocalizedMapId = -1;
  158. stats.localizationAttemptCount = stats.localizationSuccessCount = 0;
  159. SetBurstMode(burstMode);
  160. foreach (KeyValuePair<Transform, SpaceContainer> item in ARSpace.transformToSpace)
  161. item.Value.filter.ResetFiltering();
  162. OnReset?.Invoke();
  163. }
  164. public virtual void StartLocalizing()
  165. {
  166. Reset();
  167. SetContinuousLocalization(autoStart);
  168. }
  169. public virtual void StopLocalizing()
  170. {
  171. SetContinuousLocalization(false);
  172. Reset();
  173. }
  174. public virtual void Pause()
  175. {
  176. SetContinuousLocalization(false);
  177. }
  178. public virtual void Resume()
  179. {
  180. SetContinuousLocalization(true);
  181. }
  182. protected virtual void Update()
  183. {
  184. if (!m_LocalizeContinuously)
  185. return;
  186. if (ARSpace.transformToSpace.Count == 0)
  187. {
  188. m_BurstStartTime = Time.unscaledTime;
  189. return;
  190. }
  191. if (useFiltering)
  192. {
  193. foreach (KeyValuePair<Transform, SpaceContainer> item in ARSpace.transformToSpace)
  194. {
  195. float distSq = (item.Value.filter.position - item.Value.targetPosition).sqrMagnitude;
  196. float cosAngle = Quaternion.Dot(item.Value.filter.rotation, item.Value.targetRotation);
  197. if (item.Value.filter.SampleCount() == 1 || distSq > m_WarpThresholdDistSq || cosAngle < m_WarpThresholdCosAngle)
  198. {
  199. item.Value.targetPosition = item.Value.filter.position;
  200. item.Value.targetRotation = item.Value.filter.rotation;
  201. }
  202. else
  203. {
  204. float smoothing = 0.025f;
  205. float steps = Time.deltaTime / (1.0f / 60.0f);
  206. if (steps < 1.0f)
  207. steps = 1.0f;
  208. else if (steps > 6.0f)
  209. steps = 6.0f;
  210. float alpha = 1.0f - Mathf.Pow(1.0f - smoothing, steps);
  211. item.Value.targetRotation = Quaternion.Slerp(item.Value.targetRotation, item.Value.filter.rotation, alpha);
  212. item.Value.targetPosition = Vector3.Lerp(item.Value.targetPosition, item.Value.filter.position, alpha);
  213. }
  214. ARSpace.UpdateSpace(item.Value, item.Value.targetPosition, item.Value.targetRotation);
  215. }
  216. }
  217. float curTime = Time.unscaledTime;
  218. if (m_BurstModeActive) // try to localize at max speed during app start/resume
  219. {
  220. if (!isLocalizing && isTracking)
  221. {
  222. float elapsedTime = curTime - m_BurstStartTime;
  223. isLocalizing = true;
  224. if (useGeoPoseLocalizer && mapIds.Length > 0)
  225. {
  226. LocalizeGeoPose(mapIds);
  227. }
  228. else if (useServerLocalizer && mapIds.Length > 0)
  229. {
  230. LocalizeServer(mapIds);
  231. }
  232. else
  233. {
  234. Localize();
  235. }
  236. if (stats.localizationSuccessCount == 10 || elapsedTime >= 15f)
  237. {
  238. m_BurstModeActive = false;
  239. }
  240. }
  241. }
  242. if (!isLocalizing && isTracking && (curTime - m_LastLocalizeTime) >= localizationInterval)
  243. {
  244. m_LastLocalizeTime = curTime;
  245. isLocalizing = true;
  246. if (useGeoPoseLocalizer && mapIds.Length > 0)
  247. {
  248. LocalizeGeoPose(mapIds);
  249. }
  250. else if (useServerLocalizer && mapIds.Length > 0)
  251. {
  252. LocalizeServer(mapIds);
  253. }
  254. else
  255. {
  256. Localize();
  257. }
  258. }
  259. }
  260. #endregion
  261. private void SetBurstMode(bool on)
  262. {
  263. m_BurstStartTime = Time.unscaledTime;
  264. m_BurstModeActive = on;
  265. }
  266. private void SetContinuousLocalization(bool on)
  267. {
  268. m_LocalizeContinuously = on;
  269. }
  270. public static void GetLocalizerPose(out LocalizerPose localizerPose, int mapId, Vector3 pos, Quaternion rot, Matrix4x4 m, double[] mapToEcef = null)
  271. {
  272. localizerPose = default;
  273. if (mapToEcef == null)
  274. {
  275. mapToEcef = ARSpace.mapIdToMap[mapId].MapToEcefGet();
  276. }
  277. double[] wgs84 = new double[3];
  278. int r = Immersal.Core.PosMapToWgs84(wgs84, ARHelper.SwitchHandedness(pos), mapToEcef);
  279. if (r == 0)
  280. {
  281. localizerPose.valid = true;
  282. localizerPose.mapToEcef = mapToEcef;
  283. localizerPose.matrix = m;
  284. localizerPose.lastUpdatedPose = new Pose(pos, rot);
  285. localizerPose.vLatitude = wgs84[0];
  286. localizerPose.vLongitude = wgs84[1];
  287. localizerPose.vAltitude = wgs84[2];
  288. }
  289. }
  290. }
  291. }