SvrManager.cs 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  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. public class SvrManager : MonoBehaviour
  10. {
  11. public static SvrManager Instance;
  12. //{
  13. // get
  14. // {
  15. // if (instance == null) instance = FindObjectOfType<SvrManager>();
  16. // if (instance == null) Debug.LogError("SvrManager object component not found");
  17. // return instance;
  18. // }
  19. //}
  20. //private static SvrManager instance;
  21. static public int EyeLayerMax = 8; // svrApi SVR_MAX_EYE_LAYERS
  22. static public int OverlayLayerMax = 8; // svrApi SVR_MAX_OVERLAY_LAYERS
  23. static public int RenderLayersMax = 16; // svrApi SVR_MAX_RENDER_LAYERS
  24. public Action SvrInitializedCallBack;
  25. public enum svrEventType
  26. {
  27. kEventNone = 0,
  28. kEventSdkServiceStarting = 1,
  29. kEventSdkServiceStarted = 2,
  30. kEventSdkServiceStopped = 3,
  31. kEventControllerConnecting = 4,
  32. kEventControllerConnected = 5,
  33. kEventControllerDisconnected = 6,
  34. kEventThermal = 7,
  35. kEventVrModeStarted = 8,
  36. kEventVrModeStopping = 9,
  37. kEventVrModeStopped = 10,
  38. kEventSensorError = 11,
  39. kEventMagnometerUncalibrated = 12,
  40. kEventBoundarySystemCollision = 13,
  41. kEvent6dofRelocation = 14,
  42. kEvent6dofWarningFeatureCount = 15,
  43. kEvent6dofWarningLowLight = 16,
  44. kEvent6dofWarningBrightLight = 17,
  45. kEvent6dofWarningCameraCalibration = 18
  46. };
  47. [Serializable]
  48. public class SvrSettings
  49. {
  50. public enum eAntiAliasing
  51. {
  52. k1 = 1,
  53. k2 = 2,
  54. k4 = 4,
  55. };
  56. public enum eDepth
  57. {
  58. k16 = 16,
  59. k24 = 24
  60. };
  61. public enum eChromaticAberrationCorrection
  62. {
  63. kDisable = 0,
  64. kEnable = 1
  65. };
  66. public enum eVSyncCount
  67. {
  68. k0 = 0,
  69. k1 = 1,
  70. k2 = 2,
  71. };
  72. public enum eMasterTextureLimit
  73. {
  74. k0 = 0, // full size
  75. k1 = 1, // half size
  76. k2 = 2, // quarter size
  77. k3 = 3, // ...
  78. k4 = 4 // ...
  79. };
  80. public enum ePerfLevel
  81. {
  82. Minimum = 1,
  83. Medium = 2,
  84. Maximum = 3
  85. };
  86. public enum eFrustumType
  87. {
  88. Camera = 0,
  89. Device = 1,
  90. }
  91. public enum eEyeBufferType
  92. {
  93. //Mono = 0,
  94. StereoSeperate = 1,
  95. //StereoSingle = 2,
  96. //Array = 3,
  97. }
  98. [Tooltip("If head tracking lost, fade the display")]
  99. public bool poseStatusFade = true;
  100. [Tooltip("Use eye tracking (if available)")]
  101. public bool trackEyes = true;
  102. [Tooltip("Use position tracking (if available)")]
  103. public bool trackPosition = true;
  104. [Tooltip("Track position conversion from meters")]
  105. public float trackPositionScale = 1;
  106. [Tooltip("Height of the eyes from base of head")]
  107. public float headHeight = 0.0750f;
  108. [Tooltip("Depth of the eyes from center of head")]
  109. public float headDepth = 0.0805f;
  110. [Tooltip("Distance between the eyes")]
  111. public float interPupilDistance = 0.064f;
  112. //[Tooltip("Distance of line-of-sight convergence (0 disabled)")]
  113. //public float stereoConvergence = 0;
  114. //[Tooltip("Pitch angle to the horizon in degrees")]
  115. //public float horizonElevation = 0;
  116. [Tooltip("Eye field of view render target reprojection margin (% of fov) [0..]")]
  117. public float eyeFovMargin = 0.0f;
  118. [Tooltip("Eye render target scale factor")]
  119. public float eyeResolutionScaleFactor = 1.0f;
  120. [Tooltip("Eye render target depth buffer")]
  121. public eDepth eyeDepth = eDepth.k24;
  122. [Tooltip("Eye render target MSAA value")]
  123. public eAntiAliasing eyeAntiAliasing = eAntiAliasing.k2;
  124. [Tooltip("Overlay render target scale factor")]
  125. public float overlayResolutionScaleFactor = 1.0f;
  126. [Tooltip("Overlay render target depth buffer")]
  127. public eDepth overlayDepth = eDepth.k16;
  128. [Tooltip("Overlay render target MSAA value")]
  129. public eAntiAliasing overlayAntiAliasing = eAntiAliasing.k1;
  130. [Tooltip("Limit refresh rate")]
  131. public eVSyncCount vSyncCount = eVSyncCount.k1;
  132. [Tooltip("Chromatic Aberration Correction")]
  133. public eChromaticAberrationCorrection chromaticAberationCorrection = eChromaticAberrationCorrection.kEnable;
  134. [Tooltip("QualitySettings TextureQuality FullRes, HalfRes, etc.")]
  135. public eMasterTextureLimit masterTextureLimit = eMasterTextureLimit.k0;
  136. [Tooltip("CPU performance level")]
  137. public ePerfLevel cpuPerfLevel = ePerfLevel.Medium;
  138. [Tooltip("GPU performance level")]
  139. public ePerfLevel gpuPerfLevel = ePerfLevel.Medium;
  140. [Tooltip("Foveated render gain [1..], 0/feature disabled")]
  141. public Vector2 foveationGain = new Vector2(0.0f, 0.0f);
  142. [Tooltip("Foveated render hires area [0..]")]
  143. public float foveationArea = 0.0f;
  144. [Tooltip("Foveated render min pixel density [1/16..1]")]
  145. public float foveationMinimum = 0.25f;
  146. [Tooltip("Use perspective of unity camera or device frustum data")]
  147. public eFrustumType frustumType = eFrustumType.Camera;
  148. [Tooltip("Display buffer type (default stereo seperate)")]
  149. public eEyeBufferType displayType = eEyeBufferType.StereoSeperate;
  150. [Tooltip("Should Use Optics Calibration")]
  151. public bool activeOpticsCalib = false;
  152. }
  153. [SerializeField]
  154. public SvrSettings settings;
  155. [Serializable]
  156. public class SvrStatus
  157. {
  158. [Tooltip("SnapdragonVR SDK Initialized")]
  159. public bool initialized = false;
  160. [Tooltip("SnapdragonVR SDK Running")]
  161. public bool running = false;
  162. [Tooltip("SnapdragonVR SDK Pose Status: 0/None, 1/Rotation, 2/Position, 3/RotationAndPosition")]
  163. public int pose = 0;
  164. public int poseModify = 0;
  165. }
  166. [SerializeField]
  167. public SvrStatus status;
  168. public enum eFadeState { FadeIn, FadeOut }
  169. [NonSerialized]
  170. public eFadeState fadeState = eFadeState.FadeIn;
  171. [NonSerialized]
  172. public float fadeDuration = 2f;
  173. [Header("Camera Rig")]
  174. public Transform head;
  175. public Transform gaze;
  176. public Camera monoCamera;
  177. public Camera leftCamera;
  178. public Camera rightCamera;
  179. public Camera leftOverlay;
  180. public Camera rightOverlay;
  181. public Camera monoOverlay;
  182. public SvrOverlay fadeOverlay;
  183. public SvrOverlay reticleOverlay;
  184. public Vector3 leftCameraOffsetPostion= new Vector3 (0,0,0);
  185. public Vector3 leftCameraOffsetAngles= new Vector3 (0,2.5f,0);
  186. public Vector3 rightCameraOffsetPostion= new Vector3 (0,0,0);
  187. public Vector3 rightCameraOffsetAngles= new Vector3 (0,-2.5f,0);
  188. public static bool init;
  189. public Vector2 FocalPoint { get; set; } // Foveated Rendering Focal Point
  190. public int FrameCount { get { return frameCount; } }
  191. private int frameCount = 0;
  192. private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame();
  193. public SvrPlugin plugin = null;
  194. private float sensorWarmupDuration = 0.25f;
  195. private List<SvrEye> eyes = new List<SvrEye>(EyeLayerMax);
  196. private List<SvrOverlay> overlays = new List<SvrOverlay>(OverlayLayerMax);
  197. private bool disableInput = false;
  198. private Coroutine onResume = null;
  199. private Coroutine submitFrame = null;
  200. /// <summary>
  201. /// Svr event listener.
  202. /// </summary>
  203. public interface SvrEventListener {
  204. /// <summary>
  205. /// Raises the svr event event.
  206. /// </summary>
  207. /// <param name="ev">Ev.</param>
  208. void OnSvrEvent (SvrEvent ev);
  209. };
  210. public enum svrThermalLevel
  211. {
  212. kSafe,
  213. kLevel1,
  214. kLevel2,
  215. kLevel3,
  216. kCritical,
  217. kNumThermalLevels
  218. };
  219. public enum svrThermalZone
  220. {
  221. kCpu,
  222. kGpu,
  223. kSkin,
  224. kNumThermalZones
  225. };
  226. public struct svrEventData_Thermal
  227. {
  228. public svrThermalZone zone; //!< Thermal zone
  229. public svrThermalLevel level; //!< Indication of the current zone thermal level
  230. };
  231. [StructLayout(LayoutKind.Explicit)]
  232. public struct svrEventData
  233. {
  234. [FieldOffset(0)]
  235. public svrEventData_Thermal thermal;
  236. //[FieldOffset(0)]
  237. //public svrEventData_New newData;
  238. }
  239. public struct SvrEvent
  240. {
  241. public svrEventType eventType; //!< Type of event
  242. public uint deviceId; //!< An identifier for the device that generated the event (0 == HMD)
  243. public float eventTimeStamp; //!< Time stamp for the event in seconds since the last svrBeginVr call
  244. public svrEventData eventData; //!< Event specific data payload
  245. };
  246. private List<SvrEventListener> eventListeners = new List<SvrEventListener>();
  247. public bool Initialized
  248. {
  249. get { return status.initialized; }
  250. }
  251. public bool IsRunning
  252. {
  253. get { return status.running; }
  254. }
  255. public bool DisableInput
  256. {
  257. get { return disableInput; }
  258. set { disableInput = value; }
  259. }
  260. void Awake()
  261. {
  262. if(Instance) {
  263. DestroyImmediate(gameObject);
  264. return;
  265. }
  266. Instance = this;
  267. if (!ValidateReferencedComponents ())
  268. {
  269. enabled = false;
  270. return;
  271. }
  272. RegisterListeners();
  273. Input.backButtonLeavesApp = true;
  274. Screen.sleepTimeout = SleepTimeout.NeverSleep;
  275. Application.targetFrameRate = -1;
  276. }
  277. void OnGUI() {
  278. }
  279. bool ValidateReferencedComponents()
  280. {
  281. plugin = SvrPlugin.Instance;
  282. if(plugin == null)
  283. {
  284. Debug.LogError("Svr Plugin failed to load. Disabling...");
  285. return false;
  286. }
  287. if(head == null)
  288. {
  289. Debug.LogError("Required head gameobject not found! Disabling...");
  290. return false;
  291. }
  292. if(monoCamera == null && (leftCamera == null || rightCamera == null))
  293. {
  294. Debug.LogError("Required eye components are missing! Disabling...");
  295. return false;
  296. }
  297. return true;
  298. }
  299. #if UNITY_2018
  300. void OnEnable()
  301. {
  302. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
  303. {
  304. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering += OnPreRenderEvent;
  305. }
  306. }
  307. void OnDisable()
  308. {
  309. if (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset)
  310. {
  311. UnityEngine.Experimental.Rendering.RenderPipeline.beginCameraRendering -= OnPreRenderEvent;
  312. }
  313. }
  314. private void OnPreRenderEvent(Camera camera)
  315. {
  316. camera.SendMessage("OnPreRenderEvent", SendMessageOptions.DontRequireReceiver);
  317. }
  318. #endif
  319. IEnumerator Start ()
  320. {
  321. yield return StartCoroutine(Initialize());
  322. status.initialized = plugin.IsInitialized();
  323. SetOverlayFade(eFadeState.FadeIn);
  324. yield return StartCoroutine(plugin.BeginVr((int)settings.cpuPerfLevel, (int)settings.gpuPerfLevel));
  325. if (!plugin.IsRunning())
  326. {
  327. Debug.LogError("Svr failed!");
  328. Application.Quit();
  329. yield return null; // Wait one frame
  330. }
  331. float recenterTimeout = 1f;
  332. while (!plugin.RecenterTracking() && recenterTimeout > 0f)
  333. {
  334. yield return null; // Wait one frame
  335. recenterTimeout -= Time.deltaTime;
  336. }
  337. yield return new WaitForSecondsRealtime(sensorWarmupDuration);
  338. submitFrame = StartCoroutine(SubmitFrame());
  339. status.running = true;
  340. SvrInitializedCallBack?.Invoke();
  341. plugin.SetGlassDisconnectedCallBack(GlassDisconnetedCallBack);
  342. Debug.Log("Svr initialized!");
  343. }
  344. [MonoPInvokeCallback(typeof(SvrPlugin.GlassDisconnectedCallBack))]
  345. private static void GlassDisconnetedCallBack() {
  346. Debug.Log("GlassDisconnetedCallBack");
  347. Application.Quit();
  348. }
  349. IEnumerator Initialize()
  350. {
  351. // Plugin must be initialized OnStart in order to properly
  352. // get a valid surface
  353. // GameObject mainCameraGo = GameObject.FindWithTag("MainCamera");
  354. // if (mainCameraGo)
  355. // {
  356. // mainCameraGo.SetActive(false);
  357. //
  358. // Debug.Log("Camera with MainCamera tag found.");
  359. // if (!disableInput)
  360. // {
  361. // Debug.Log("Will use translation and orientation from the MainCamera.");
  362. // transform.position = mainCameraGo.transform.position;
  363. // transform.rotation = mainCameraGo.transform.rotation;
  364. // }
  365. //
  366. // Debug.Log("Disabling Camera with MainCamera tag");
  367. // }
  368. GL.Clear(false, true, Color.black);
  369. yield return StartCoroutine(plugin.Initialize());
  370. InitializeCameras();
  371. InitializeEyes();
  372. InitializeOverlays();
  373. int trackingMode = (int)SvrPlugin.TrackingMode.kTrackingOrientation;
  374. if (settings.trackPosition)
  375. trackingMode |= (int)SvrPlugin.TrackingMode.kTrackingPosition;
  376. if (settings.trackEyes)
  377. trackingMode |= (int)SvrPlugin.TrackingMode.kTrackingEye;
  378. plugin.SetTrackingMode(trackingMode);
  379. plugin.SetVSyncCount((int)settings.vSyncCount);
  380. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  381. }
  382. Matrix4x4 invertZ = new Matrix4x4(
  383. new Vector4(1, 0, 0, 0),
  384. new Vector4(0, 1, 0, 0),
  385. new Vector4(0, 0, -1, 0),
  386. new Vector4(0, 0, 0, 1));
  387. private void InitializeCameras()
  388. {
  389. float stereoConvergence = plugin.deviceInfo.targetFrustumConvergence; //settings.stereoConvergence
  390. float horizonElevation = plugin.deviceInfo.targetFrustumPitch; //settings.horizonElevation
  391. float convergenceAngle = 0f;
  392. if (stereoConvergence > Mathf.Epsilon) convergenceAngle = Mathf.Rad2Deg * Mathf.Atan2(0.5f * settings.interPupilDistance, stereoConvergence);
  393. else if (stereoConvergence < -Mathf.Epsilon) convergenceAngle = -Mathf.Rad2Deg * Mathf.Atan2(0.5f * settings.interPupilDistance, -stereoConvergence);
  394. // left
  395. Vector3 eyePos;
  396. eyePos.x = -0.5f * settings.interPupilDistance;
  397. eyePos.y = (!settings.trackPosition ? settings.headHeight : 0);
  398. eyePos.z = (!settings.trackPosition ? settings.headDepth : 0);
  399. eyePos += head.transform.localPosition;
  400. Quaternion eyeRot;
  401. eyeRot = Quaternion.Euler(horizonElevation, convergenceAngle, 0);
  402. if (leftCamera != null)
  403. {
  404. leftCamera.transform.localPosition = eyePos+leftCameraOffsetPostion;
  405. leftCamera.transform.localRotation = eyeRot;
  406. leftCamera.transform.localEulerAngles = leftCamera.transform.localEulerAngles+leftCameraOffsetAngles;
  407. }
  408. if (leftOverlay != null)
  409. {
  410. leftOverlay.transform.localPosition = eyePos;
  411. leftOverlay.transform.localRotation = eyeRot;
  412. }
  413. // right
  414. eyePos.x *= -1;
  415. eyeRot = Quaternion.Euler(horizonElevation, -convergenceAngle, 0);
  416. if (rightCamera != null)
  417. {
  418. rightCamera.transform.localPosition = eyePos+rightCameraOffsetPostion;
  419. rightCamera.transform.localRotation = eyeRot;
  420. rightCamera.transform.localEulerAngles = rightCamera.transform.localEulerAngles+rightCameraOffsetAngles;
  421. }
  422. if (rightOverlay != null)
  423. {
  424. rightOverlay.transform.localPosition = eyePos;
  425. rightOverlay.transform.localRotation = eyeRot;
  426. }
  427. // mono
  428. eyePos.x = 0.0f;
  429. eyeRot = Quaternion.Euler(horizonElevation, 0, 0);
  430. if (monoCamera != null)
  431. {
  432. monoCamera.transform.localPosition = eyePos;
  433. monoCamera.transform.localRotation = eyeRot;
  434. }
  435. if (monoOverlay != null)
  436. {
  437. monoOverlay.transform.localPosition = eyePos;
  438. monoOverlay.transform.localRotation = eyeRot;
  439. }
  440. }
  441. private void AddEyes(Camera cam, SvrEye.eSide side)
  442. {
  443. bool enableCamera = false;
  444. var eyesFound = cam.gameObject.GetComponents<SvrEye>();
  445. for (int i = 0; i < eyesFound.Length; i++)
  446. {
  447. eyesFound[i].Side = side;
  448. if (eyesFound[i].imageType == SvrEye.eType.RenderTexture) enableCamera = true;
  449. }
  450. eyes.AddRange(eyesFound);
  451. if (eyesFound.Length == 0)
  452. {
  453. var eye = cam.gameObject.AddComponent<SvrEye>();
  454. eye.Side = side;
  455. eyes.Add(eye);
  456. enableCamera = true;
  457. }
  458. #if UNITY_5_4 || UNITY_5_5
  459. cam.hdr = false;
  460. #else // UNITY_5_6 plus
  461. cam.allowHDR = false;
  462. cam.allowMSAA = false;
  463. #endif
  464. cam.enabled = enableCamera;
  465. }
  466. private void InitializeEyes()
  467. {
  468. eyes.Clear();
  469. if (monoCamera != null && monoCamera.gameObject.activeSelf)
  470. {
  471. AddEyes(monoCamera, SvrEye.eSide.Both);
  472. }
  473. if (leftCamera != null && leftCamera.gameObject.activeSelf)
  474. {
  475. AddEyes(leftCamera, SvrEye.eSide.Left);
  476. }
  477. if (rightCamera != null && rightCamera.gameObject.activeSelf)
  478. {
  479. AddEyes(rightCamera, SvrEye.eSide.Right);
  480. }
  481. for (int i = 0; i < SvrEye.Instances.Count; i++)
  482. {
  483. var eye = SvrEye.Instances[i];
  484. if (!eyes.Contains(eye))
  485. {
  486. eyes.Add(eye); // Add eyes found outside of svr camera hierarchy
  487. }
  488. }
  489. SvrPlugin.DeviceInfo info = plugin.deviceInfo;
  490. foreach(SvrEye eye in eyes)
  491. {
  492. if (eye == null) continue;
  493. eye.FovMargin = settings.eyeFovMargin;
  494. eye.Format = RenderTextureFormat.Default;
  495. eye.Resolution = new Vector2(info.targetEyeWidthPixels, info.targetEyeHeightPixels);
  496. eye.ResolutionScaleFactor = settings.eyeResolutionScaleFactor;
  497. eye.Depth = (int)settings.eyeDepth;
  498. eye.AntiAliasing = (int)settings.eyeAntiAliasing; // hdr not supported with antialiasing
  499. eye.FrustumType = (int)settings.frustumType;
  500. eye.OnPreRenderListener = OnPreRenderListener;
  501. eye.OnPostRenderListener = OnPostRenderListener;
  502. eye.Initialize();
  503. }
  504. }
  505. private void AddOverlays(Camera cam, SvrOverlay.eSide side)
  506. {
  507. bool enableCamera = false;
  508. var overlaysFound = cam.gameObject.GetComponents<SvrOverlay>();
  509. for (int i = 0; i < overlaysFound.Length; i++)
  510. {
  511. overlaysFound[i].Side = side;
  512. if (overlaysFound[i].imageType == SvrOverlay.eType.RenderTexture) enableCamera = true;
  513. }
  514. overlays.AddRange(overlaysFound);
  515. if (overlaysFound.Length == 0)
  516. {
  517. var overlay = cam.gameObject.AddComponent<SvrOverlay>();
  518. overlay.Side = side;
  519. overlays.Add(overlay);
  520. enableCamera = true;
  521. }
  522. #if UNITY_5_4 || UNITY_5_5
  523. cam.hdr = false;
  524. #else // UNITY_5_6 plus
  525. cam.allowHDR = false;
  526. cam.allowMSAA = false;
  527. #endif
  528. cam.enabled = enableCamera;
  529. }
  530. private void InitializeOverlays()
  531. {
  532. overlays.Clear();
  533. if (leftOverlay != null && leftOverlay.gameObject.activeSelf)
  534. {
  535. AddOverlays(leftOverlay, SvrOverlay.eSide.Left);
  536. }
  537. if (rightOverlay != null && rightOverlay.gameObject.activeSelf)
  538. {
  539. AddOverlays(rightOverlay, SvrOverlay.eSide.Right);
  540. }
  541. if (monoOverlay != null && monoOverlay.gameObject.activeSelf)
  542. {
  543. AddOverlays(monoOverlay, SvrOverlay.eSide.Both);
  544. }
  545. for (int i = 0; i < SvrOverlay.Instances.Count; i++)
  546. {
  547. var overlay = SvrOverlay.Instances[i];
  548. if (!overlays.Contains(overlay))
  549. {
  550. overlays.Add(overlay); // Add overlays found outside of svr camera hierarchy
  551. }
  552. }
  553. SvrPlugin.DeviceInfo info = plugin.deviceInfo;
  554. foreach (SvrOverlay overlay in overlays)
  555. {
  556. if (overlay == null) continue;
  557. overlay.Format = RenderTextureFormat.Default;
  558. overlay.Resolution = new Vector2(info.targetEyeWidthPixels, info.targetEyeHeightPixels);
  559. overlay.ResolutionScaleFactor = settings.overlayResolutionScaleFactor;
  560. overlay.Depth = (int)settings.overlayDepth;
  561. overlay.AntiAliasing = (int)settings.overlayAntiAliasing; // hdr not supported with antialiasing
  562. overlay.FrustumType = (int)settings.frustumType;
  563. overlay.OnPreRenderListener = OnPreRenderListener;
  564. overlay.OnPostRenderListener = OnPostRenderListener;
  565. overlay.Initialize();
  566. }
  567. }
  568. public void SetOverlayFade(eFadeState fadeValue)
  569. {
  570. fadeState = fadeValue;
  571. var startAlpha = fadeState == eFadeState.FadeIn ? 1f : 0f;
  572. UpdateOverlayFade(startAlpha);
  573. }
  574. public bool IsOverlayFading()
  575. {
  576. return !Mathf.Approximately((float)fadeState, fadeAlpha);
  577. }
  578. private float fadeAlpha = 0f;
  579. private void UpdateOverlayFade(float targetAlpha, float rate = 0)
  580. {
  581. if (fadeOverlay == null) return;
  582. fadeAlpha = rate > 0 ? Mathf.MoveTowards(fadeAlpha, targetAlpha, rate) : targetAlpha;
  583. var fadeTexture = fadeOverlay.imageTexture as Texture2D;
  584. if (fadeTexture != null)
  585. {
  586. var fadeColors = fadeTexture.GetPixels();
  587. for (int i = 0; i < fadeColors.Length; ++i)
  588. {
  589. fadeColors[i].a = fadeAlpha;
  590. }
  591. fadeTexture.SetPixels(fadeColors);
  592. fadeTexture.Apply(false);
  593. }
  594. var isActive = fadeAlpha > 0.0f;
  595. if (fadeOverlay.enabled != isActive)
  596. {
  597. fadeOverlay.enabled = isActive;
  598. }
  599. }
  600. IEnumerator SubmitFrame ()
  601. {
  602. Vector3 frustumSize = Vector3.zero;
  603. frustumSize.x = 0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left);
  604. frustumSize.y = 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom);
  605. frustumSize.z = plugin.deviceInfo.targetFrustumLeft.near;
  606. //Debug.LogFormat("SubmitFrame: Frustum Size ({0:F2}, {1:F2}, {2:F2})", frustumSize.x, frustumSize.y, frustumSize.z);
  607. while (true)
  608. {
  609. yield return waitForEndOfFrame;
  610. if ((plugin.GetTrackingMode() & (int)SvrPlugin.TrackingMode.kTrackingEye) != 0) // Request eye pose
  611. {
  612. status.pose |= plugin.GetEyePose(ref eyePose);
  613. }
  614. var eyePoint = Vector3.zero;
  615. if ((status.pose & (int)SvrPlugin.TrackingMode.kTrackingEye) != 0) // Valid eye pose
  616. {
  617. //Debug.LogFormat("Left Eye Position: {0}, Direction: {1}", eyePose.leftPosition.ToString(), eyePose.leftDirection.ToString());
  618. //Debug.LogFormat("Right Eye Position: {0}, Direction: {1}", eyePose.rightPosition.ToString(), eyePose.rightDirection.ToString());
  619. //Debug.LogFormat("Combined Eye Position: {0}, Direction: {1}", eyePose.combinedPosition.ToString(), eyePose.combinedDirection.ToString());
  620. var combinedDirection = Vector3.zero;
  621. if ((eyePose.leftStatus & (int)SvrPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.leftDirection;
  622. if ((eyePose.rightStatus & (int)SvrPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.rightDirection;
  623. //if ((eyePose.combinedStatus & (int)SvrPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.combinedDirection;
  624. if (combinedDirection.sqrMagnitude > 0f)
  625. {
  626. combinedDirection.Normalize();
  627. //Debug.LogFormat("Eye Direction: ({0:F2}, {1:F2}, {2:F2})", combinedDirection.x, combinedDirection.y, combinedDirection.z);
  628. float denominator = Vector3.Dot(combinedDirection, Vector3.forward);
  629. if (denominator > float.Epsilon)
  630. {
  631. // eye direction intersection with frustum near plane (left)
  632. eyePoint = combinedDirection * frustumSize.z / denominator;
  633. eyePoint.x /= frustumSize.x; // [-1..1]
  634. eyePoint.y /= frustumSize.y; // [-1..1]
  635. //Debug.LogFormat("Eye Point: ({0:F2}, {1:F2})", eyePoint.x, eyePoint.y);
  636. }
  637. }
  638. }
  639. var currentGain = SvrOverrideSettings.FoveateGain == Vector2.zero ?
  640. settings.foveationGain : SvrOverrideSettings.FoveateGain;
  641. var currentArea = SvrOverrideSettings.FoveateArea == 0f ?
  642. settings.foveationArea : SvrOverrideSettings.FoveateArea;
  643. var currentMinimum = SvrOverrideSettings.FoveateMinimum == 0f ?
  644. settings.foveationMinimum : SvrOverrideSettings.FoveateMinimum;
  645. for (int i = 0; i < eyes.Count; i++)
  646. {
  647. var eye = eyes[i];
  648. if (eye.TextureId > 0 && eye.ImageType == SvrEye.eType.RenderTexture)
  649. {
  650. plugin.SetFoveationParameters(eye.TextureId, eye.PreviousId, eyePoint.x, eyePoint.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  651. plugin.ApplyFoveation();
  652. }
  653. }
  654. var horizontalFieldOfView = 0f;
  655. if (settings.eyeFovMargin > 0f)
  656. {
  657. horizontalFieldOfView = (monoCamera.enabled ? monoCamera.fieldOfView / monoCamera.aspect : leftCamera.fieldOfView / leftCamera.aspect) * Mathf.Deg2Rad;
  658. }
  659. plugin.SubmitFrame(frameCount, horizontalFieldOfView, (int)settings.displayType);
  660. frameCount++;
  661. }
  662. }
  663. public bool RecenterTracking()
  664. {
  665. if (!Initialized)
  666. return false;
  667. return plugin.RecenterTracking();
  668. }
  669. void OnPreRenderListener (int sideMask, int textureId, int previousId)
  670. {
  671. if (!IsRunning)
  672. return;
  673. var currentGain = SvrOverrideSettings.FoveateGain == Vector2.zero ?
  674. settings.foveationGain : SvrOverrideSettings.FoveateGain;
  675. var currentArea = SvrOverrideSettings.FoveateArea == 0f ?
  676. settings.foveationArea : SvrOverrideSettings.FoveateArea;
  677. var currentMinimum = SvrOverrideSettings.FoveateMinimum == 0f ?
  678. settings.foveationMinimum : SvrOverrideSettings.FoveateMinimum;
  679. plugin.SetFoveationParameters(textureId, previousId, FocalPoint.x, FocalPoint.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  680. plugin.BeginEye(sideMask, frameDelta);
  681. }
  682. void OnPostRenderListener (int sideMask, int layerMask)
  683. {
  684. if (!IsRunning)
  685. return;
  686. plugin.EndEye (sideMask, layerMask);
  687. }
  688. public void SetPause(bool pause)
  689. {
  690. if (!Initialized)
  691. return;
  692. if (pause)
  693. {
  694. OnPause();
  695. }
  696. else
  697. {
  698. onResume = StartCoroutine(OnResume());
  699. }
  700. }
  701. void OnPause()
  702. {
  703. //Debug.Log("SvrManager.OnPause()");
  704. status.running = false;
  705. if (onResume != null) {
  706. StopCoroutine(onResume);
  707. onResume = null;
  708. }
  709. if (submitFrame != null) { StopCoroutine(submitFrame); submitFrame = null; }
  710. if (plugin.IsRunning()) plugin.EndVr();
  711. }
  712. IEnumerator OnResume()
  713. {
  714. //Debug.Log("SvrManager.OnResume()");
  715. SetOverlayFade(eFadeState.FadeIn);
  716. yield return StartCoroutine(plugin.BeginVr((int)settings.cpuPerfLevel, (int)settings.gpuPerfLevel));
  717. float recenterTimeout = 1f;
  718. while (!plugin.RecenterTracking() && recenterTimeout > 0f)
  719. {
  720. yield return null; // Wait one frame
  721. recenterTimeout -= Time.deltaTime;
  722. }
  723. yield return new WaitForSecondsRealtime(sensorWarmupDuration);
  724. submitFrame = StartCoroutine (SubmitFrame ());
  725. status.running = plugin.IsRunning();
  726. onResume = null;
  727. }
  728. [NonSerialized]
  729. public SvrPlugin.HeadPose headPose;
  730. [NonSerialized]
  731. public SvrPlugin.EyePose eyePose;
  732. [NonSerialized]
  733. public Vector3 eyeDirection = Vector3.forward;
  734. [NonSerialized]
  735. public Vector2 eyeFocus = Vector2.zero;
  736. [NonSerialized]
  737. public float eyeSmoother = 0.2f;
  738. [NonSerialized]
  739. public float[] frameDelta = new float[9];
  740. public Vector3 modifyPosition = Vector3.zero;
  741. public Quaternion modifyOrientation = Quaternion.identity;
  742. bool outBload = false;
  743. float[] outTransformArray = new float[32];
  744. Matrix4x4 leftcalib, rightCalib;
  745. void LateUpdate()
  746. {
  747. if (!IsRunning)
  748. {
  749. return;
  750. }
  751. int trackingMode = plugin.GetTrackingMode();
  752. var prevOrientation = headPose.orientation;
  753. //status.poseModify = plugin.GetPredictedPoseModify(ref modifyOrientation, ref modifyPosition, frameCount);
  754. status.pose = plugin.GetHeadPose(ref headPose, frameCount);
  755. if ((trackingMode & (int)SvrPlugin.TrackingMode.kTrackingEye) != 0)
  756. {
  757. status.pose |= plugin.GetEyePose(ref eyePose, frameCount);
  758. }
  759. if (!disableInput)
  760. {
  761. if ((status.pose & (int)SvrPlugin.TrackingMode.kTrackingOrientation) != 0)
  762. {
  763. head.transform.localRotation = headPose.orientation;
  764. // delta orientation screen space x, y offset for foveated rendering
  765. var deltaOrientation = Quaternion.Inverse(prevOrientation) * headPose.orientation;
  766. var lookDirection = deltaOrientation * Vector3.forward;
  767. //Debug.LogFormat("Look Direction: {0}", lookDirection.ToString());
  768. lookDirection *= plugin.deviceInfo.targetFrustumLeft.near / lookDirection.z;
  769. float xTotal = 0.5f * (plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left);
  770. float xAdjust = (xTotal != 0.0f) ? lookDirection.x / xTotal : 0.0f;
  771. float yTotal = 0.5f * (plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom);
  772. float yAdjust = (yTotal != 0.0f) ? lookDirection.y / yTotal : 0.0f;
  773. //xAdjust *= 0.5f * plugin.deviceInfo.targetEyeWidthPixels;
  774. //yAdjust *= 0.5f * plugin.deviceInfo.targetEyeHeightPixels;
  775. // rotation around z [cos(z), sin(z), 0], [-sin(z), cos(z), 0], [0, 0, 1]
  776. Vector3 deltaEulers = deltaOrientation.eulerAngles;
  777. float cosZ = Mathf.Cos(deltaEulers.z * Mathf.Deg2Rad);
  778. float sinZ = Mathf.Sin(deltaEulers.z * Mathf.Deg2Rad);
  779. // Output rotation and translation
  780. frameDelta[0] = cosZ;
  781. frameDelta[1] = sinZ;
  782. frameDelta[2] = 0.0f;
  783. frameDelta[3] = -sinZ;
  784. frameDelta[4] = cosZ;
  785. frameDelta[5] = 0.0f;
  786. frameDelta[6] = xAdjust;
  787. frameDelta[7] = yAdjust;
  788. frameDelta[8] = 1.0f;
  789. }
  790. if (settings.trackPosition && (status.pose & (int)SvrPlugin.TrackingMode.kTrackingPosition) != 0)
  791. {
  792. head.transform.localPosition = headPose.position * settings.trackPositionScale;
  793. }
  794. if ((status.pose & (int)SvrPlugin.TrackingMode.kTrackingEye) != 0)
  795. {
  796. //Debug.LogFormat("Left Eye Position: {0}, Direction: {1}", eyePose.leftPosition.ToString(), eyePose.leftDirection.ToString());
  797. //Debug.LogFormat("Right Eye Position: {0}, Direction: {1}", eyePose.rightPosition.ToString(), eyePose.rightDirection.ToString());
  798. //Debug.LogFormat("Combined Eye Position: {0}, Direction: {1}", eyePose.combinedPosition.ToString(), eyePose.combinedDirection.ToString());
  799. var combinedDirection = Vector3.zero;
  800. if ((eyePose.leftStatus & (int)SvrPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.leftDirection;
  801. if ((eyePose.rightStatus & (int)SvrPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.rightDirection;
  802. //if ((eyePose.combinedStatus & (int)SvrPlugin.EyePoseStatus.kGazeVectorValid) != 0) combinedDirection += eyePose.combinedDirection;
  803. if (combinedDirection.sqrMagnitude > 0f)
  804. {
  805. combinedDirection.Normalize();
  806. //Debug.LogFormat("Eye Direction: ({0:F2}, {1:F2}, {2:F2})", combinedDirection.x, combinedDirection.y, combinedDirection.z);
  807. eyeDirection = eyeSmoother > 0.001f ? Vector3.Lerp(eyeDirection, combinedDirection, eyeSmoother) : combinedDirection;
  808. //var combinedPosition = Vector3.zero;
  809. //if ((eyePose.leftStatus & (int)SvrPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.leftPosition;
  810. //if ((eyePose.rightStatus & (int)SvrPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.rightPosition;
  811. ////if ((eyePose.combinedStatus & (int)SvrPlugin.EyePoseStatus.kGazePointValid) != 0) combinedPosition += eyePose.combinedPosition;
  812. gaze.localPosition = monoCamera.transform.localPosition;
  813. gaze.localRotation = Quaternion.LookRotation(eyeDirection, Vector3.up);
  814. float denominator = Vector3.Dot(eyeDirection, Vector3.forward);
  815. if (denominator > float.Epsilon)
  816. {
  817. // eye direction intersection with frustum near plane (left)
  818. var eyePoint = eyeDirection * plugin.deviceInfo.targetFrustumLeft.near / denominator;
  819. // size of the frustum near plane (left)
  820. var nearSize = new Vector2(0.5f*(plugin.deviceInfo.targetFrustumLeft.right - plugin.deviceInfo.targetFrustumLeft.left),
  821. 0.5f*(plugin.deviceInfo.targetFrustumLeft.top - plugin.deviceInfo.targetFrustumLeft.bottom));
  822. eyeFocus.Set(eyePoint.x / nearSize.x, eyePoint.y / nearSize.y); // Normalized [-1,1]
  823. //Debug.LogFormat("Eye Focus: {0}", eyeFocus.ToString());
  824. FocalPoint = eyeFocus; // Cache for foveated rendering
  825. }
  826. }
  827. }
  828. }
  829. var isValid = true;
  830. if (settings.poseStatusFade)
  831. {
  832. isValid = !settings.trackPosition
  833. || ((trackingMode & (int)SvrPlugin.TrackingMode.kTrackingPosition) == 0)
  834. || (status.pose & (int)SvrPlugin.TrackingMode.kTrackingPosition) != 0;
  835. }
  836. var targetAlpha = fadeState == eFadeState.FadeOut || !isValid ? 1f : 0f;
  837. UpdateOverlayFade(targetAlpha, Time.deltaTime / fadeDuration);
  838. if (settings.activeOpticsCalib) {
  839. plugin.SVRGetTransformMatrix(ref outBload, outTransformArray);
  840. }
  841. if (outBload) {
  842. leftcalib.SetColumn(0, new Vector4(outTransformArray[0], outTransformArray[1], outTransformArray[2], outTransformArray[3]));
  843. leftcalib.SetColumn(1, new Vector4(outTransformArray[4], outTransformArray[5], outTransformArray[6], outTransformArray[7]));
  844. leftcalib.SetColumn(2, new Vector4(outTransformArray[8], outTransformArray[9], outTransformArray[10], outTransformArray[11]));
  845. leftcalib.SetColumn(3, new Vector4(outTransformArray[12], outTransformArray[13], outTransformArray[14], outTransformArray[15]));
  846. rightCalib.SetColumn(0, new Vector4(outTransformArray[16], outTransformArray[17], outTransformArray[18], outTransformArray[19]));
  847. rightCalib.SetColumn(1, new Vector4(outTransformArray[20], outTransformArray[21], outTransformArray[22], outTransformArray[23]));
  848. rightCalib.SetColumn(2, new Vector4(outTransformArray[24], outTransformArray[25], outTransformArray[26], outTransformArray[27]));
  849. rightCalib.SetColumn(3, new Vector4(outTransformArray[28], outTransformArray[29], outTransformArray[30], outTransformArray[31]));
  850. leftCamera.worldToCameraMatrix = leftcalib * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  851. rightCamera.worldToCameraMatrix = rightCalib * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  852. //if (Input.GetMouseButton(0)) {
  853. // leftCamera.worldToCameraMatrix = leftcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  854. // rightCamera.worldToCameraMatrix = rightcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  855. //Matrix4x4 FLIP_Z = Matrix4x4.Scale(new Vector3(1, 1, -1));
  856. //Matrix4x4 transformLeft = Matrix4x4.Translate(new Vector3(0.032f, 0, 0));
  857. //Matrix4x4 transformRight = Matrix4x4.Translate(new Vector3(-0.032f, 0, 0));
  858. //Matrix4x4 rotation = Matrix4x4.Rotate(headPose.orientation);
  859. //Matrix4x4 position = Matrix4x4.Translate(headPose.position);
  860. //leftCamera.worldToCameraMatrix = leftcalibration * transformLeft * rotation * position * FLIP_Z;
  861. //rightCamera.worldToCameraMatrix = rightcalibration * transformRight * rotation * position * FLIP_Z;
  862. //Debug.Log("NEW:" + leftCamera.transform.localEulerAngles.x + " " + leftCamera.transform.localEulerAngles.y + " " + leftCamera.transform.localEulerAngles.z);
  863. //Debug.Log("NEW:" + rightCamera.transform.localEulerAngles.x + " " + rightCamera.transform.localEulerAngles.y + " " + rightCamera.transform.localEulerAngles.z);
  864. //Debug.Log("Head NEW:" + head.transform.eulerAngles.x + " " + head.transform.eulerAngles.y + " " + head.transform.eulerAngles.z);
  865. //leftCamera.worldToCameraMatrix = leftcalibration * leftPD * initView;//leftcalibration * leftPD * initView;
  866. //rightCamera.worldToCameraMatrix = rightcalibration * rightPD * initView;// rightcalibration * rightPD * initView;
  867. //leftCamera.worldToCameraMatrix = leftXIE;//leftcalibration * leftPD * initView;
  868. //rightCamera.worldToCameraMatrix = rigthXIE;// rightcalibration * rightPD * initView;
  869. //Debug.Log(leftcalibration * leftPD * initView);
  870. //Debug.Log(rightcalibration * rightPD * initView);
  871. //leftCamera.worldToCameraMatrix = initView;
  872. //rightCamera.worldToCameraMatrix = initView;
  873. // Debug.Log($"leftCamera worldToCameraMatrix=[{leftCamera.worldToCameraMatrix.m00}, {leftCamera.worldToCameraMatrix.m01}, {leftCamera.worldToCameraMatrix.m02}, {leftCamera.worldToCameraMatrix.m03};" +
  874. //$"{leftCamera.worldToCameraMatrix.m10}, {leftCamera.worldToCameraMatrix.m11}, {leftCamera.worldToCameraMatrix.m12}, {leftCamera.worldToCameraMatrix.m13};" +
  875. //$"{leftCamera.worldToCameraMatrix.m20}, {leftCamera.worldToCameraMatrix.m21}, {leftCamera.worldToCameraMatrix.m22}, {leftCamera.worldToCameraMatrix.m23};" +
  876. //$"{leftCamera.worldToCameraMatrix.m30}, {leftCamera.worldToCameraMatrix.m31}, {leftCamera.worldToCameraMatrix.m32}, {leftCamera.worldToCameraMatrix.m33}]");
  877. // Debug.Log($"rightCamera worldToCameraMatrix=[{rightCamera.worldToCameraMatrix.m00}, {rightCamera.worldToCameraMatrix.m01}, {rightCamera.worldToCameraMatrix.m02}, {rightCamera.worldToCameraMatrix.m03};" +
  878. // $"{rightCamera.worldToCameraMatrix.m10}, {rightCamera.worldToCameraMatrix.m11}, {rightCamera.worldToCameraMatrix.m12}, {rightCamera.worldToCameraMatrix.m13};" +
  879. // $"{rightCamera.worldToCameraMatrix.m20}, {rightCamera.worldToCameraMatrix.m21}, {rightCamera.worldToCameraMatrix.m22}, {rightCamera.worldToCameraMatrix.m23};" +
  880. // $"{rightCamera.worldToCameraMatrix.m30}, {rightCamera.worldToCameraMatrix.m31}, {rightCamera.worldToCameraMatrix.m32}, {rightCamera.worldToCameraMatrix.m33}]");
  881. //} else if (Input.GetMouseButton(0) == false) {
  882. //Matrix4x4 FLIP_Z = Matrix4x4.Scale(new Vector3(1, 1, -1));
  883. //Matrix4x4 transformLeft = Matrix4x4.Translate(new Vector3(0.032f, 0, 0));
  884. //Matrix4x4 transformRight = Matrix4x4.Translate(new Vector3(-0.032f, 0, 0));
  885. //Matrix4x4 rotation = Matrix4x4.Rotate(headPose.orientation);
  886. //Matrix4x4 position = Matrix4x4.Translate(headPose.position);
  887. //leftCamera.worldToCameraMatrix = transformLeft * rotation * position * FLIP_Z;
  888. //rightCamera.worldToCameraMatrix = transformRight * rotation * position * FLIP_Z;
  889. //Debug.Log("OLD:"+ leftCamera.transform.localEulerAngles.x + " "+ leftCamera.transform.localEulerAngles.y +" "+ leftCamera.transform.localEulerAngles.z);
  890. //Debug.Log("OLD:" + rightCamera.transform.localEulerAngles.x + " " + rightCamera.transform.localEulerAngles.y + " " + rightCamera.transform.localEulerAngles.z);
  891. ////leftCamera.worldToCameraMatrix = leftcalibration * leftPD * initView;//leftcalibration * leftPD * initView;
  892. ////rightCamera.worldToCameraMatrix = rightcalibration * rightPD * initView;// rightcalibration * rightPD * initView;
  893. ////leftCamera.worldToCameraMatrix = leftcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  894. ////rightCamera.worldToCameraMatrix = rightcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  895. //leftCamera.ResetWorldToCameraMatrix();
  896. //rightCamera.ResetWorldToCameraMatrix();
  897. //Debug.Log(leftCamera.worldToCameraMatrix);
  898. //Debug.Log(rightCamera.worldToCameraMatrix);
  899. //Debug.Log("Head OLD:" + head.transform.eulerAngles.x + " " + head.transform.eulerAngles.y + " " + head.transform.eulerAngles.z);
  900. //}
  901. } else {
  902. leftCamera.ResetWorldToCameraMatrix();
  903. rightCamera.ResetWorldToCameraMatrix();
  904. // if (Input.GetMouseButton(0)) {
  905. // //leftCamera.worldToCameraMatrix = leftcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  906. // //rightCamera.worldToCameraMatrix = rightcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  907. // Matrix4x4 FLIP_Z = Matrix4x4.Scale(new Vector3(1, 1, -1));
  908. // Matrix4x4 transformLeft = Matrix4x4.Translate(new Vector3(0.032f, 0, 0));
  909. // Matrix4x4 transformRight = Matrix4x4.Translate(new Vector3(-0.032f, 0, 0));
  910. // Matrix4x4 rotation = Matrix4x4.Rotate(headPose.orientation);
  911. // Matrix4x4 position = Matrix4x4.Translate(headPose.position);
  912. // leftCamera.worldToCameraMatrix = leftcalibration * transformLeft * rotation * position * FLIP_Z;
  913. // rightCamera.worldToCameraMatrix = rightcalibration * transformRight * rotation * position * FLIP_Z;
  914. // //leftCamera.worldToCameraMatrix = leftcalibration * leftPD * initView;//leftcalibration * leftPD * initView;
  915. // //rightCamera.worldToCameraMatrix = rightcalibration * rightPD * initView;// rightcalibration * rightPD * initView;
  916. // //leftCamera.worldToCameraMatrix = leftXIE;//leftcalibration * leftPD * initView;
  917. // //rightCamera.worldToCameraMatrix = rigthXIE;// rightcalibration * rightPD * initView;
  918. // //Debug.Log(leftcalibration * leftPD * initView);
  919. // //Debug.Log(rightcalibration * rightPD * initView);
  920. // //leftCamera.worldToCameraMatrix = initView;
  921. // //rightCamera.worldToCameraMatrix = initView;
  922. // Debug.Log($"leftCamera worldToCameraMatrix=[{leftCamera.worldToCameraMatrix.m00}, {leftCamera.worldToCameraMatrix.m01}, {leftCamera.worldToCameraMatrix.m02}, {leftCamera.worldToCameraMatrix.m03};" +
  923. //$"{leftCamera.worldToCameraMatrix.m10}, {leftCamera.worldToCameraMatrix.m11}, {leftCamera.worldToCameraMatrix.m12}, {leftCamera.worldToCameraMatrix.m13};" +
  924. //$"{leftCamera.worldToCameraMatrix.m20}, {leftCamera.worldToCameraMatrix.m21}, {leftCamera.worldToCameraMatrix.m22}, {leftCamera.worldToCameraMatrix.m23};" +
  925. //$"{leftCamera.worldToCameraMatrix.m30}, {leftCamera.worldToCameraMatrix.m31}, {leftCamera.worldToCameraMatrix.m32}, {leftCamera.worldToCameraMatrix.m33}]");
  926. // Debug.Log($"rightCamera worldToCameraMatrix=[{rightCamera.worldToCameraMatrix.m00}, {rightCamera.worldToCameraMatrix.m01}, {rightCamera.worldToCameraMatrix.m02}, {rightCamera.worldToCameraMatrix.m03};" +
  927. // $"{rightCamera.worldToCameraMatrix.m10}, {rightCamera.worldToCameraMatrix.m11}, {rightCamera.worldToCameraMatrix.m12}, {rightCamera.worldToCameraMatrix.m13};" +
  928. // $"{rightCamera.worldToCameraMatrix.m20}, {rightCamera.worldToCameraMatrix.m21}, {rightCamera.worldToCameraMatrix.m22}, {rightCamera.worldToCameraMatrix.m23};" +
  929. // $"{rightCamera.worldToCameraMatrix.m30}, {rightCamera.worldToCameraMatrix.m31}, {rightCamera.worldToCameraMatrix.m32}, {rightCamera.worldToCameraMatrix.m33}]");
  930. // } else if (Input.GetMouseButton(0) == false) {
  931. // //leftCamera.ResetWorldToCameraMatrix();
  932. // //rightCamera.ResetWorldToCameraMatrix();
  933. // //leftCamera.worldToCameraMatrix = leftcalibration * leftPD * initView;//leftcalibration * leftPD * initView;
  934. // //rightCamera.worldToCameraMatrix = rightcalibration * rightPD * initView;// rightcalibration * rightPD * initView;
  935. // leftCamera.worldToCameraMatrix = leftcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(leftCamera.transform.position, leftCamera.transform.rotation, leftCamera.transform.lossyScale));
  936. // rightCamera.worldToCameraMatrix = rightcalibration * invertZ * Matrix4x4.Inverse(Matrix4x4.TRS(rightCamera.transform.position, rightCamera.transform.rotation, rightCamera.transform.lossyScale));
  937. // Debug.Log(leftCamera.worldToCameraMatrix);
  938. // Debug.Log(rightCamera.worldToCameraMatrix);
  939. // leftCamera.ResetWorldToCameraMatrix();
  940. // rightCamera.ResetWorldToCameraMatrix();
  941. // }
  942. }
  943. }
  944. public void Shutdown()
  945. {
  946. Debug.Log("SvrManager.Shutdown()");
  947. status.running = false;
  948. if (submitFrame != null) { StopCoroutine(submitFrame); submitFrame = null; }
  949. if (plugin.IsRunning()) plugin.EndVr();
  950. if (plugin.IsInitialized()) plugin.Shutdown();
  951. status.initialized = false;
  952. }
  953. void OnDestroy() {
  954. if (Instance != this)
  955. return;
  956. Debug.Log("SvrManager.OnDestroy()");
  957. UnregisterListeners();
  958. Shutdown();
  959. }
  960. public delegate void OnApplicationPauseDele(bool pause);
  961. public static event OnApplicationPauseDele onApplicationPauseDele;
  962. void OnApplicationPause(bool pause)
  963. {
  964. Debug.LogFormat("SvrManager.OnApplicationPause({0})",pause);
  965. onApplicationPauseDele?.Invoke(pause);
  966. SetPause(pause);
  967. }
  968. void OnApplicationQuit()
  969. {
  970. //Debug.Log("SvrManager.OnApplicationQuit()");
  971. //Shutdown();
  972. }
  973. static public Matrix4x4 Perspective(float left, float right, float bottom, float top, float near, float far)
  974. {
  975. float x = 2.0F * near / (right - left);
  976. float y = 2.0F * near / (top - bottom);
  977. float a = (right + left) / (right - left);
  978. float b = (top + bottom) / (top - bottom);
  979. float c = -(far + near) / (far - near);
  980. float d = -(2.0F * far * near) / (far - near);
  981. float e = -1.0F;
  982. Matrix4x4 m = new Matrix4x4();
  983. m[0, 0] = x;
  984. m[0, 1] = 0;
  985. m[0, 2] = a;
  986. m[0, 3] = 0;
  987. m[1, 0] = 0;
  988. m[1, 1] = y;
  989. m[1, 2] = b;
  990. m[1, 3] = 0;
  991. m[2, 0] = 0;
  992. m[2, 1] = 0;
  993. m[2, 2] = c;
  994. m[2, 3] = d;
  995. m[3, 0] = 0;
  996. m[3, 1] = 0;
  997. m[3, 2] = e;
  998. m[3, 3] = 0;
  999. return m;
  1000. }
  1001. void RegisterListeners()
  1002. {
  1003. SvrOverrideSettings.OnEyeAntiAliasingChangedEvent += OnEyeAntiAliasingChanged;
  1004. SvrOverrideSettings.OnEyeDepthChangedEvent += OnEyeDepthChanged;
  1005. SvrOverrideSettings.OnEyeResolutionScaleFactorChangedEvent += OnEyeResolutionScaleFactorChanged;
  1006. SvrOverrideSettings.OnOverlayAntiAliasingChangedEvent += OnOverlayAntiAliasingChanged;
  1007. SvrOverrideSettings.OnOverlayDepthChangedEvent += OnOverlayDepthChanged;
  1008. SvrOverrideSettings.OnOverlayResolutionScaleFactorChangedEvent += OnOverlayResolutionScaleFactorChanged;
  1009. SvrOverrideSettings.OnChromaticAberrationCorrectionChangedEvent += OnChromaticAberrationCorrectionChanged;
  1010. SvrOverrideSettings.OnVSyncCountChangedEvent += OnVSyncCountChanged;
  1011. SvrOverrideSettings.OnMasterTextureLimitChangedEvent += OnMasterTextureLimitChanged;
  1012. SvrOverrideSettings.OnPerfLevelChangedEvent += OnPerfLevelChanged;
  1013. SvrOverrideSettings.OnFoveateChangedEvent += OnFoveateChanged;
  1014. }
  1015. void UnregisterListeners()
  1016. {
  1017. SvrOverrideSettings.OnEyeAntiAliasingChangedEvent -= OnEyeAntiAliasingChanged;
  1018. SvrOverrideSettings.OnEyeDepthChangedEvent -= OnEyeDepthChanged;
  1019. SvrOverrideSettings.OnEyeResolutionScaleFactorChangedEvent -= OnEyeResolutionScaleFactorChanged;
  1020. SvrOverrideSettings.OnOverlayAntiAliasingChangedEvent -= OnOverlayAntiAliasingChanged;
  1021. SvrOverrideSettings.OnOverlayDepthChangedEvent -= OnOverlayDepthChanged;
  1022. SvrOverrideSettings.OnOverlayResolutionScaleFactorChangedEvent -= OnOverlayResolutionScaleFactorChanged;
  1023. SvrOverrideSettings.OnChromaticAberrationCorrectionChangedEvent -= OnChromaticAberrationCorrectionChanged;
  1024. SvrOverrideSettings.OnVSyncCountChangedEvent -= OnVSyncCountChanged;
  1025. SvrOverrideSettings.OnMasterTextureLimitChangedEvent -= OnMasterTextureLimitChanged;
  1026. SvrOverrideSettings.OnPerfLevelChangedEvent -= OnPerfLevelChanged;
  1027. SvrOverrideSettings.OnFoveateChangedEvent -= OnFoveateChanged;
  1028. }
  1029. void OnEyeAntiAliasingChanged(SvrOverrideSettings.eAntiAliasing antiAliasing)
  1030. {
  1031. foreach (SvrEye eye in eyes)
  1032. {
  1033. eye.AntiAliasing = antiAliasing == SvrOverrideSettings.eAntiAliasing.NoOverride ?
  1034. (int)settings.eyeAntiAliasing : (int)antiAliasing;
  1035. }
  1036. }
  1037. void OnEyeDepthChanged(SvrOverrideSettings.eDepth depth)
  1038. {
  1039. foreach (SvrEye eye in eyes)
  1040. {
  1041. eye.Depth = depth == SvrOverrideSettings.eDepth.NoOverride ?
  1042. (int)settings.eyeDepth : (int)depth;
  1043. }
  1044. }
  1045. void OnEyeResolutionScaleFactorChanged(float scaleFactor)
  1046. {
  1047. foreach (SvrEye eye in eyes)
  1048. {
  1049. eye.ResolutionScaleFactor = scaleFactor <= 0 ? settings.eyeResolutionScaleFactor : scaleFactor;
  1050. }
  1051. }
  1052. void OnOverlayAntiAliasingChanged(SvrOverrideSettings.eAntiAliasing antiAliasing)
  1053. {
  1054. foreach (SvrOverlay overlay in overlays)
  1055. {
  1056. overlay.AntiAliasing = antiAliasing == SvrOverrideSettings.eAntiAliasing.NoOverride ?
  1057. (int)settings.overlayAntiAliasing : (int)antiAliasing;
  1058. }
  1059. }
  1060. void OnOverlayDepthChanged(SvrOverrideSettings.eDepth depth)
  1061. {
  1062. foreach (SvrOverlay overlay in overlays)
  1063. {
  1064. overlay.Depth = depth == SvrOverrideSettings.eDepth.NoOverride ?
  1065. (int)settings.overlayDepth : (int)depth;
  1066. }
  1067. }
  1068. void OnOverlayResolutionScaleFactorChanged(float scaleFactor)
  1069. {
  1070. foreach (SvrOverlay overlay in overlays)
  1071. {
  1072. overlay.ResolutionScaleFactor = scaleFactor <= 0 ? settings.overlayResolutionScaleFactor : scaleFactor;
  1073. }
  1074. }
  1075. void OnChromaticAberrationCorrectionChanged(SvrOverrideSettings.eChromaticAberrationCorrection aberrationCorrection)
  1076. {
  1077. if(aberrationCorrection == SvrOverrideSettings.eChromaticAberrationCorrection.kDisable)
  1078. {
  1079. plugin.SetFrameOption(SvrPlugin.FrameOption.kDisableChromaticCorrection);
  1080. }
  1081. else
  1082. {
  1083. plugin.UnsetFrameOption(SvrPlugin.FrameOption.kDisableChromaticCorrection);
  1084. }
  1085. }
  1086. void OnVSyncCountChanged(SvrOverrideSettings.eVSyncCount vSyncCount)
  1087. {
  1088. if (vSyncCount == SvrOverrideSettings.eVSyncCount.NoOverride)
  1089. {
  1090. plugin.SetVSyncCount((int)settings.vSyncCount);
  1091. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  1092. }
  1093. else
  1094. {
  1095. plugin.SetVSyncCount((int)vSyncCount);
  1096. QualitySettings.vSyncCount = (int)settings.vSyncCount;
  1097. }
  1098. }
  1099. void OnMasterTextureLimitChanged(SvrOverrideSettings.eMasterTextureLimit masterTextureLimit)
  1100. {
  1101. QualitySettings.masterTextureLimit = masterTextureLimit == SvrOverrideSettings.eMasterTextureLimit.NoOverride ?
  1102. (int)settings.masterTextureLimit : (int)masterTextureLimit;
  1103. }
  1104. void OnPerfLevelChanged(SvrOverrideSettings.ePerfLevel cpuPerfLevel, SvrOverrideSettings.ePerfLevel gpuPerfLevel)
  1105. {
  1106. int currentCpuPerfLevel = cpuPerfLevel == SvrOverrideSettings.ePerfLevel.NoOverride ?
  1107. (int)settings.cpuPerfLevel : (int)SvrOverrideSettings.CpuPerfLevel;
  1108. int currentGpuPerfLevel = gpuPerfLevel == SvrOverrideSettings.ePerfLevel.NoOverride ?
  1109. (int)settings.gpuPerfLevel : (int)SvrOverrideSettings.GpuPerfLevel;
  1110. plugin.SetPerformanceLevels(currentCpuPerfLevel, currentGpuPerfLevel);
  1111. }
  1112. void OnFoveateChanged(Vector2 gain, float area, float minPixelDensity)
  1113. {
  1114. var point = Vector2.zero;
  1115. var currentGain = gain == Vector2.zero ?
  1116. settings.foveationGain : SvrOverrideSettings.FoveateGain;
  1117. var currentArea = area == 0f ?
  1118. settings.foveationArea : SvrOverrideSettings.FoveateArea;
  1119. var currentMinimum = minPixelDensity == 0f ?
  1120. settings.foveationMinimum : SvrOverrideSettings.FoveateMinimum;
  1121. plugin.SetFoveationParameters(0, 0, point.x, point.y, currentGain.x, currentGain.y, currentArea, currentMinimum);
  1122. }
  1123. /// <summary>
  1124. /// Update this instance.
  1125. /// </summary>
  1126. //---------------------------------------------------------------------------------------------
  1127. void Update()
  1128. {
  1129. SvrEvent frameEvent = new SvrEvent ();
  1130. while (plugin.PollEvent(ref frameEvent))
  1131. {
  1132. Debug.LogFormat("SvrEvent: {0}", frameEvent.eventType.ToString());
  1133. for (int i = 0; i < eventListeners.Count; i++) {
  1134. eventListeners [i].OnSvrEvent (frameEvent);
  1135. }
  1136. }
  1137. }
  1138. /// <summary>
  1139. /// Adds the event listener.
  1140. /// </summary>
  1141. /// <param name="listener">Listener.</param>
  1142. //---------------------------------------------------------------------------------------------
  1143. public void AddEventListener(SvrEventListener listener)
  1144. {
  1145. if (listener != null) {
  1146. eventListeners.Insert (0, listener);
  1147. }
  1148. }
  1149. /// <summary>
  1150. /// Start Tracking
  1151. /// </summary>
  1152. /// <returns>Handle to the controller</returns>
  1153. /// <param name="desc">Desc.</param>
  1154. //---------------------------------------------------------------------------------------------
  1155. public int ControllerStartTracking(string desc)
  1156. {
  1157. return plugin.ControllerStartTracking(desc);
  1158. }
  1159. /// <summary>
  1160. /// Stop Tracking
  1161. /// </summary>
  1162. /// <param name="handle">Handle.</param>
  1163. //---------------------------------------------------------------------------------------------
  1164. public void ControllerStopTracking(int handle)
  1165. {
  1166. plugin.ControllerStopTracking(handle);
  1167. }
  1168. /// <summary>
  1169. /// Get current state
  1170. /// </summary>
  1171. /// <returns>Controller State.</returns>
  1172. /// <param name="handle">Handle.</param>
  1173. //---------------------------------------------------------------------------------------------
  1174. public SvrControllerState ControllerGetState(int handle, int space = 0)
  1175. {
  1176. return plugin.ControllerGetState(handle, space);
  1177. }
  1178. /// <summary>
  1179. /// Send an event to the controller
  1180. /// </summary>
  1181. /// <param name="handle">Handle.</param>
  1182. /// <param name="what">What.</param>
  1183. /// <param name="arg1">Arg1.</param>
  1184. /// <param name="arg2">Arg2.</param>
  1185. //---------------------------------------------------------------------------------------------
  1186. public void ControllerSendMessage(int handle, SvrController.svrControllerMessageType what, int arg1, int arg2)
  1187. {
  1188. plugin.ControllerSendMessage (handle, what, arg1, arg2);
  1189. }
  1190. /// <summary>
  1191. /// Controllers the query.
  1192. /// </summary>
  1193. /// <returns>The query.</returns>
  1194. /// <param name="handle">Handle.</param>
  1195. /// <param name="what">What.</param>
  1196. /// <param name="mem">Mem.</param>
  1197. /// <param name="size">Size.</param>
  1198. //---------------------------------------------------------------------------------------------
  1199. public object ControllerQuery(int handle, SvrController.svrControllerQueryType what)
  1200. {
  1201. return plugin.ControllerQuery (handle, what);
  1202. }
  1203. }