GSXRManager.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.Events;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Runtime.InteropServices;
  8. using AOT;
  9. using SC.XR.Unity;
  10. public class GSXRManager : MonoBehaviour
  11. {
  12. public static GSXRManager Instance;
  13. //{
  14. // get
  15. // {
  16. // if (instance == null) instance = FindObjectOfType<GSXRManager>();
  17. // if (instance == null) Debug.LogError("GSXRManager object component not found");
  18. // return instance;
  19. // }
  20. //}
  21. //private static GSXRManager instance;
  22. static public int EyeLayerMax = 8;
  23. static public int OverlayLayerMax = 8;
  24. static public int RenderLayersMax = 16;
  25. public static Action SlamInitializedCallBack;
  26. //public static Action SlamOnPauseCallback;
  27. //public static Action SlamOnResumeCallback;
  28. [SerializeField]
  29. private SpecificationType m_SpecificationType = SpecificationType.GSXR;
  30. public SpecificationType SpecificationType
  31. {
  32. get { return m_SpecificationType; }
  33. private set { m_SpecificationType = value; }
  34. }
  35. public enum slamEventType
  36. {
  37. kEventNone = 0,
  38. kEventSdkServiceStarting = 1,
  39. kEventSdkServiceStarted = 2,
  40. kEventSdkServiceStopped = 3,
  41. kEventControllerConnecting = 4,
  42. kEventControllerConnected = 5,
  43. kEventControllerDisconnected = 6,
  44. kEventThermal = 7,
  45. kEventVrModeStarted = 8,
  46. kEventVrModeStopping = 9,
  47. kEventVrModeStopped = 10,
  48. kEventSensorError = 11,
  49. kEventMagnometerUncalibrated = 12,
  50. kEventBoundarySystemCollision = 13,
  51. kEvent6dofRelocation = 14,
  52. kEvent6dofWarningFeatureCount = 15,
  53. kEvent6dofWarningLowLight = 16,
  54. kEvent6dofWarningBrightLight = 17,
  55. kEvent6dofWarningCameraCalibration = 18
  56. }
  57. public enum controllerBondState
  58. {
  59. No_Bond = 0,
  60. Left_Bond = 1,
  61. Right_Bond = 2,
  62. Left_UnBond = 3,
  63. Right_UnBond = 4,
  64. OverTime_Bond = 5,
  65. Unknown = 6
  66. }
  67. [Serializable]
  68. public class SlamSettings
  69. {
  70. public enum eAntiAliasing
  71. {
  72. k1 = 1,
  73. k2 = 2,
  74. k4 = 4,
  75. };
  76. public enum eDepth
  77. {
  78. k16 = 16,
  79. k24 = 24
  80. };
  81. public enum eChromaticAberrationCorrection
  82. {
  83. kDisable = 0,
  84. kEnable = 1
  85. };
  86. public enum eVSyncCount
  87. {
  88. k0 = 0,
  89. k1 = 1,
  90. k2 = 2,
  91. };
  92. public enum eMasterTextureLimit
  93. {
  94. k0 = 0, // full size
  95. k1 = 1, // half size
  96. k2 = 2, // quarter size
  97. k3 = 3, // ...
  98. k4 = 4 // ...
  99. };
  100. public enum ePerfLevel
  101. {
  102. Minimum = 1,
  103. Medium = 2,
  104. Maximum = 3
  105. };
  106. public enum eFrustumType
  107. {
  108. Camera = 0,
  109. Device = 1,
  110. }
  111. public enum eEyeBufferType
  112. {
  113. //Mono = 0,
  114. StereoSeperate = 1,
  115. //StereoSingle = 2,
  116. //Array = 3,
  117. }
  118. [Tooltip("If head tracking lost, fade the display")]
  119. public bool poseStatusFade = true;
  120. [Tooltip("Use eye tracking (if available)")]
  121. public bool trackEyes = true;
  122. [Tooltip("Use position tracking (if available)")]
  123. public bool trackPosition = true;
  124. [Tooltip("Track position conversion from meters")]
  125. public float trackPositionScale = 1;
  126. [Tooltip("Height of the eyes from base of head")]
  127. public float headHeight = 0.0750f;
  128. [Tooltip("Depth of the eyes from center of head")]
  129. public float headDepth = 0.0805f;
  130. [Tooltip("Distance between the eyes")]
  131. public float interPupilDistance = 0.064f;
  132. //[Tooltip("Distance of line-of-sight convergence (0 disabled)")]
  133. //public float stereoConvergence = 0;
  134. //[Tooltip("Pitch angle to the horizon in degrees")]
  135. //public float horizonElevation = 0;
  136. [Tooltip("Eye field of view render target reprojection margin (% of fov) [0..]")]
  137. public float eyeFovMargin = 0.0f;
  138. [Tooltip("Eye render target scale factor")]
  139. public float eyeResolutionScaleFactor = 1.0f;
  140. [Tooltip("Eye render target depth buffer")]
  141. public eDepth eyeDepth = eDepth.k24;
  142. [Tooltip("Eye render target MSAA value")]
  143. public eAntiAliasing eyeAntiAliasing = eAntiAliasing.k2;
  144. [Tooltip("Overlay render target scale factor")]
  145. public float overlayResolutionScaleFactor = 1.0f;
  146. [Tooltip("Overlay render target depth buffer")]
  147. public eDepth overlayDepth = eDepth.k16;
  148. [Tooltip("Overlay render target MSAA value")]
  149. public eAntiAliasing overlayAntiAliasing = eAntiAliasing.k1;
  150. [Tooltip("Limit refresh rate")]
  151. public eVSyncCount vSyncCount = eVSyncCount.k1;
  152. [Tooltip("Chromatic Aberration Correction")]
  153. public eChromaticAberrationCorrection chromaticAberationCorrection = eChromaticAberrationCorrection.kEnable;
  154. [Tooltip("QualitySettings TextureQuality FullRes, HalfRes, etc.")]
  155. public eMasterTextureLimit masterTextureLimit = eMasterTextureLimit.k0;
  156. [Tooltip("CPU performance level")]
  157. public ePerfLevel cpuPerfLevel = ePerfLevel.Medium;
  158. [Tooltip("GPU performance level")]
  159. public ePerfLevel gpuPerfLevel = ePerfLevel.Medium;
  160. [Tooltip("Foveated render gain [1..], 0/feature disabled")]
  161. public Vector2 foveationGain = new Vector2(0.0f, 0.0f);
  162. [Tooltip("Foveated render hires area [0..]")]
  163. public float foveationArea = 0.0f;
  164. [Tooltip("Foveated render min pixel density [1/16..1]")]
  165. public float foveationMinimum = 0.25f;
  166. [Tooltip("Use perspective of unity camera or device frustum data")]
  167. public eFrustumType frustumType = eFrustumType.Camera;
  168. [Tooltip("Display buffer type (default stereo seperate)")]
  169. public eEyeBufferType displayType = eEyeBufferType.StereoSeperate;
  170. }
  171. [SerializeField]
  172. public SlamSettings settings;
  173. [Serializable]
  174. public class SlamStatus
  175. {
  176. [Tooltip("SnapdragonVR SDK Initialized")]
  177. public bool initialized = false;
  178. [Tooltip("SnapdragonVR SDK Running")]
  179. public bool running = false;
  180. [Tooltip("SnapdragonVR SDK Pose Status: 0/None, 1/Rotation, 2/Position, 3/RotationAndPosition")]
  181. public int pose = 0;
  182. }
  183. [SerializeField]
  184. public SlamStatus status;
  185. public enum eFadeState { FadeIn, FadeOut }
  186. [NonSerialized]
  187. public eFadeState fadeState = eFadeState.FadeIn;
  188. [NonSerialized]
  189. public float fadeDuration = 0.5f;
  190. [Header("Camera Rig")]
  191. public Transform head;
  192. public Transform gaze;
  193. public Camera monoCamera;
  194. public Camera leftCamera;
  195. public Camera rightCamera;
  196. public Camera leftOverlay;
  197. public Camera rightOverlay;
  198. public Camera monoOverlay;
  199. public GSXROverlay fadeOverlay;
  200. public GSXROverlay reticleOverlay;
  201. private bool IsUseOpticsCalibration = true;
  202. private bool IsUseCommonEvent = false;
  203. public Vector2 FocalPoint { get; set; } // Foveated Rendering Focal Point
  204. public int FrameCount { get { return frameCount; } }
  205. private int frameCount = 0;
  206. private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame();
  207. public GSXRPlugin plugin = null;
  208. private float sensorWarmupDuration = 0.25f;
  209. private List<GSXREye> eyes = new List<GSXREye>(EyeLayerMax);
  210. private List<GSXROverlay> overlays = new List<GSXROverlay>(OverlayLayerMax);
  211. private bool disableInput = false;
  212. private Coroutine onResume = null;
  213. private Coroutine submitFrame = null;
  214. private Matrix4x4 headDeltaInitLocalToWorld = Matrix4x4.identity;
  215. public Material DepthM;
  216. public bool IsCreateDepthRT = false;
  217. private bool IsDontDestroyOnLoad = true;
  218. private bool isInitRecenter = false;
  219. /// <summary>
  220. /// Slam event listener.
  221. /// </summary>
  222. public interface SlamEventListener
  223. {
  224. /// <summary>
  225. /// Raises the slam event event.
  226. /// </summary>
  227. /// <param name="ev">Ev.</param>
  228. void OnSlamEvent(SlamEvent ev);
  229. };
  230. public enum slamThermalLevel
  231. {
  232. kSafe,
  233. kLevel1,
  234. kLevel2,
  235. kLevel3,
  236. kCritical,
  237. kNumThermalLevels
  238. };
  239. public enum slamThermalZone
  240. {
  241. kCpu,
  242. kGpu,
  243. kSkin,
  244. kNumThermalZones
  245. };
  246. public struct slamEventData_Thermal
  247. {
  248. public slamThermalZone zone; //!< Thermal zone
  249. public slamThermalLevel level; //!< Indication of the current zone thermal level
  250. };
  251. [StructLayout(LayoutKind.Explicit)]
  252. public struct slamEventData
  253. {
  254. [FieldOffset(0)]
  255. public slamEventData_Thermal thermal;
  256. //[FieldOffset(0)]
  257. //public slamEventData_New newData;
  258. }
  259. public struct SlamEvent
  260. {
  261. public slamEventType eventType; //!< Type of event
  262. public uint deviceId; //!< An identifier for the device that generated the event (0 == HMD)
  263. public float eventTimeStamp; //!< Time stamp for the event in seconds since the last BeginVr call
  264. public slamEventData eventData; //!< Event specific data payload
  265. };
  266. // david start
  267. public struct SCSingleLayerData
  268. {
  269. public UInt32 layerId;
  270. public UInt32 parentLayerId;
  271. public UInt32 layerTextureId;
  272. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
  273. public float[] modelMatrixData;
  274. public UInt32 editFlag;
  275. public int z;
  276. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 12)]
  277. public float[] vertexPosition;
  278. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 8)]
  279. public float[] vertexUV;
  280. public float alpha;
  281. public byte bOpaque;
  282. public UInt32 taskId;
  283. public UInt32 recentTaskId;
  284. };
  285. public struct SCAllLayers
  286. {
  287. public UInt32 layerNum;
  288. [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 16)]
  289. public float[] viewMatrixData;
  290. public IntPtr layerData;
  291. };
  292. // david end
  293. private List<SlamEventListener> eventListeners = new List<SlamEventListener>();
  294. public bool Initialized
  295. {
  296. get { return status.initialized; }
  297. }
  298. public bool IsRunning
  299. {
  300. get { return status.running; }
  301. }
  302. public bool DisableInput
  303. {
  304. get { return disableInput; }
  305. set { disableInput = value; }
  306. }
  307. void Awake()
  308. {
  309. if (Instance)
  310. {
  311. DestroyImmediate(gameObject);
  312. return;
  313. }
  314. Instance = this;
  315. if (!ValidateReferencedComponents())
  316. {
  317. enabled = false;
  318. return;
  319. }
  320. RegisterListeners();
  321. Input.backButtonLeavesApp = true;
  322. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  323. Application.targetFrameRate = -1;
  324. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsCreateDepthRT"))
  325. {
  326. IsCreateDepthRT = API_Module_SDKConfiguration.GetBool("Module_Slam", "IsCreateDepthRT", 0);
  327. DebugMy.Log("IsCreateDepthRT:" + IsCreateDepthRT, this, true);
  328. }
  329. }
  330. //void OnGUI() {
  331. //}
  332. bool ValidateReferencedComponents()
  333. {
  334. plugin = GSXRPlugin.Instance;
  335. if (plugin == null)
  336. {
  337. Debug.LogError("slam Plugin failed to load. Disabling...");
  338. return false;
  339. }
  340. if (head == null)
  341. {
  342. Debug.LogError("Required head gameobject not found! Disabling...");
  343. return false;
  344. }
  345. if (monoCamera == null && (leftCamera == null || rightCamera == null))
  346. {
  347. Debug.LogError("Required eye components are missing! Disabling...");
  348. return false;
  349. }
  350. return true;
  351. }
  352. #if UNITY_2018
  353. void OnEnable()
  354. {
  355. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
  356. {
  357. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering += OnPreRenderEvent;
  358. }
  359. }
  360. void OnDisable()
  361. {
  362. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
  363. {
  364. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering -= OnPreRenderEvent;
  365. }
  366. }
  367. private void OnPreRenderEvent(Camera camera)
  368. {
  369. camera.SendMessage("OnPreRenderEvent", SendMessageOptions.DontRequireReceiver);
  370. }
  371. #endif
  372. IEnumerator Start()
  373. {
  374. yield return StartCoroutine(Initialize());
  375. status.initialized = plugin.IsInitialized();
  376. SetOverlayFade(eFadeState.FadeIn);
  377. yield return StartCoroutine(plugin.BeginVr((int)settings.cpuPerfLevel, (int)settings.gpuPerfLevel));
  378. /// for some platform plugin.BeginVr return so fast,so need check plugin.IsRunning() and Wait
  379. int waitFrameCount = 200;
  380. while (!plugin.IsRunning() && waitFrameCount >= 0)
  381. {
  382. yield return null;
  383. waitFrameCount--;
  384. }
  385. ///
  386. if (!plugin.IsRunning())
  387. {
  388. Debug.LogError("Slam failed!");
  389. Application.Quit();
  390. yield return null; // Wait one frame
  391. }
  392. //float recenterTimeout = 8f;
  393. //while (!plugin.RecenterTracking() && recenterTimeout > 0f) {
  394. // yield return null; // Wait one frame
  395. // recenterTimeout -= Time.deltaTime;
  396. //}
  397. yield return new WaitForSecondsRealtime(sensorWarmupDuration);
  398. submitFrame = StartCoroutine(SubmitFrame());
  399. status.running = true;
  400. SlamInitializedCallBack?.Invoke(); //Slam initialization complete callback
  401. plugin.GSXR_Set_GlassDisconnectedCallBack(GlassDisconnetedCallBack); //Register glasses disconnection callback
  402. Debug.Log("Slam initialized!");
  403. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsUseCommonEvent"))
  404. {
  405. IsUseCommonEvent = API_Module_SDKConfiguration.GetBool("Module_Slam", "IsUseCommonEvent", 1);
  406. DebugMy.Log("IsUseCommonEvent:" + IsUseCommonEvent, this, true);
  407. }
  408. if (IsUseCommonEvent)
  409. {
  410. gameObject.AddComponent<Module_CommonEvent>();
  411. }
  412. // DebugMy.Log("SDK SpecificationType:" + API_GSXR_Slam.SlamManager.SpecificationType + ":" + plugin.GSXR_Get_Version(), this, true);
  413. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsUseOpticsCalibration"))
  414. {
  415. IsUseOpticsCalibration = API_Module_SDKConfiguration.GetBool("Module_Slam", "IsUseOpticsCalibration", 1);
  416. DebugMy.Log("IsUseOpticsCalibration:" + IsUseOpticsCalibration, this, true);
  417. }
  418. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "trackPositionScale"))
  419. {
  420. settings.trackPositionScale = API_Module_SDKConfiguration.GetFloat("Module_Slam", "trackPositionScale", 1);
  421. DebugMy.Log("settings.trackPositionScale:" + settings.trackPositionScale, this, true);
  422. }
  423. Vector3 localLeftShoulder = Vector3.zero;
  424. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "LeftShoulderX") && API_Module_SDKConfiguration.HasKey("Module_Slam", "LeftShoulderY") && API_Module_SDKConfiguration.HasKey("Module_Slam", "LeftShoulderZ"))
  425. {
  426. localLeftShoulder = new Vector3(API_Module_SDKConfiguration.GetFloat("Module_Slam", "LeftShoulderX", 0.0f), API_Module_SDKConfiguration.GetFloat("Module_Slam", "LeftShoulderY", 0.0f), API_Module_SDKConfiguration.GetFloat("Module_Slam", "LeftShoulderZ", 0.0f));
  427. }
  428. if (API_Module_SDKConfiguration.HasKey("Module_SDKSystem", "IsDontDestroyOnLoad"))
  429. {
  430. IsDontDestroyOnLoad = API_Module_SDKConfiguration.GetBool("Module_SDKSystem", "IsDontDestroyOnLoad", 1);
  431. }
  432. shoulder = new Shoulder(head, localLeftShoulder == Vector3.zero ? new Vector3(-0.15f, -0.08f, -0.1f) : localLeftShoulder);
  433. isInit = true;
  434. }
  435. [MonoPInvokeCallback(typeof(Action))]
  436. private static void GlassDisconnetedCallBack()
  437. {
  438. Debug.Log("GlassDisconnetedCallBack");
  439. Application.Quit();
  440. }
  441. IEnumerator Initialize()
  442. {
  443. // Plugin must be initialized OnStart in order to properly
  444. // get a valid surface
  445. // GameObject mainCameraGo = GameObject.FindWithTag("MainCamera");
  446. // if (mainCameraGo)
  447. // {
  448. // mainCameraGo.SetActive(false);
  449. //
  450. // Debug.Log("Camera with MainCamera tag found.");
  451. // if (!disableInput)
  452. // {
  453. // Debug.Log("Will use translation and orientation from the MainCamera.");
  454. // transform.position = mainCameraGo.transform.position;
  455. // transform.rotation = mainCameraGo.transform.rotation;
  456. // }
  457. //
  458. // Debug.Log("Disabling Camera with MainCamera tag");
  459. // }
  460. GL.Clear(false, true, Color.black);
  461. yield return StartCoroutine(plugin.Initialize());
  462. InitializeCameras();
  463. InitializeEyes();
  464. InitializeOverlays();
  465. int trackingMode = (int)GSXRPlugin.TrackingMode.kTrackingOrientation;
  466. if (API_Module_SDKConfiguration.HasKey("Module_Slam", "IsSlamUse3Dof"))
  467. {
  468. if (API_Module_SDKConfiguration.GetBool("Module_Slam", "IsSlamUse3Dof", 0))
  469. {
  470. DebugMy.Log("Slam Use3Dof", this, true);
  471. settings.trackPosition = false;
  472. }
  473. }
  474. if (settings.trackPosition)
  475. trackingMode |= (int)GSXRPlugin.TrackingMode.kTrackingPosition;
  476. if (settings.trackEyes)
  477. trackingMode |= (int)GSXRPlugin.TrackingMode.kTrackingEye;
  478. plugin.SetTrackingMode(trackingMode);
  479. plugin.SetVSyncCount((int)settings.vSyncCount);
  480. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  481. }
  482. Matrix4x4 invertZ = new Matrix4x4(
  483. new Vector4(1, 0, 0, 0),
  484. new Vector4(0, 1, 0, 0),
  485. new Vector4(0, 0, -1, 0),
  486. new Vector4(0, 0, 0, 1));
  487. private void InitializeCameras()
  488. {
  489. float stereoConvergence = plugin.deviceInfo.targetFrustumConvergence; //settings.stereoConvergence
  490. float horizonElevation = plugin.deviceInfo.targetFrustumPitch; //settings.horizonElevation
  491. float convergenceAngle = 0f;
  492. if (stereoConvergence > Mathf.Epsilon) convergenceAngle = Mathf.Rad2Deg * Mathf.Atan2(0.5f * settings.interPupilDistance, stereoConvergence);
  493. else if (stereoConvergence < -Mathf.Epsilon) convergenceAngle = -Mathf.Rad2Deg * Mathf.Atan2(0.5f * settings.interPupilDistance, -stereoConvergence);
  494. // left
  495. Vector3 eyePos;
  496. eyePos.x = -0.5f * settings.interPupilDistance;
  497. eyePos.y = (!settings.trackPosition ? settings.headHeight : 0);
  498. eyePos.z = (!settings.trackPosition ? settings.headDepth : 0);
  499. eyePos += head.transform.localPosition;
  500. Quaternion eyeRot;
  501. eyeRot = Quaternion.Euler(horizonElevation, convergenceAngle, 0);
  502. if (leftCamera != null)
  503. {
  504. leftCamera.transform.localPosition = eyePos;
  505. leftCamera.transform.localRotation = eyeRot;
  506. }
  507. if (leftOverlay != null)
  508. {
  509. leftOverlay.transform.localPosition = eyePos;
  510. leftOverlay.transform.localRotation = eyeRot;
  511. }
  512. // right
  513. eyePos.x *= -1;
  514. eyeRot = Quaternion.Euler(horizonElevation, -convergenceAngle, 0);
  515. if (rightCamera != null)
  516. {
  517. rightCamera.transform.localPosition = eyePos;
  518. rightCamera.transform.localRotation = eyeRot;
  519. }
  520. if (rightOverlay != null)
  521. {
  522. rightOverlay.transform.localPosition = eyePos;
  523. rightOverlay.transform.localRotation = eyeRot;
  524. }
  525. // mono
  526. eyePos.x = 0.0f;
  527. eyeRot = Quaternion.Euler(horizonElevation, 0, 0);
  528. if (monoCamera != null)
  529. {
  530. monoCamera.transform.localPosition = eyePos;
  531. monoCamera.transform.localRotation = eyeRot;
  532. }
  533. if (monoOverlay != null)
  534. {
  535. monoOverlay.transform.localPosition = eyePos;
  536. monoOverlay.transform.localRotation = eyeRot;
  537. }
  538. }
  539. private void AddEyes(Camera cam, GSXREye.eSide side)
  540. {
  541. bool enableCamera = false;
  542. var eyesFound = cam.gameObject.GetComponents<GSXREye>();
  543. for (int i = 0; i < eyesFound.Length; i++)
  544. {
  545. eyesFound[i].Side = side;
  546. if (eyesFound[i].imageType == GSXREye.eType.RenderTexture) enableCamera = true;
  547. }
  548. eyes.AddRange(eyesFound);
  549. if (eyesFound.Length == 0)
  550. {
  551. var eye = cam.gameObject.AddComponent<GSXREye>();
  552. eye.Side = side;
  553. eyes.Add(eye);
  554. enableCamera = true;
  555. }
  556. #if UNITY_5_4 || UNITY_5_5
  557. cam.hdr = false;
  558. #else // UNITY_5_6 plus
  559. cam.allowHDR = false;
  560. cam.allowMSAA = false;
  561. #endif
  562. //cam.enabled = enableCamera;
  563. }
  564. private void InitializeEyes()
  565. {
  566. eyes.Clear();
  567. if (monoCamera != null && monoCamera.gameObject.activeSelf)
  568. {
  569. AddEyes(monoCamera, GSXREye.eSide.Both);
  570. }
  571. if (leftCamera != null && leftCamera.gameObject.activeSelf)
  572. {
  573. AddEyes(leftCamera, GSXREye.eSide.Left);
  574. }
  575. if (rightCamera != null && rightCamera.gameObject.activeSelf)
  576. {
  577. AddEyes(rightCamera, GSXREye.eSide.Right);
  578. }
  579. for (int i = 0; i < GSXREye.Instances.Count; i++)
  580. {
  581. var eye = GSXREye.Instances[i];
  582. if (!eyes.Contains(eye))
  583. {
  584. eyes.Add(eye); // Add eyes found outside of slam camera hierarchy
  585. }
  586. }
  587. GSXRPlugin.DeviceInfo info = plugin.deviceInfo;
  588. foreach (GSXREye eye in eyes)
  589. {
  590. if (eye == null) continue;
  591. eye.FovMargin = settings.eyeFovMargin;
  592. eye.Format = RenderTextureFormat.Default;
  593. eye.Resolution = new Vector2(info.targetEyeWidthPixels, info.targetEyeHeightPixels);
  594. eye.ResolutionScaleFactor = settings.eyeResolutionScaleFactor;
  595. eye.Depth = (int)settings.eyeDepth;
  596. eye.AntiAliasing = (int)settings.eyeAntiAliasing; // hdr not supported with antialiasing
  597. eye.FrustumType = (int)settings.frustumType;
  598. eye.OnPreRenderListener = OnPreRenderListener;
  599. eye.OnPostRenderListener = OnPostRenderListener;
  600. eye.Initialize();
  601. }
  602. }
  603. private void AddOverlays(Camera cam, GSXROverlay.eSide side)
  604. {
  605. bool enableCamera = false;
  606. var overlaysFound = cam.gameObject.GetComponents<GSXROverlay>();
  607. for (int i = 0; i < overlaysFound.Length; i++)
  608. {
  609. overlaysFound[i].Side = side;
  610. if (overlaysFound[i].imageType == GSXROverlay.eType.RenderTexture) enableCamera = true;
  611. }
  612. overlays.AddRange(overlaysFound);
  613. if (overlaysFound.Length == 0)
  614. {
  615. var overlay = cam.gameObject.AddComponent<GSXROverlay>();
  616. overlay.Side = side;
  617. overlays.Add(overlay);
  618. enableCamera = true;
  619. }
  620. #if UNITY_5_4 || UNITY_5_5
  621. cam.hdr = false;
  622. #else // UNITY_5_6 plus
  623. cam.allowHDR = false;
  624. cam.allowMSAA = false;
  625. #endif
  626. cam.enabled = enableCamera;
  627. }
  628. private void InitializeOverlays()
  629. {
  630. overlays.Clear();
  631. if (leftOverlay != null && leftOverlay.gameObject.activeSelf)
  632. {
  633. AddOverlays(leftOverlay, GSXROverlay.eSide.Left);
  634. }
  635. if (rightOverlay != null && rightOverlay.gameObject.activeSelf)
  636. {
  637. AddOverlays(rightOverlay, GSXROverlay.eSide.Right);
  638. }
  639. if (monoOverlay != null && monoOverlay.gameObject.activeSelf)
  640. {
  641. AddOverlays(monoOverlay, GSXROverlay.eSide.Both);
  642. }
  643. for (int i = 0; i < GSXROverlay.Instances.Count; i++)
  644. {
  645. var overlay = GSXROverlay.Instances[i];
  646. if (!overlays.Contains(overlay))
  647. {
  648. overlays.Add(overlay); // Add overlays found outside of slam camera hierarchy
  649. }
  650. }
  651. GSXRPlugin.DeviceInfo info = plugin.deviceInfo;
  652. foreach (GSXROverlay overlay in overlays)
  653. {
  654. if (overlay == null) continue;
  655. overlay.Format = RenderTextureFormat.Default;
  656. overlay.Resolution = new Vector2(info.targetEyeWidthPixels, info.targetEyeHeightPixels);
  657. overlay.ResolutionScaleFactor = settings.overlayResolutionScaleFactor;
  658. overlay.Depth = (int)settings.overlayDepth;
  659. overlay.AntiAliasing = (int)settings.overlayAntiAliasing; // hdr not supported with antialiasing
  660. overlay.FrustumType = (int)settings.frustumType;
  661. overlay.OnPreRenderListener = OnPreRenderListener;
  662. overlay.OnPostRenderListener = OnPostRenderListener;
  663. overlay.Initialize();
  664. }
  665. }
  666. public void SetOverlayFade(eFadeState fadeValue)
  667. {
  668. fadeState = fadeValue;
  669. var startAlpha = fadeState == eFadeState.FadeIn ? 1f : 0f;
  670. UpdateOverlayFade(startAlpha);
  671. }
  672. public bool IsOverlayFading()
  673. {
  674. return !Mathf.Approximately((float)fadeState, fadeAlpha);
  675. }
  676. private float fadeAlpha = 0f;
  677. private void UpdateOverlayFade(float targetAlpha, float rate = 0)
  678. {
  679. if (fadeOverlay == null) return;
  680. fadeAlpha = rate > 0 ? Mathf.MoveTowards(fadeAlpha, targetAlpha, rate) : targetAlpha;
  681. var fadeTexture = fadeOverlay.imageTexture as Texture2D;
  682. if (fadeTexture != null)
  683. {
  684. var fadeColors = fadeTexture.GetPixels();
  685. for (int i = 0; i < fadeColors.Length; ++i)
  686. {
  687. fadeColors[i].a = fadeAlpha;
  688. }
  689. fadeTexture.SetPixels(fadeColors);
  690. fadeTexture.Apply(false);
  691. }
  692. var isActive = fadeAlpha > 0.0f;
  693. if (fadeOverlay.enabled != isActive)
  694. {
  695. fadeOverlay.enabled = isActive;
  696. }
  697. }
  698. IEnumerator SubmitFrame()
  699. {
  700. Vector3 frustumSize = Vector3.zero;
  701. frustumSize.x = 0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left);
  702. frustumSize.y = 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom);
  703. frustumSize.z = plugin.deviceInfo.targetFrustumLeft.near;
  704. //Debug.LogFormat("SubmitFrame: Frustum Size ({0:F2}, {1:F2}, {2:F2})", frustumSize.x, frustumSize.y, frustumSize.z);
  705. while (true)
  706. {
  707. yield return waitForEndOfFrame;//固定帧测试
  708. if ((plugin.GetTrackingMode() & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0) // Request eye pose
  709. {
  710. status.pose |= plugin.GSXR_Get_EyePose(ref eyePose);
  711. }
  712. var eyePoint = Vector3.zero;
  713. if ((status.pose & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0) // Valid eye pose
  714. {
  715. //Debug.LogFormat("Left Eye Position: {0}, Direction: {1}", eyePose.leftPosition.ToString(), eyePose.leftDirection.ToString());
  716. //Debug.LogFormat("Right Eye Position: {0}, Direction: {1}", eyePose.rightPosition.ToString(), eyePose.rightDirection.ToString());
  717. //Debug.LogFormat("Combined Eye Position: {0}, Direction: {1}", eyePose.combinedPosition.ToString(), eyePose.combinedDirection.ToString());
  718. var combinedDirection = Vector3.zero;
  719. if ((eyePose.leftStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.leftDirection;
  720. if ((eyePose.rightStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.rightDirection;
  721. //if ((eyePose.combinedStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.combinedDirection;
  722. if (combinedDirection.sqrMagnitude > 0f)
  723. {
  724. combinedDirection.Normalize();
  725. //Debug.LogFormat("Eye Direction: ({0:F2}, {1:F2}, {2:F2})", combinedDirection.x, combinedDirection.y, combinedDirection.z);
  726. float denominator = Vector3.Dot(combinedDirection, Vector3.forward);
  727. if (denominator > float.Epsilon)
  728. {
  729. // eye direction intersection with frustum near plane (left)
  730. eyePoint = combinedDirection * frustumSize.z / denominator;
  731. eyePoint.x /= frustumSize.x; // [-1..1]
  732. eyePoint.y /= frustumSize.y; // [-1..1]
  733. //Debug.LogFormat("Eye Point: ({0:F2}, {1:F2})", eyePoint.x, eyePoint.y);
  734. }
  735. }
  736. }
  737. var currentGain = GSXROverrideSettings.FoveateGain == Vector2.zero ?
  738. settings.foveationGain : GSXROverrideSettings.FoveateGain;
  739. var currentArea = GSXROverrideSettings.FoveateArea == 0f ?
  740. settings.foveationArea : GSXROverrideSettings.FoveateArea;
  741. var currentMinimum = GSXROverrideSettings.FoveateMinimum == 0f ?
  742. settings.foveationMinimum : GSXROverrideSettings.FoveateMinimum;
  743. for (int i = 0; i < eyes.Count; i++)
  744. {
  745. var eye = eyes[i];
  746. if (eye.TextureId > 0 && eye.ImageType == GSXREye.eType.RenderTexture)
  747. {
  748. plugin.SetFoveationParameters(eye.TextureId, eye.PreviousId, eyePoint.x, eyePoint.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  749. plugin.ApplyFoveation();
  750. }
  751. }
  752. var horizontalFieldOfView = 0f;
  753. if (settings.eyeFovMargin > 0f)
  754. {
  755. horizontalFieldOfView = (monoCamera.enabled ? monoCamera.fieldOfView / monoCamera.aspect : leftCamera.fieldOfView / leftCamera.aspect) * Mathf.Deg2Rad;
  756. }
  757. plugin.SubmitFrame(frameCount, horizontalFieldOfView, (int)settings.displayType);
  758. frameCount++;
  759. }
  760. }
  761. public bool RecenterTracking()
  762. {
  763. if (!Initialized)
  764. return false;
  765. return plugin.RecenterTracking();
  766. }
  767. void OnPreRenderListener(int sideMask, int textureId, int previousId)
  768. {
  769. if (!IsRunning)
  770. return;
  771. var currentGain = GSXROverrideSettings.FoveateGain == Vector2.zero ?
  772. settings.foveationGain : GSXROverrideSettings.FoveateGain;
  773. var currentArea = GSXROverrideSettings.FoveateArea == 0f ?
  774. settings.foveationArea : GSXROverrideSettings.FoveateArea;
  775. var currentMinimum = GSXROverrideSettings.FoveateMinimum == 0f ?
  776. settings.foveationMinimum : GSXROverrideSettings.FoveateMinimum;
  777. plugin.SetFoveationParameters(textureId, previousId, FocalPoint.x, FocalPoint.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  778. plugin.BeginEye(sideMask, frameDelta);
  779. }
  780. void OnPostRenderListener(int sideMask, int layerMask)
  781. {
  782. if (!IsRunning)
  783. return;
  784. plugin.EndEye(sideMask, layerMask);
  785. }
  786. public void SetPause(bool pause)
  787. {
  788. if (!Initialized || !isInit)
  789. return;
  790. if (pause)
  791. {
  792. OnPause();
  793. }
  794. else
  795. {
  796. onResume = StartCoroutine(OnResume());
  797. }
  798. }
  799. void OnPause()
  800. {
  801. //Debug.Log("GSXRManager.OnPause()");
  802. status.running = false;
  803. if (onResume != null)
  804. {
  805. StopCoroutine(onResume);
  806. onResume = null;
  807. }
  808. if (submitFrame != null) { StopCoroutine(submitFrame); submitFrame = null; }
  809. if (plugin.IsRunning()) plugin.EndVr();
  810. }
  811. IEnumerator OnResume()
  812. {
  813. //Debug.Log("GSXRManager.OnResume()");
  814. SetOverlayFade(eFadeState.FadeIn);
  815. yield return StartCoroutine(plugin.BeginVr((int)settings.cpuPerfLevel, (int)settings.gpuPerfLevel));
  816. float recenterTimeout = 1f;
  817. while (!plugin.RecenterTracking() && recenterTimeout > 0f)
  818. {
  819. yield return null; // Wait one frame
  820. recenterTimeout -= Time.deltaTime;
  821. }
  822. yield return new WaitForSecondsRealtime(sensorWarmupDuration);
  823. submitFrame = StartCoroutine(SubmitFrame());
  824. status.running = plugin.IsRunning();
  825. onResume = null;
  826. onApplicationPauseDele?.Invoke(false);
  827. }
  828. [NonSerialized]
  829. public GSXRPlugin.HeadPose headPose;
  830. [NonSerialized]
  831. public GSXRPlugin.EyePose eyePose;
  832. [NonSerialized]
  833. public Vector3 eyeDirection = Vector3.forward;
  834. [NonSerialized]
  835. public Vector2 eyeFocus = Vector2.zero;
  836. [NonSerialized]
  837. public float eyeSmoother = 0.2f;
  838. [NonSerialized]
  839. public float[] frameDelta = new float[9];
  840. public Vector3 modifyPosition = Vector3.zero;
  841. public Quaternion modifyOrientation = Quaternion.identity;
  842. bool outBload = false;
  843. float[] outTransformArray = new float[32];
  844. Matrix4x4 leftcalib = Matrix4x4.identity;
  845. Matrix4x4 rightCalib = Matrix4x4.identity;
  846. bool isInit;
  847. bool isRotNan = false;
  848. bool isPosNan = false;
  849. void LateUpdate()
  850. {
  851. if (!IsRunning)
  852. {
  853. return;
  854. }
  855. int trackingMode = plugin.GetTrackingMode();
  856. var prevOrientation = headPose.orientation;
  857. status.pose = plugin.GetHeadPose(ref headPose, frameCount);
  858. // if (((API_GSXR_Slam.SlamManager.status.pose & (int)GSXRPlugin.TrackingMode.kNotInit) != 0) || ((API_GSXR_Slam.SlamManager.status.pose & (int)GSXRPlugin.TrackingMode.kLost) != 0))
  859. // {
  860. // DebugMy.Log("Tracking state ===================================== NotInit or Lost !!!! " + API_GSXR_Slam.SlamManager.status.pose, this, true);
  861. // }
  862. if (float.IsNaN(headPose.position.x) || float.IsNaN(headPose.position.y) || float.IsNaN(headPose.position.z))
  863. {
  864. DebugMy.Log("Position is " + headPose.position + " Error!!!!!!!!!!!!!!!!!!!!!!!!!!!", this, true);
  865. if (!isPosNan)
  866. {
  867. isPosNan = true;
  868. headPose.position = Vector3.zero;
  869. API_Module_DetectorSystem_Notice.SetNotice("The device position is NAN", "Please Reboot recovery", NoticeType.Warning, 0.8f, AlignmentType.Center, FollowType.False);
  870. API_Module_DetectorSystem_Notice.Show(1.5f);
  871. }
  872. }
  873. else
  874. {
  875. if (isPosNan)
  876. {
  877. isPosNan = false;
  878. DebugMy.Log("Position is " + headPose.position + " Success", this, true);
  879. }
  880. }
  881. if (float.IsNaN(headPose.orientation.x) || float.IsNaN(headPose.orientation.y) || float.IsNaN(headPose.orientation.z) || float.IsNaN(headPose.orientation.w))
  882. {
  883. DebugMy.Log("rotation is " + headPose.orientation + " Error!!!!!!!!!!!!!!!!!!!!!!!!!!!", this, true);
  884. if (!isRotNan)
  885. {
  886. isRotNan = true;
  887. headPose.orientation = Quaternion.identity;
  888. API_Module_DetectorSystem_Notice.SetNotice("The device rotation is NAN", "Please Reboot recovery", NoticeType.Warning, 0.8f, AlignmentType.Center, FollowType.False);
  889. API_Module_DetectorSystem_Notice.Show(1.5f);
  890. }
  891. }
  892. else
  893. {
  894. if (isRotNan)
  895. {
  896. isRotNan = false;
  897. DebugMy.Log("rotation is " + headPose.orientation + "Success", this, true);
  898. }
  899. }
  900. if ((trackingMode & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0)
  901. {
  902. status.pose |= plugin.GSXR_Get_EyePose(ref eyePose, frameCount);
  903. }
  904. if (!disableInput)
  905. {
  906. if ((status.pose & (int)GSXRPlugin.TrackingMode.kTrackingOrientation) != 0)
  907. {
  908. head.transform.localRotation = headPose.orientation;
  909. // delta orientation screen space x, y offset for foveated rendering
  910. var deltaOrientation = Quaternion.Inverse(prevOrientation) * headPose.orientation;
  911. var lookDirection = deltaOrientation * Vector3.forward;
  912. //Debug.LogFormat("Look Direction: {0}", lookDirection.ToString());
  913. lookDirection *= plugin.deviceInfo.targetFrustumLeft.near / lookDirection.z;
  914. float xTotal = 0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left);
  915. float xAdjust = (xTotal != 0.0f) ? lookDirection.x / xTotal : 0.0f;
  916. float yTotal = 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom);
  917. float yAdjust = (yTotal != 0.0f) ? lookDirection.y / yTotal : 0.0f;
  918. //xAdjust *= 0.5f * plugin.deviceInfo.targetEyeWidthPixels;
  919. //yAdjust *= 0.5f * plugin.deviceInfo.targetEyeHeightPixels;
  920. // rotation around z [cos(z), sin(z), 0], [-sin(z), cos(z), 0], [0, 0, 1]
  921. Vector3 deltaEulers = deltaOrientation.eulerAngles;
  922. float cosZ = Mathf.Cos(deltaEulers.z * Mathf.Deg2Rad);
  923. float sinZ = Mathf.Sin(deltaEulers.z * Mathf.Deg2Rad);
  924. // Output rotation and translation
  925. frameDelta[0] = cosZ;
  926. frameDelta[1] = sinZ;
  927. frameDelta[2] = 0.0f;
  928. frameDelta[3] = -sinZ;
  929. frameDelta[4] = cosZ;
  930. frameDelta[5] = 0.0f;
  931. frameDelta[6] = xAdjust;
  932. frameDelta[7] = yAdjust;
  933. frameDelta[8] = 1.0f;
  934. }
  935. if (settings.trackPosition && (status.pose & (int)GSXRPlugin.TrackingMode.kTrackingPosition) != 0)
  936. {
  937. if (isInitRecenter == false && headPose.position != Vector3.zero)
  938. {
  939. plugin.RecenterTracking();
  940. isInitRecenter = true;
  941. Debug.Log("isInitRecenter == true");
  942. }
  943. head.transform.localPosition = headPose.position * settings.trackPositionScale;
  944. }
  945. if ((status.pose & (int)GSXRPlugin.TrackingMode.kTrackingEye) != 0)
  946. {
  947. //Debug.LogFormat("Left Eye Position: {0}, Direction: {1}", eyePose.leftPosition.ToString(), eyePose.leftDirection.ToString());
  948. //Debug.LogFormat("Right Eye Position: {0}, Direction: {1}", eyePose.rightPosition.ToString(), eyePose.rightDirection.ToString());
  949. //Debug.LogFormat("Combined Eye Position: {0}, Direction: {1}", eyePose.combinedPosition.ToString(), eyePose.combinedDirection.ToString());
  950. var combinedDirection = Vector3.zero;
  951. if ((eyePose.leftStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.leftDirection;
  952. if ((eyePose.rightStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.rightDirection;
  953. //if ((eyePose.combinedStatus & (int)GSXRPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.combinedDirection;
  954. if (combinedDirection.sqrMagnitude > 0f)
  955. {
  956. combinedDirection.Normalize();
  957. //Debug.LogFormat("Eye Direction: ({0:F2}, {1:F2}, {2:F2})", combinedDirection.x, combinedDirection.y, combinedDirection.z);
  958. eyeDirection = eyeSmoother > 0.001f ? Vector3.Lerp(eyeDirection, combinedDirection, eyeSmoother) : combinedDirection;
  959. //var combinedPosition = Vector3.zero;
  960. //if ((eyePose.leftStatus & (int)GSXRPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.leftPosition;
  961. //if ((eyePose.rightStatus & (int)GSXRPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.rightPosition;
  962. ////if ((eyePose.combinedStatus & (int)GSXRPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.combinedPosition;
  963. gaze.localPosition = monoCamera.transform.localPosition;
  964. gaze.localRotation = Quaternion.LookRotation(eyeDirection, Vector3.up);
  965. float denominator = Vector3.Dot(eyeDirection, Vector3.forward);
  966. if (denominator > float.Epsilon)
  967. {
  968. // eye direction intersection with frustum near plane (left)
  969. var eyePoint = eyeDirection * plugin.deviceInfo.targetFrustumLeft.near / denominator;
  970. // size of the frustum near plane (left)
  971. var nearSize = new Vector2(0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left),
  972. 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom));
  973. eyeFocus.Set(eyePoint.x / nearSize.x, eyePoint.y / nearSize.y); // Normalized [-1,1]
  974. //Debug.LogFormat("Eye Focus: {0}", eyeFocus.ToString());
  975. FocalPoint = eyeFocus; // Cache for foveated rendering
  976. }
  977. }
  978. }
  979. }
  980. //var isValid = true;
  981. //if (settings.poseStatusFade)
  982. //{
  983. // isValid = !settings.trackPosition
  984. // || ((trackingMode & (int)GSXRPlugin.TrackingMode.kTrackingPosition) == 0)
  985. // || (status.pose & (int)GSXRPlugin.TrackingMode.kTrackingPosition) != 0;
  986. //}
  987. //var targetAlpha = fadeState == eFadeState.FadeOut || !isValid ? 1f : 0f;
  988. var targetAlpha = fadeState == eFadeState.FadeOut ? 1f : 0f;
  989. UpdateOverlayFade(targetAlpha, Time.deltaTime / fadeDuration);
  990. if (plugin.GSXR_Is_SupportOpticsCalibration())
  991. {
  992. if (leftcalib == Matrix4x4.identity || rightCalib == Matrix4x4.identity)
  993. {
  994. plugin.GSXR_Get_TransformMatrix(ref outBload, outTransformArray);
  995. if (outBload)
  996. {
  997. leftcalib.SetColumn(0, new Vector4(outTransformArray[0], outTransformArray[1], outTransformArray[2], outTransformArray[3]));
  998. leftcalib.SetColumn(1, new Vector4(outTransformArray[4], outTransformArray[5], outTransformArray[6], outTransformArray[7]));
  999. leftcalib.SetColumn(2, new Vector4(outTransformArray[8], outTransformArray[9], outTransformArray[10], outTransformArray[11]));
  1000. leftcalib.SetColumn(3, new Vector4(outTransformArray[12], outTransformArray[13], outTransformArray[14], outTransformArray[15]));
  1001. rightCalib.SetColumn(0, new Vector4(outTransformArray[16], outTransformArray[17], outTransformArray[18], outTransformArray[19]));
  1002. rightCalib.SetColumn(1, new Vector4(outTransformArray[20], outTransformArray[21], outTransformArray[22], outTransformArray[23]));
  1003. rightCalib.SetColumn(2, new Vector4(outTransformArray[24], outTransformArray[25], outTransformArray[26], outTransformArray[27]));
  1004. rightCalib.SetColumn(3, new Vector4(outTransformArray[28], outTransformArray[29], outTransformArray[30], outTransformArray[31]));
  1005. Debug.Log($"leftcalib [{leftcalib.m00}, {leftcalib.m01}, {leftcalib.m02}, {leftcalib.m03};" +
  1006. $"{leftcalib.m10}, {leftcalib.m11}, {leftcalib.m12}, {leftcalib.m13};" +
  1007. $"{leftcalib.m20}, {leftcalib.m21}, {leftcalib.m22}, {leftcalib.m23};" +
  1008. $"{leftcalib.m30}, {leftcalib.m31}, {leftcalib.m32}, {leftcalib.m33}]");
  1009. Debug.Log($"rightCalib [{rightCalib.m00}, {rightCalib.m01}, {rightCalib.m02}, {rightCalib.m03};" +
  1010. $"{rightCalib.m10}, {rightCalib.m11}, {rightCalib.m12}, {rightCalib.m13};" +
  1011. $"{rightCalib.m20}, {rightCalib.m21}, {rightCalib.m22}, {rightCalib.m23};" +
  1012. $"{rightCalib.m30}, {rightCalib.m31}, {rightCalib.m32}, {rightCalib.m33}]");
  1013. }
  1014. }
  1015. //if (outBload) {
  1016. // Matrix4x4 xx = leftcalib * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  1017. // Matrix4x4 yy = rightCalib * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  1018. // Debug.Log("SlamManager: OpticsCalibration leftCamera.worldToCameraMatrix:" + xx);
  1019. // Debug.Log("SlamManager: OpticsCalibration rightCamera.worldToCameraMatrix:" + yy);
  1020. //}
  1021. if (head.position != head.localPosition || head.rotation != head.localRotation)
  1022. {
  1023. ///for If Head parent not at origin,must mul the delta Matirx for Camera ViewMatrix
  1024. //MD*Ml*P = Mw*P ==> MD == Mw * (M1 -1 ni)
  1025. headDeltaInitLocalToWorld = Matrix4x4.TRS(head.position, head.rotation, Vector3.one) * Matrix4x4.Inverse(Matrix4x4.TRS(head.localPosition, head.localRotation, Vector3.one));
  1026. }
  1027. leftCamera.worldToCameraMatrix = plugin.leftViewMatrix * invertZ;
  1028. leftCamera.worldToCameraMatrix = Matrix4x4.Inverse(headDeltaInitLocalToWorld * leftCamera.cameraToWorldMatrix/* not worldToCameraMatrix*/);
  1029. rightCamera.worldToCameraMatrix = plugin.rightViewMatrix * invertZ;
  1030. rightCamera.worldToCameraMatrix = Matrix4x4.Inverse(headDeltaInitLocalToWorld * rightCamera.cameraToWorldMatrix/* not worldToCameraMatrix*/);
  1031. //Debug.Log("SlamManager: leftCamera.worldToCameraMatrix:" + leftCamera.worldToCameraMatrix);
  1032. //Debug.Log("SlamManager: rightCamera.worldToCameraMatrix:" + rightCamera.worldToCameraMatrix);
  1033. }
  1034. }
  1035. public void Shutdown()
  1036. {
  1037. Debug.Log("GSXRManager.Shutdown()");
  1038. status.running = false;
  1039. if (submitFrame != null) { StopCoroutine(submitFrame); submitFrame = null; }
  1040. if (plugin.IsRunning()) plugin.EndVr();
  1041. if (IsDontDestroyOnLoad)
  1042. {
  1043. if (plugin.IsInitialized()) plugin.Shutdown();
  1044. }
  1045. status.initialized = false;
  1046. }
  1047. void OnDestroy()
  1048. {
  1049. if (Instance != this)
  1050. return;
  1051. UnregisterListeners();
  1052. // plugin.GSXR_Set_ControllerBondEventCallback(null); //UnRegister Controller binding callback
  1053. Shutdown();
  1054. }
  1055. public delegate void OnApplicationPauseDele(bool pause);
  1056. public static event OnApplicationPauseDele onApplicationPauseDele;
  1057. void OnApplicationPause(bool pause)
  1058. {
  1059. return;
  1060. // ScenceMain.isEnterApp = false;
  1061. Debug.LogFormat("GSXRManager.OnApplicationPause({0})", pause);
  1062. if (pause)
  1063. {
  1064. onApplicationPauseDele?.Invoke(true);
  1065. }
  1066. SetPause(pause);
  1067. }
  1068. void OnApplicationQuit()
  1069. {
  1070. Debug.Log("GSXRManager.OnApplicationQuit()");
  1071. if (!IsDontDestroyOnLoad)
  1072. {
  1073. Shutdown();
  1074. if (plugin.IsInitialized()) plugin.Shutdown();
  1075. }
  1076. }
  1077. static public Matrix4x4 Perspective(float left, float right, float bottom, float top, float near, float far)
  1078. {
  1079. float x = 2.0F * near / (right - left);
  1080. float y = 2.0F * near / (top - bottom);
  1081. float a = (right + left) / (right - left);
  1082. float b = (top + bottom) / (top - bottom);
  1083. float c = -(far + near) / (far - near);
  1084. float d = -(2.0F * far * near) / (far - near);
  1085. float e = -1.0F;
  1086. Matrix4x4 m = new Matrix4x4();
  1087. m[0, 0] = x;
  1088. m[0, 1] = 0;
  1089. m[0, 2] = a;
  1090. m[0, 3] = 0;
  1091. m[1, 0] = 0;
  1092. m[1, 1] = y;
  1093. m[1, 2] = b;
  1094. m[1, 3] = 0;
  1095. m[2, 0] = 0;
  1096. m[2, 1] = 0;
  1097. m[2, 2] = c;
  1098. m[2, 3] = d;
  1099. m[3, 0] = 0;
  1100. m[3, 1] = 0;
  1101. m[3, 2] = e;
  1102. m[3, 3] = 0;
  1103. return m;
  1104. }
  1105. void RegisterListeners()
  1106. {
  1107. GSXROverrideSettings.OnEyeAntiAliasingChangedEvent += OnEyeAntiAliasingChanged;
  1108. GSXROverrideSettings.OnEyeDepthChangedEvent += OnEyeDepthChanged;
  1109. GSXROverrideSettings.OnEyeResolutionScaleFactorChangedEvent += OnEyeResolutionScaleFactorChanged;
  1110. GSXROverrideSettings.OnOverlayAntiAliasingChangedEvent += OnOverlayAntiAliasingChanged;
  1111. GSXROverrideSettings.OnOverlayDepthChangedEvent += OnOverlayDepthChanged;
  1112. GSXROverrideSettings.OnOverlayResolutionScaleFactorChangedEvent += OnOverlayResolutionScaleFactorChanged;
  1113. GSXROverrideSettings.OnChromaticAberrationCorrectionChangedEvent += OnChromaticAberrationCorrectionChanged;
  1114. GSXROverrideSettings.OnVSyncCountChangedEvent += OnVSyncCountChanged;
  1115. GSXROverrideSettings.OnMasterTextureLimitChangedEvent += OnMasterTextureLimitChanged;
  1116. GSXROverrideSettings.OnPerfLevelChangedEvent += OnPerfLevelChanged;
  1117. GSXROverrideSettings.OnFoveateChangedEvent += OnFoveateChanged;
  1118. }
  1119. void UnregisterListeners()
  1120. {
  1121. GSXROverrideSettings.OnEyeAntiAliasingChangedEvent -= OnEyeAntiAliasingChanged;
  1122. GSXROverrideSettings.OnEyeDepthChangedEvent -= OnEyeDepthChanged;
  1123. GSXROverrideSettings.OnEyeResolutionScaleFactorChangedEvent -= OnEyeResolutionScaleFactorChanged;
  1124. GSXROverrideSettings.OnOverlayAntiAliasingChangedEvent -= OnOverlayAntiAliasingChanged;
  1125. GSXROverrideSettings.OnOverlayDepthChangedEvent -= OnOverlayDepthChanged;
  1126. GSXROverrideSettings.OnOverlayResolutionScaleFactorChangedEvent -= OnOverlayResolutionScaleFactorChanged;
  1127. GSXROverrideSettings.OnChromaticAberrationCorrectionChangedEvent -= OnChromaticAberrationCorrectionChanged;
  1128. GSXROverrideSettings.OnVSyncCountChangedEvent -= OnVSyncCountChanged;
  1129. GSXROverrideSettings.OnMasterTextureLimitChangedEvent -= OnMasterTextureLimitChanged;
  1130. GSXROverrideSettings.OnPerfLevelChangedEvent -= OnPerfLevelChanged;
  1131. GSXROverrideSettings.OnFoveateChangedEvent -= OnFoveateChanged;
  1132. }
  1133. void OnEyeAntiAliasingChanged(GSXROverrideSettings.eAntiAliasing antiAliasing)
  1134. {
  1135. foreach (GSXREye eye in eyes)
  1136. {
  1137. eye.AntiAliasing = antiAliasing == GSXROverrideSettings.eAntiAliasing.NoOverride ?
  1138. (int)settings.eyeAntiAliasing : (int)antiAliasing;
  1139. }
  1140. }
  1141. void OnEyeDepthChanged(GSXROverrideSettings.eDepth depth)
  1142. {
  1143. foreach (GSXREye eye in eyes)
  1144. {
  1145. eye.Depth = depth == GSXROverrideSettings.eDepth.NoOverride ?
  1146. (int)settings.eyeDepth : (int)depth;
  1147. }
  1148. }
  1149. void OnEyeResolutionScaleFactorChanged(float scaleFactor)
  1150. {
  1151. foreach (GSXREye eye in eyes)
  1152. {
  1153. eye.ResolutionScaleFactor = scaleFactor <= 0 ? settings.eyeResolutionScaleFactor : scaleFactor;
  1154. }
  1155. }
  1156. void OnOverlayAntiAliasingChanged(GSXROverrideSettings.eAntiAliasing antiAliasing)
  1157. {
  1158. foreach (GSXROverlay overlay in overlays)
  1159. {
  1160. overlay.AntiAliasing = antiAliasing == GSXROverrideSettings.eAntiAliasing.NoOverride ?
  1161. (int)settings.overlayAntiAliasing : (int)antiAliasing;
  1162. }
  1163. }
  1164. void OnOverlayDepthChanged(GSXROverrideSettings.eDepth depth)
  1165. {
  1166. foreach (GSXROverlay overlay in overlays)
  1167. {
  1168. overlay.Depth = depth == GSXROverrideSettings.eDepth.NoOverride ?
  1169. (int)settings.overlayDepth : (int)depth;
  1170. }
  1171. }
  1172. void OnOverlayResolutionScaleFactorChanged(float scaleFactor)
  1173. {
  1174. foreach (GSXROverlay overlay in overlays)
  1175. {
  1176. overlay.ResolutionScaleFactor = scaleFactor <= 0 ? settings.overlayResolutionScaleFactor : scaleFactor;
  1177. }
  1178. }
  1179. void OnChromaticAberrationCorrectionChanged(GSXROverrideSettings.eChromaticAberrationCorrection aberrationCorrection)
  1180. {
  1181. if (aberrationCorrection == GSXROverrideSettings.eChromaticAberrationCorrection.kDisable)
  1182. {
  1183. plugin.SetFrameOption(GSXRPlugin.FrameOption.kDisableChromaticCorrection);
  1184. }
  1185. else
  1186. {
  1187. plugin.UnsetFrameOption(GSXRPlugin.FrameOption.kDisableChromaticCorrection);
  1188. }
  1189. }
  1190. void OnVSyncCountChanged(GSXROverrideSettings.eVSyncCount vSyncCount)
  1191. {
  1192. if (vSyncCount == GSXROverrideSettings.eVSyncCount.NoOverride)
  1193. {
  1194. plugin.SetVSyncCount((int)settings.vSyncCount);
  1195. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  1196. }
  1197. else
  1198. {
  1199. plugin.SetVSyncCount((int)vSyncCount);
  1200. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  1201. }
  1202. }
  1203. void OnMasterTextureLimitChanged(GSXROverrideSettings.eMasterTextureLimit masterTextureLimit)
  1204. {
  1205. QualitySettings.masterTextureLimit = masterTextureLimit == GSXROverrideSettings.eMasterTextureLimit.NoOverride ?
  1206. (int)settings.masterTextureLimit : (int)masterTextureLimit;
  1207. }
  1208. void OnPerfLevelChanged(GSXROverrideSettings.ePerfLevel cpuPerfLevel, GSXROverrideSettings.ePerfLevel gpuPerfLevel)
  1209. {
  1210. int currentCpuPerfLevel = cpuPerfLevel == GSXROverrideSettings.ePerfLevel.NoOverride ?
  1211. (int)settings.cpuPerfLevel : (int)GSXROverrideSettings.CpuPerfLevel;
  1212. int currentGpuPerfLevel = gpuPerfLevel == GSXROverrideSettings.ePerfLevel.NoOverride ?
  1213. (int)settings.gpuPerfLevel : (int)GSXROverrideSettings.GpuPerfLevel;
  1214. plugin.SetPerformanceLevels(currentCpuPerfLevel, currentGpuPerfLevel);
  1215. }
  1216. void OnFoveateChanged(Vector2 gain, float area, float minPixelDensity)
  1217. {
  1218. var point = Vector2.zero;
  1219. var currentGain = gain == Vector2.zero ?
  1220. settings.foveationGain : GSXROverrideSettings.FoveateGain;
  1221. var currentArea = area == 0f ?
  1222. settings.foveationArea : GSXROverrideSettings.FoveateArea;
  1223. var currentMinimum = minPixelDensity == 0f ?
  1224. settings.foveationMinimum : GSXROverrideSettings.FoveateMinimum;
  1225. plugin.SetFoveationParameters(0, 0, point.x, point.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  1226. }
  1227. /// <summary>
  1228. /// Update this instance.
  1229. /// </summary>
  1230. //---------------------------------------------------------------------------------------------
  1231. void Update()
  1232. {
  1233. SlamEvent frameEvent = new SlamEvent();
  1234. while (plugin.PollEvent(ref frameEvent))
  1235. {
  1236. //Debug.LogFormat("SlamEvent: {0}", frameEvent.eventType.ToString());
  1237. for (int i = 0; i < eventListeners.Count; i++)
  1238. {
  1239. eventListeners[i].OnSlamEvent(frameEvent);
  1240. }
  1241. }
  1242. }
  1243. /// <summary>
  1244. /// Adds the event listener.
  1245. /// </summary>
  1246. /// <param name="listener">Listener.</param>
  1247. //---------------------------------------------------------------------------------------------
  1248. public void AddEventListener(SlamEventListener listener)
  1249. {
  1250. if (listener != null)
  1251. {
  1252. eventListeners.Insert(0, listener);
  1253. }
  1254. }
  1255. /// <summary>
  1256. /// Start Tracking
  1257. /// </summary>
  1258. /// <returns>Handle to the controller</returns>
  1259. /// <param name="desc">Desc.</param>
  1260. //---------------------------------------------------------------------------------------------
  1261. public int ControllerStartTracking(string desc)
  1262. {
  1263. return plugin.ControllerStartTracking(desc);
  1264. }
  1265. /// <summary>
  1266. /// Stop Tracking
  1267. /// </summary>
  1268. /// <param name="handle">Handle.</param>
  1269. //---------------------------------------------------------------------------------------------
  1270. public void ControllerStopTracking(int handle)
  1271. {
  1272. plugin.ControllerStopTracking(handle);
  1273. }
  1274. /// <summary>
  1275. /// Get current state
  1276. /// </summary>
  1277. /// <returns>Controller State.</returns>
  1278. /// <param name="handle">Handle.</param>
  1279. //---------------------------------------------------------------------------------------------
  1280. public GSXRControllerState ControllerGetState(int handle, int space = 0)
  1281. {
  1282. return plugin.ControllerGetState(handle, space);
  1283. }
  1284. /// <summary>
  1285. /// Send an event to the controller
  1286. /// </summary>
  1287. /// <param name="handle">Handle.</param>
  1288. /// <param name="what">What.</param>
  1289. /// <param name="arg1">Arg1.</param>
  1290. /// <param name="arg2">Arg2.</param>
  1291. //---------------------------------------------------------------------------------------------
  1292. public void ControllerSendMessage(int handle, GSXRController.slamControllerMessageType what, int arg1, int arg2)
  1293. {
  1294. plugin.ControllerSendMessage(handle, what, arg1, arg2);
  1295. }
  1296. /// <summary>
  1297. /// Controllers the query.
  1298. /// </summary>
  1299. /// <returns>The query.</returns>
  1300. /// <param name="handle">Handle.</param>
  1301. /// <param name="what">What.</param>
  1302. /// <param name="mem">Mem.</param>
  1303. /// <param name="size">Size.</param>
  1304. //---------------------------------------------------------------------------------------------
  1305. public object ControllerQuery(int handle, GSXRController.slamControllerQueryType what)
  1306. {
  1307. return plugin.ControllerQuery(handle, what);
  1308. }
  1309. Coroutine startSlameCor;
  1310. public void StartSlam()
  1311. {
  1312. if (startSlameCor == null)
  1313. {
  1314. Debug.Log("StartSlam Coroutine Start");
  1315. startSlameCor = StartCoroutine(startSlam());
  1316. }
  1317. else
  1318. {
  1319. Debug.Log("startSlame Coroutine Not Null");
  1320. }
  1321. }
  1322. IEnumerator startSlam()
  1323. {
  1324. yield return new WaitUntil(() => GSXRManager.Instance != null);
  1325. yield return new WaitUntil(() => !GSXRManager.Instance.IsRunning);
  1326. GSXRManager.Instance.SetPause(false);
  1327. yield return new WaitUntil(() => IsTrackingValid);
  1328. startSlameCor = null;
  1329. }
  1330. Coroutine stopSlameCor;
  1331. //when stopSlam you must be sure no StartCorutine run before!
  1332. public void StopSlam()
  1333. {
  1334. if (stopSlameCor == null && startSlameCor == null)
  1335. {
  1336. Debug.Log("stopSlame Coroutine Start");
  1337. stopSlameCor = StartCoroutine(stopSlam());
  1338. }
  1339. else if (stopSlameCor != null)
  1340. {
  1341. Debug.Log("stopSlame Coroutine Not Null");
  1342. }
  1343. else if (startSlameCor != null)
  1344. {
  1345. Debug.Log("stopSlame: startSlame Coroutine Not Null");
  1346. }
  1347. }
  1348. IEnumerator stopSlam()
  1349. {
  1350. yield return new WaitUntil(() => GSXRManager.Instance != null);
  1351. yield return new WaitUntil(() => GSXRManager.Instance.IsRunning);
  1352. GSXRManager.Instance.SetPause(true);
  1353. yield return new WaitUntil(() => !GSXRManager.Instance.IsRunning);
  1354. stopSlameCor = null;
  1355. }
  1356. Coroutine resetSlameCor;
  1357. public void ResetSlam()
  1358. {
  1359. if (resetSlameCor == null)
  1360. {
  1361. Debug.Log("resetSlameCor Coroutine Start");
  1362. resetSlameCor = StartCoroutine(resetSlam());
  1363. }
  1364. else
  1365. {
  1366. Debug.Log("resetSlameCor Coroutine Not Null");
  1367. }
  1368. }
  1369. IEnumerator resetSlam()
  1370. {
  1371. Debug.Log("ResetSlam Coroutine Step 0: CheckFlag...");
  1372. yield return new WaitUntil(() => GSXRManager.Instance != null);
  1373. yield return new WaitUntil(() => GSXRManager.Instance.IsRunning);
  1374. Debug.Log("ResetSlam Coroutine Step 1: StopSlam");
  1375. GSXRManager.Instance.SetPause(true);
  1376. yield return new WaitUntil(() => !GSXRManager.Instance.IsRunning);
  1377. Debug.Log("ResetSlam Coroutine Step 2: StartSlam");
  1378. GSXRManager.Instance.SetPause(false);
  1379. yield return new WaitUntil(() => IsTrackingValid);
  1380. Debug.Log("ResetSlam Coroutine Finish");
  1381. resetSlameCor = null;
  1382. }
  1383. public bool IsTrackingValid
  1384. {
  1385. get
  1386. {
  1387. if (GSXRManager.Instance && GSXRManager.Instance.IsRunning)
  1388. {
  1389. return !GSXRManager.Instance.settings.trackPosition
  1390. || ((GSXRManager.Instance.plugin.GetTrackingMode() & (int)GSXRPlugin.TrackingMode.kTrackingPosition) == 0)
  1391. || (GSXRManager.Instance.status.pose & (int)GSXRPlugin.TrackingMode.kTrackingPosition) != 0;
  1392. }
  1393. return false;
  1394. }
  1395. }
  1396. public Shoulder shoulder;
  1397. public class Shoulder
  1398. {
  1399. public Transform Left { get; private set; }
  1400. public Transform Right { get; private set; }
  1401. private Transform head;
  1402. private Vector3 leftOffset;
  1403. public Shoulder(Transform head, Vector3 leftOffset)
  1404. {
  1405. this.head = head;
  1406. this.leftOffset = leftOffset;
  1407. if (head)
  1408. {
  1409. Left = new GameObject("LeftShoulder").transform;
  1410. Left.SetParent(head, false);
  1411. Left.localPosition = leftOffset;
  1412. Right = new GameObject("RightShoulder").transform;
  1413. Right.SetParent(head, false);
  1414. Right.localPosition = new Vector3(-leftOffset.x, leftOffset.y, leftOffset.z);
  1415. }
  1416. }
  1417. }
  1418. public void GSXR_Set_OnFloorOrOnHead(int type)
  1419. {
  1420. if (type != 0 && type != 1)
  1421. {
  1422. DebugMy.Log("GSXR_Set_OnFloorOrOnHead: index Must 1 or 0", this, true);
  1423. return;
  1424. }
  1425. plugin.GSXR_Set_OnFloorOrOnHead(type);
  1426. }
  1427. Coroutine VibrateCoroutine0, VibrateCoroutine1;
  1428. public void GSXR_Set_ControllerVibrate(int index, bool isOn, VibrateOnType vibrateOnType, float time)
  1429. {
  1430. if (index != 0 && index != 1)
  1431. {
  1432. DebugMy.Log("GSXR_Set_ControllerVibrate: index Must 1 or 0", this, true);
  1433. return;
  1434. }
  1435. if (vibrateOnType == VibrateOnType.Null)
  1436. {
  1437. //DebugMy.Log("GSXR_Set_ControllerVibrate: vibrateOnType Null", this, true);
  1438. return;
  1439. }
  1440. //DebugMy.Log("GSXR_Set_ControllerVibrate:" + index + " " + isOn + " " + vibrateOnType + " " + time, this, true);
  1441. if (index == 0 && VibrateCoroutine0 != null)
  1442. {
  1443. StopCoroutine(VibrateCoroutine0);
  1444. VibrateCoroutine0 = null;
  1445. }
  1446. else if (index == 1 && VibrateCoroutine1 != null)
  1447. {
  1448. StopCoroutine(VibrateCoroutine1);
  1449. VibrateCoroutine1 = null;
  1450. }
  1451. if (isOn)
  1452. {
  1453. if (index == 0)
  1454. {
  1455. VibrateCoroutine0 = StartCoroutine(VibrateRun(index, vibrateOnType, time));
  1456. }
  1457. else if (index == 1)
  1458. {
  1459. VibrateCoroutine1 = StartCoroutine(VibrateRun(index, vibrateOnType, time));
  1460. }
  1461. }
  1462. else
  1463. {
  1464. plugin.GSXR_Set_ControllerVibrate(index, false);
  1465. }
  1466. }
  1467. public int GSXR_Set_ControllerVibrate(int index, bool isOn, float amplitude, float frequency, float time)
  1468. {
  1469. if (index != 0 && index != 1 && index != 2)
  1470. {
  1471. DebugMy.Log("GSXR_Set_ControllerVibrateStatus: index Must 2 or 1 or 0", this, true);
  1472. return -1;
  1473. }
  1474. int amplitude1 = Convert.ToInt32(Math.Ceiling(amplitude * 16));
  1475. int frequency1 = Convert.ToInt32(Math.Ceiling(frequency * 16));
  1476. int time1 = Convert.ToInt32(Math.Round(time * 10));
  1477. //Debug.Log("KMSet_ControllerVibrate: "+index+","+isOn+","+amplitude1+","+ frequency1+","+ time1);
  1478. return plugin.GSXR_Set_ControllerVibrate(index, isOn, amplitude1, frequency1, time1);
  1479. }
  1480. public bool GSXR_Get_ControllerVibrateStatus(int index)
  1481. {
  1482. if (index != 0 && index != 1)
  1483. {
  1484. DebugMy.Log("GSXR_Get_ControllerVibrateStatus: index Must 1 or 0", this, true);
  1485. return false;
  1486. }
  1487. return plugin.GSXR_Get_ControllerVibrateStatus(index);
  1488. }
  1489. public int GSXR_Get_ControllerVibrateState(int index)
  1490. {
  1491. if (index != 0 && index != 1 && index != 2)
  1492. {
  1493. DebugMy.Log("GSXR_Get_ControllerVibrateState: index Must 2 or 1 or 0", this, true);
  1494. return -1;
  1495. }
  1496. return ((plugin.GSXR_Get_ControllerVibrateState(index) >> 2) & 1);
  1497. }
  1498. public enum VibrateOnType
  1499. {
  1500. Shutdown,
  1501. OneShot,
  1502. Continuous,
  1503. OneShotContinuous,
  1504. Null,
  1505. }
  1506. IEnumerator VibrateRun(int index, VibrateOnType vibrateOnType, float time)
  1507. {
  1508. yield return null;
  1509. if (vibrateOnType == VibrateOnType.OneShot)
  1510. {
  1511. plugin.GSXR_Set_ControllerVibrate(index, true);
  1512. yield return new WaitForSeconds(time);
  1513. plugin.GSXR_Set_ControllerVibrate(index, false);
  1514. }
  1515. else if (vibrateOnType == VibrateOnType.Continuous)
  1516. {
  1517. plugin.GSXR_Set_ControllerVibrate(index, true);
  1518. while (true)
  1519. {
  1520. yield return null;
  1521. }
  1522. }
  1523. else if (vibrateOnType == VibrateOnType.OneShotContinuous)
  1524. {
  1525. while (true)
  1526. {
  1527. plugin.GSXR_Set_ControllerVibrate(index, true);
  1528. yield return new WaitForSeconds(time);
  1529. plugin.GSXR_Set_ControllerVibrate(index, false);
  1530. yield return new WaitForSeconds(time / 2);
  1531. }
  1532. }
  1533. else if (vibrateOnType == VibrateOnType.Shutdown)
  1534. {
  1535. plugin.GSXR_Set_ControllerVibrate(index, false);
  1536. }
  1537. if (index == 0)
  1538. {
  1539. VibrateCoroutine0 = null;
  1540. }
  1541. else if (index == 1)
  1542. {
  1543. VibrateCoroutine1 = null;
  1544. }
  1545. }
  1546. public int GSXR_Get_ControllerAccelerometer(float[] orientationArray, int index)
  1547. {
  1548. if (index != 0 && index != 1)
  1549. {
  1550. DebugMy.Log("GSXR_Get_ControllerAccelerometer: index Must 1 or 0", this, true);
  1551. return -4;
  1552. }
  1553. return plugin.GSXR_Get_ControllerAccelerometer(orientationArray, index);
  1554. }
  1555. public int GSXR_Get_ControllerGyroscope(float[] orientationArray, int index)
  1556. {
  1557. if (index != 0 && index != 1)
  1558. {
  1559. DebugMy.Log("GSXR_Get_ControllerGyroscope: index Must 1 or 0", this, true);
  1560. return -4;
  1561. }
  1562. return GSXR_Get_ControllerGyroscope(orientationArray, index);
  1563. }
  1564. public int GSXR_Get_ControllerAngleVelocity(float[] orientationArray, int index)
  1565. {
  1566. if (index != 0 && index != 1)
  1567. {
  1568. DebugMy.Log("GSXR_Get_ControllerAngleVelocity: index Must 1 or 0", this, true);
  1569. return -4;
  1570. }
  1571. return plugin.GSXR_Get_ControllerAngleVelocity(orientationArray, index);
  1572. }
  1573. public int GSXR_Get_ControllerLinearVelocity(float[] orientationArray, int index)
  1574. {
  1575. if (index != 0 && index != 1)
  1576. {
  1577. DebugMy.Log("GSXR_Get_ControllerLinearVelocity: index Must 1 or 0", this, true);
  1578. return -4;
  1579. }
  1580. return plugin.GSXR_Get_ControllerLinearVelocity(orientationArray, index);
  1581. }
  1582. public void GSXR_Bind_Controller(int index, int type)
  1583. {
  1584. if (index != 0 && index != 1)
  1585. {
  1586. DebugMy.Log("GSXR_Bind_Controller: index Must 1 or 0", this, true);
  1587. return;
  1588. }
  1589. plugin.GSXR_Bind_Controller(index, type);
  1590. }
  1591. public void GSXR_Unbind_Controller(int index, int type)
  1592. {
  1593. if (index != 0 && index != 1)
  1594. {
  1595. DebugMy.Log("GSXR_Unbind_Controller: index Must 1 or 0", this, true);
  1596. return;
  1597. }
  1598. Debug.Log("GSXR_Unbind_Controller===>normal execute");
  1599. plugin.GSXR_Unbind_Controller(index, type);
  1600. }
  1601. public int GSXR_Get_ControllerBondState()
  1602. {
  1603. return plugin.GSXR_Get_ControllerBondState();
  1604. }
  1605. public void GSXR_Set_ControllerBondEventCallback(bool isEnable)
  1606. {
  1607. if (isEnable)
  1608. {
  1609. plugin.GSXR_Set_ControllerBondEventCallback(ControllerBondStateCallBack);
  1610. }
  1611. else
  1612. {
  1613. plugin.GSXR_Set_ControllerBondEventCallback(null);
  1614. }
  1615. }
  1616. [MonoPInvokeCallback(typeof(Action<int>))]
  1617. private static void ControllerBondStateCallBack(int bondState)
  1618. {
  1619. if (OnBondStateEvent != null && OnBondStateEvent.GetInvocationList().Length != 0)
  1620. {
  1621. OnBondStateEvent(bondState);
  1622. }
  1623. }
  1624. private static Action<int> OnBondStateEvent;
  1625. public void GSXR_Add_ControllerBondEventCallback(Action<int> callback) //Register the Controller binding status callback
  1626. {
  1627. OnBondStateEvent += callback;
  1628. }
  1629. public void GSXR_Remove_ControllerBondEventCallback(Action<int> callback) //UnRegister the Controller binding status callback
  1630. {
  1631. OnBondStateEvent -= callback;
  1632. }
  1633. }