XRSystem.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. // XRSystem is where information about XR views and passes are read from 2 exclusive sources:
  2. // - XRDisplaySubsystem from the XR SDK
  3. // - the test automated test framework
  4. #if ENABLE_VR && ENABLE_XR_MODULE
  5. using System;
  6. using System.Collections.Generic;
  7. using UnityEngine.XR;
  8. namespace UnityEngine.Rendering.Universal
  9. {
  10. internal partial class XRSystem
  11. {
  12. // Valid empty pass when a camera is not using XR
  13. internal readonly XRPass emptyPass = new XRPass();
  14. // Store active passes and avoid allocating memory every frames
  15. List<XRPass> framePasses = new List<XRPass>();
  16. // XR SDK display interface
  17. static List<XRDisplaySubsystem> displayList = new List<XRDisplaySubsystem>();
  18. XRDisplaySubsystem display = null;
  19. // XRSDK does not support msaa per XR display. All displays share the same msaa level.
  20. static int msaaLevel = 1;
  21. // Internal resources used by XR rendering
  22. Material occlusionMeshMaterial = null;
  23. Material mirrorViewMaterial = null;
  24. MaterialPropertyBlock mirrorViewMaterialProperty = new MaterialPropertyBlock();
  25. RenderTexture testRenderTexture = null;
  26. const string k_XRMirrorTag = "XR Mirror View";
  27. static ProfilingSampler _XRMirrorProfilingSampler = new ProfilingSampler(k_XRMirrorTag);
  28. internal XRSystem()
  29. {
  30. RefreshXrSdk();
  31. TextureXR.maxViews = Math.Max(TextureXR.slices, GetMaxViews());
  32. }
  33. internal void InitializeXRSystemData(XRSystemData data)
  34. {
  35. if (data)
  36. {
  37. if (occlusionMeshMaterial != null)
  38. CoreUtils.Destroy(occlusionMeshMaterial);
  39. if (mirrorViewMaterial != null)
  40. CoreUtils.Destroy(mirrorViewMaterial);
  41. occlusionMeshMaterial = CoreUtils.CreateEngineMaterial(data.shaders.xrOcclusionMeshPS);
  42. mirrorViewMaterial = CoreUtils.CreateEngineMaterial(data.shaders.xrMirrorViewPS);
  43. }
  44. }
  45. static void GetDisplaySubsystem()
  46. {
  47. #if UNITY_2020_2_OR_NEWER
  48. //SubsystemManager.GetSubsystems(displayList);
  49. SubsystemManager.GetInstances(displayList);
  50. #else
  51. SubsystemManager.GetInstances(displayList);
  52. #endif
  53. }
  54. // With XR SDK: disable legacy VR system before rendering first frame
  55. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
  56. internal static void XRSystemInit()
  57. {
  58. if (GraphicsSettings.currentRenderPipeline == null)
  59. return;
  60. GetDisplaySubsystem();
  61. // XRTODO: refactor with RefreshXrSdk()
  62. for (int i = 0; i < displayList.Count; i++)
  63. {
  64. displayList[i].disableLegacyRenderer = true;
  65. displayList[i].textureLayout = XRDisplaySubsystem.TextureLayout.Texture2DArray;
  66. displayList[i].sRGB = QualitySettings.activeColorSpace == ColorSpace.Linear;
  67. }
  68. }
  69. internal static void UpdateMSAALevel(int level)
  70. {
  71. if (msaaLevel == level)
  72. return;
  73. level = Mathf.NextPowerOfTwo(level);
  74. level = Mathf.Clamp(level, (int)MsaaQuality.Disabled, (int)MsaaQuality._8x);
  75. GetDisplaySubsystem();
  76. #if UNITY_2020_2_OR_NEWER
  77. for (int i = 0; i < displayList.Count; i++)
  78. displayList[i].SetMSAALevel(level);
  79. #endif
  80. msaaLevel = level;
  81. }
  82. internal static int GetMSAALevel()
  83. {
  84. return msaaLevel;
  85. }
  86. internal static void UpdateRenderScale(float renderScale)
  87. {
  88. GetDisplaySubsystem();
  89. for (int i = 0; i < displayList.Count; i++)
  90. displayList[i].scaleOfAllRenderTargets = renderScale;
  91. }
  92. // Compute the maximum number of views (slices) to allocate for texture arrays
  93. internal int GetMaxViews()
  94. {
  95. int maxViews = 1;
  96. if (display != null)
  97. {
  98. // XRTODO : replace by API from XR SDK, assume we have 2 slices until then
  99. maxViews = 2;
  100. }
  101. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  102. else if (XRGraphicsAutomatedTests.enabled)
  103. {
  104. maxViews = Math.Max(maxViews, 2);
  105. }
  106. #endif
  107. return maxViews;
  108. }
  109. internal void BeginLateLatching(Camera camera, XRPass xrPass)
  110. {
  111. //Only support late latching for multiview use case
  112. if (display != null && xrPass.singlePassEnabled && xrPass.viewCount == 2)
  113. {
  114. display.BeginRecordingIfLateLatched(camera);
  115. xrPass.isLateLatchEnabled = true;
  116. }
  117. }
  118. internal void EndLateLatching(Camera camera, XRPass xrPass)
  119. {
  120. if (display != null && xrPass.isLateLatchEnabled)
  121. {
  122. display.EndRecordingIfLateLatched(camera);
  123. xrPass.isLateLatchEnabled = false;
  124. }
  125. }
  126. internal List<XRPass> SetupFrame(Camera camera, bool enableXRRendering)
  127. {
  128. bool xrEnabled = RefreshXrSdk();
  129. if (display != null)
  130. {
  131. // XRTODO: Handle stereo mode selection in URP pipeline asset UI
  132. display.textureLayout = XRDisplaySubsystem.TextureLayout.Texture2DArray;
  133. display.zNear = camera.nearClipPlane;
  134. display.zFar = camera.farClipPlane;
  135. display.sRGB = QualitySettings.activeColorSpace == ColorSpace.Linear;
  136. }
  137. if (framePasses.Count > 0)
  138. {
  139. Debug.LogWarning("XRSystem.ReleaseFrame() was not called!");
  140. ReleaseFrame();
  141. }
  142. if (camera == null)
  143. return framePasses;
  144. // Enable XR layout only for game camera
  145. bool isGameCamera = (camera.cameraType == CameraType.Game || camera.cameraType == CameraType.VR);
  146. bool xrSupported = isGameCamera && camera.targetTexture == null && enableXRRendering;
  147. if (xrEnabled && xrSupported)
  148. {
  149. // Disable vsync on the main display when rendering to a XR device.
  150. QualitySettings.vSyncCount = 0;
  151. // On Android and iOS, vSyncCount is ignored and all frame rate control is done using Application.targetFrameRate.
  152. float frameRate = 300.0f;
  153. Application.targetFrameRate = Mathf.CeilToInt(frameRate);
  154. CreateLayoutFromXrSdk(camera, singlePassAllowed: true);
  155. OverrideForAutomatedTests(camera);
  156. }
  157. else
  158. {
  159. AddPassToFrame(emptyPass);
  160. }
  161. return framePasses;
  162. }
  163. internal void ReleaseFrame()
  164. {
  165. for (int i = 0; i < framePasses.Count; i++)
  166. {
  167. // Pop from the back to keep initial ordering (see implementation of ObjectPool)
  168. var xrPass = framePasses[framePasses.Count - i - 1];
  169. if (xrPass != emptyPass)
  170. XRPass.Release(xrPass);
  171. }
  172. framePasses.Clear();
  173. if (testRenderTexture)
  174. RenderTexture.ReleaseTemporary(testRenderTexture);
  175. }
  176. internal bool RefreshXrSdk()
  177. {
  178. GetDisplaySubsystem();
  179. if (displayList.Count > 0)
  180. {
  181. if (displayList.Count > 1)
  182. throw new NotImplementedException("Only 1 XR display is supported.");
  183. display = displayList[0];
  184. display.disableLegacyRenderer = true;
  185. // Refresh max views
  186. TextureXR.maxViews = Math.Max(TextureXR.slices, GetMaxViews());
  187. return display.running;
  188. }
  189. else
  190. {
  191. display = null;
  192. }
  193. return false;
  194. }
  195. // Used for updating URP cameraData data struct with XRPass data.
  196. internal void UpdateCameraData(ref CameraData baseCameraData, in XRPass xr)
  197. {
  198. // Update cameraData viewport for XR
  199. Rect cameraRect = baseCameraData.camera.rect;
  200. Rect xrViewport = xr.GetViewport();
  201. baseCameraData.pixelRect = new Rect(cameraRect.x * xrViewport.width + xrViewport.x,
  202. cameraRect.y * xrViewport.height + xrViewport.y,
  203. cameraRect.width * xrViewport.width,
  204. cameraRect.height * xrViewport.height);
  205. Rect camPixelRect = baseCameraData.pixelRect;
  206. baseCameraData.pixelWidth = (int)System.Math.Round(camPixelRect.width + camPixelRect.x) - (int)System.Math.Round(camPixelRect.x);
  207. baseCameraData.pixelHeight = (int)System.Math.Round(camPixelRect.height + camPixelRect.y) - (int)System.Math.Round(camPixelRect.y);
  208. baseCameraData.aspectRatio = (float)baseCameraData.pixelWidth / (float)baseCameraData.pixelHeight;
  209. bool isDefaultXRViewport = (!(Math.Abs(xrViewport.x) > 0.0f || Math.Abs(xrViewport.y) > 0.0f ||
  210. Math.Abs(xrViewport.width) < xr.renderTargetDesc.width ||
  211. Math.Abs(xrViewport.height) < xr.renderTargetDesc.height));
  212. baseCameraData.isDefaultViewport = baseCameraData.isDefaultViewport && isDefaultXRViewport;
  213. // Update cameraData cameraTargetDescriptor for XR. This descriptor is mainly used for configuring intermediate screen space textures
  214. var originalTargetDesc = baseCameraData.cameraTargetDescriptor;
  215. baseCameraData.cameraTargetDescriptor = xr.renderTargetDesc;
  216. if (baseCameraData.isHdrEnabled)
  217. {
  218. baseCameraData.cameraTargetDescriptor.graphicsFormat = originalTargetDesc.graphicsFormat;
  219. }
  220. baseCameraData.cameraTargetDescriptor.msaaSamples = originalTargetDesc.msaaSamples;
  221. baseCameraData.cameraTargetDescriptor.width = baseCameraData.pixelWidth;
  222. baseCameraData.cameraTargetDescriptor.height = baseCameraData.pixelHeight;
  223. }
  224. // Used for camera stacking where we need to update the parameters per camera
  225. internal void UpdateFromCamera(ref XRPass xrPass, CameraData cameraData)
  226. {
  227. if (xrPass.enabled && display != null)
  228. {
  229. display.GetRenderPass(xrPass.multipassId, out var renderPass);
  230. display.GetCullingParameters(cameraData.camera, renderPass.cullingPassIndex, out var cullingParams);
  231. // Disable legacy stereo culling path
  232. cullingParams.cullingOptions &= ~CullingOptions.Stereo;
  233. xrPass.UpdateCullingParams(cullingPassId: renderPass.cullingPassIndex, cullingParams);
  234. if (xrPass.singlePassEnabled)
  235. {
  236. for (int renderParamIndex = 0; renderParamIndex < renderPass.GetRenderParameterCount(); ++renderParamIndex)
  237. {
  238. renderPass.GetRenderParameter(cameraData.camera, renderParamIndex, out var renderParam);
  239. xrPass.UpdateView(renderParamIndex, renderPass, renderParam);
  240. }
  241. }
  242. else
  243. {
  244. renderPass.GetRenderParameter(cameraData.camera, 0, out var renderParam);
  245. xrPass.UpdateView(0, renderPass, renderParam);
  246. }
  247. OverrideForAutomatedTests(cameraData.camera);
  248. }
  249. }
  250. void CreateLayoutFromXrSdk(Camera camera, bool singlePassAllowed)
  251. {
  252. bool CanUseSinglePass(XRDisplaySubsystem.XRRenderPass renderPass)
  253. {
  254. if (renderPass.renderTargetDesc.dimension != TextureDimension.Tex2DArray)
  255. return false;
  256. if (renderPass.GetRenderParameterCount() != 2 || renderPass.renderTargetDesc.volumeDepth != 2)
  257. return false;
  258. renderPass.GetRenderParameter(camera, 0, out var renderParam0);
  259. renderPass.GetRenderParameter(camera, 1, out var renderParam1);
  260. if (renderParam0.textureArraySlice != 0 || renderParam1.textureArraySlice != 1)
  261. return false;
  262. if (renderParam0.viewport != renderParam1.viewport)
  263. return false;
  264. return true;
  265. }
  266. for (int renderPassIndex = 0; renderPassIndex < display.GetRenderPassCount(); ++renderPassIndex)
  267. {
  268. display.GetRenderPass(renderPassIndex, out var renderPass);
  269. display.GetCullingParameters(camera, renderPass.cullingPassIndex, out var cullingParams);
  270. // Disable legacy stereo culling path
  271. cullingParams.cullingOptions &= ~CullingOptions.Stereo;
  272. if (singlePassAllowed && CanUseSinglePass(renderPass))
  273. {
  274. var xrPass = XRPass.Create(renderPass, multipassId: framePasses.Count, cullingParams, occlusionMeshMaterial);
  275. for (int renderParamIndex = 0; renderParamIndex < renderPass.GetRenderParameterCount(); ++renderParamIndex)
  276. {
  277. renderPass.GetRenderParameter(camera, renderParamIndex, out var renderParam);
  278. xrPass.AddView(renderPass, renderParam);
  279. }
  280. AddPassToFrame(xrPass);
  281. }
  282. else
  283. {
  284. for (int renderParamIndex = 0; renderParamIndex < renderPass.GetRenderParameterCount(); ++renderParamIndex)
  285. {
  286. renderPass.GetRenderParameter(camera, renderParamIndex, out var renderParam);
  287. var xrPass = XRPass.Create(renderPass, multipassId: framePasses.Count, cullingParams, occlusionMeshMaterial);
  288. xrPass.AddView(renderPass, renderParam);
  289. AddPassToFrame(xrPass);
  290. }
  291. }
  292. }
  293. }
  294. internal void Dispose()
  295. {
  296. CoreUtils.Destroy(occlusionMeshMaterial);
  297. CoreUtils.Destroy(mirrorViewMaterial);
  298. }
  299. internal void AddPassToFrame(XRPass xrPass)
  300. {
  301. xrPass.UpdateOcclusionMesh();
  302. framePasses.Add(xrPass);
  303. }
  304. internal static class XRShaderIDs
  305. {
  306. public static readonly int _SourceTexArraySlice = Shader.PropertyToID("_SourceTexArraySlice");
  307. public static readonly int _SRGBRead = Shader.PropertyToID("_SRGBRead");
  308. public static readonly int _SRGBWrite = Shader.PropertyToID("_SRGBWrite");
  309. }
  310. internal void RenderMirrorView(CommandBuffer cmd, Camera camera)
  311. {
  312. // XRTODO : remove this check when the Quest plugin is fixed
  313. if (Application.platform == RuntimePlatform.Android && !XRGraphicsAutomatedTests.running)
  314. return;
  315. if (display == null || !display.running || !mirrorViewMaterial)
  316. return;
  317. using (new ProfilingScope(cmd, _XRMirrorProfilingSampler))
  318. {
  319. cmd.SetRenderTarget(camera.targetTexture != null ? camera.targetTexture : new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget));
  320. bool yflip = camera.targetTexture != null || camera.cameraType == CameraType.SceneView || camera.cameraType == CameraType.Preview;
  321. int mirrorBlitMode = display.GetPreferredMirrorBlitMode();
  322. if (display.GetMirrorViewBlitDesc(null, out var blitDesc, mirrorBlitMode))
  323. {
  324. if (blitDesc.nativeBlitAvailable)
  325. {
  326. display.AddGraphicsThreadMirrorViewBlit(cmd, blitDesc.nativeBlitInvalidStates, mirrorBlitMode);
  327. }
  328. else
  329. {
  330. for (int i = 0; i < blitDesc.blitParamsCount; ++i)
  331. {
  332. blitDesc.GetBlitParameter(i, out var blitParam);
  333. Vector4 scaleBias = yflip ? new Vector4(blitParam.srcRect.width, -blitParam.srcRect.height, blitParam.srcRect.x, blitParam.srcRect.height + blitParam.srcRect.y) :
  334. new Vector4(blitParam.srcRect.width, blitParam.srcRect.height, blitParam.srcRect.x, blitParam.srcRect.y);
  335. Vector4 scaleBiasRt = new Vector4(blitParam.destRect.width, blitParam.destRect.height, blitParam.destRect.x, blitParam.destRect.y);
  336. // Eye texture is always gamma corrected, use explicit sRGB read in shader if srcTex formats is not sRGB format. sRGB format will have implicit sRGB read so it is already handled.
  337. mirrorViewMaterialProperty.SetFloat(XRShaderIDs._SRGBRead, (blitParam.srcTex.sRGB) ? 0.0f : 1.0f);
  338. // Perform explicit sRGB write in shader if color space is gamma
  339. mirrorViewMaterialProperty.SetFloat(XRShaderIDs._SRGBWrite, (QualitySettings.activeColorSpace == ColorSpace.Linear) ? 0.0f : 1.0f);
  340. mirrorViewMaterialProperty.SetTexture(ShaderPropertyId.sourceTex, blitParam.srcTex);
  341. mirrorViewMaterialProperty.SetVector(ShaderPropertyId.scaleBias, scaleBias);
  342. mirrorViewMaterialProperty.SetVector(ShaderPropertyId.scaleBiasRt, scaleBiasRt);
  343. mirrorViewMaterialProperty.SetFloat(XRShaderIDs._SourceTexArraySlice, (float)blitParam.srcTexArraySlice);
  344. int shaderPass = (blitParam.srcTex.dimension == TextureDimension.Tex2DArray) ? 1 : 0;
  345. cmd.DrawProcedural(Matrix4x4.identity, mirrorViewMaterial, shaderPass, MeshTopology.Quads, 4, 1, mirrorViewMaterialProperty);
  346. }
  347. }
  348. }
  349. else
  350. {
  351. cmd.ClearRenderTarget(true, true, Color.black);
  352. }
  353. }
  354. }
  355. private void OverrideForAutomatedTests(Camera camera)
  356. {
  357. #if DEVELOPMENT_BUILD || UNITY_EDITOR
  358. if (XRGraphicsAutomatedTests.enabled && XRGraphicsAutomatedTests.running)
  359. {
  360. var camProjMatrix = camera.projectionMatrix;
  361. var camViewMatrix = camera.worldToCameraMatrix;
  362. if (camera.TryGetCullingParameters(false, out var cullingParams))
  363. {
  364. cullingParams.stereoProjectionMatrix = camProjMatrix;
  365. cullingParams.stereoViewMatrix = camViewMatrix;
  366. cullingParams.stereoSeparationDistance = 0.0f;
  367. cullingParams.cullingOptions &= ~CullingOptions.Stereo;
  368. for (int passId = 0; passId < framePasses.Count; passId++)
  369. {
  370. framePasses[passId].UpdateCullingParams(framePasses[passId].cullingPassId, cullingParams);
  371. for (int viewId = 0; viewId < framePasses[passId].viewCount; viewId++)
  372. {
  373. var projMatrix = camProjMatrix;
  374. var viewMatrix = camViewMatrix;
  375. // Alter the first view in order to detect more issues
  376. bool isFirstViewMultiPass = framePasses.Count == 2 && passId == 0;
  377. bool isFirstViewSinglePass = framePasses.Count == 1 && viewId == 0;
  378. if (isFirstViewMultiPass || isFirstViewSinglePass)
  379. {
  380. var planes = projMatrix.decomposeProjection;
  381. planes.left *= 0.44f;
  382. planes.right *= 0.88f;
  383. planes.top *= 0.11f;
  384. planes.bottom *= 0.33f;
  385. projMatrix = Matrix4x4.Frustum(planes);
  386. viewMatrix *= Matrix4x4.Translate(new Vector3(.34f, 0.25f, -0.08f));
  387. }
  388. framePasses[passId].UpdateView(viewId, projMatrix, viewMatrix, framePasses[passId].GetViewport(viewId), viewId);
  389. }
  390. }
  391. }
  392. }
  393. #endif
  394. }
  395. }
  396. }
  397. #endif