LocalizerBase.cs 9.0 KB

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