Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

UniversalRenderPipelineCore.cs 98KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004
  1. using System;
  2. using System.Collections.Generic;
  3. using Unity.Collections;
  4. using Unity.Collections.LowLevel.Unsafe;
  5. using UnityEngine.Assertions;
  6. using UnityEngine.Experimental.GlobalIllumination;
  7. using UnityEngine.Experimental.Rendering;
  8. using Lightmapping = UnityEngine.Experimental.GlobalIllumination.Lightmapping;
  9. namespace UnityEngine.Rendering.Universal
  10. {
  11. static class NativeArrayExtensions
  12. {
  13. /// <summary>
  14. /// IMPORTANT: Make sure you do not write to the value! There are no checks for this!
  15. /// </summary>
  16. public static unsafe ref T UnsafeElementAt<T>(this NativeArray<T> array, int index) where T : struct
  17. {
  18. return ref UnsafeUtility.ArrayElementAsRef<T>(array.GetUnsafeReadOnlyPtr(), index);
  19. }
  20. public static unsafe ref T UnsafeElementAtMutable<T>(this NativeArray<T> array, int index) where T : struct
  21. {
  22. return ref UnsafeUtility.ArrayElementAsRef<T>(array.GetUnsafePtr(), index);
  23. }
  24. }
  25. /// <summary>
  26. /// Options for mixed lighting setup.
  27. /// </summary>
  28. public enum MixedLightingSetup
  29. {
  30. /// <summary>
  31. /// Use this to disable mixed lighting.
  32. /// </summary>
  33. None,
  34. /// <summary>
  35. /// Use this to select shadow mask.
  36. /// </summary>
  37. ShadowMask,
  38. /// <summary>
  39. /// Use this to select subtractive.
  40. /// </summary>
  41. Subtractive,
  42. };
  43. /// <summary>
  44. /// Enumeration that indicates what kind of image scaling is occurring if any
  45. /// </summary>
  46. internal enum ImageScalingMode
  47. {
  48. /// No scaling
  49. None,
  50. /// Upscaling to a larger image
  51. Upscaling,
  52. /// Downscaling to a smaller image
  53. Downscaling
  54. }
  55. /// <summary>
  56. /// Enumeration that indicates what kind of upscaling filter is being used
  57. /// </summary>
  58. internal enum ImageUpscalingFilter
  59. {
  60. /// Bilinear filtering
  61. Linear,
  62. /// Nearest-Neighbor filtering
  63. Point,
  64. /// FidelityFX Super Resolution
  65. FSR,
  66. /// Spatial-Temporal Post-Processing
  67. STP
  68. }
  69. /// <summary>
  70. /// Struct that flattens several rendering settings used to render a camera stack.
  71. /// URP builds the <c>RenderingData</c> settings from several places, including the pipeline asset, camera and light settings.
  72. /// The settings also might vary on different platforms and depending on if Adaptive Performance is used.
  73. /// </summary>
  74. public struct RenderingData
  75. {
  76. internal ContextContainer frameData;
  77. internal RenderingData(ContextContainer frameData)
  78. {
  79. this.frameData = frameData;
  80. cameraData = new CameraData(frameData);
  81. lightData = new LightData(frameData);
  82. shadowData = new ShadowData(frameData);
  83. postProcessingData = new PostProcessingData(frameData);
  84. }
  85. internal UniversalRenderingData universalRenderingData => frameData.Get<UniversalRenderingData>();
  86. // Non-rendergraph path only. Do NOT use with rendergraph!
  87. internal ref CommandBuffer commandBuffer
  88. {
  89. get
  90. {
  91. ref var cmd = ref frameData.Get<UniversalRenderingData>().m_CommandBuffer;
  92. if (cmd == null)
  93. Debug.LogError("RenderingData.commandBuffer is null. RenderGraph does not support this property. Please use the command buffer provided by the RenderGraphContext.");
  94. return ref cmd;
  95. }
  96. }
  97. /// <summary>
  98. /// Returns culling results that exposes handles to visible objects, lights and probes.
  99. /// You can use this to draw objects with <c>ScriptableRenderContext.DrawRenderers</c>
  100. /// <see cref="CullingResults"/>
  101. /// <seealso cref="ScriptableRenderContext"/>
  102. /// </summary>
  103. public ref CullingResults cullResults => ref frameData.Get<UniversalRenderingData>().cullResults;
  104. /// <summary>
  105. /// Holds several rendering settings related to camera.
  106. /// <see cref="CameraData"/>
  107. /// </summary>
  108. public CameraData cameraData;
  109. /// <summary>
  110. /// Holds several rendering settings related to lights.
  111. /// <see cref="LightData"/>
  112. /// </summary>
  113. public LightData lightData;
  114. /// <summary>
  115. /// Holds several rendering settings related to shadows.
  116. /// <see cref="ShadowData"/>
  117. /// </summary>
  118. public ShadowData shadowData;
  119. /// <summary>
  120. /// Holds several rendering settings and resources related to the integrated post-processing stack.
  121. /// <see cref="PostProcessData"/>
  122. /// </summary>
  123. public PostProcessingData postProcessingData;
  124. /// <summary>
  125. /// True if the pipeline supports dynamic batching.
  126. /// This settings doesn't apply when drawing shadow casters. Dynamic batching is always disabled when drawing shadow casters.
  127. /// </summary>
  128. public ref bool supportsDynamicBatching => ref frameData.Get<UniversalRenderingData>().supportsDynamicBatching;
  129. /// <summary>
  130. /// Holds per-object data that are requested when drawing
  131. /// <see cref="PerObjectData"/>
  132. /// </summary>
  133. public ref PerObjectData perObjectData => ref frameData.Get<UniversalRenderingData>().perObjectData;
  134. /// <summary>
  135. /// True if post-processing effect is enabled while rendering the camera stack.
  136. /// </summary>
  137. public ref bool postProcessingEnabled => ref frameData.Get<UniversalPostProcessingData>().isEnabled;
  138. }
  139. /// <summary>
  140. /// Struct that holds settings related to lights.
  141. /// </summary>
  142. public struct LightData
  143. {
  144. ContextContainer frameData;
  145. internal LightData(ContextContainer frameData)
  146. {
  147. this.frameData = frameData;
  148. }
  149. internal UniversalLightData universalLightData => frameData.Get<UniversalLightData>();
  150. /// <summary>
  151. /// Holds the main light index from the <c>VisibleLight</c> list returned by culling. If there's no main light in the scene, <c>mainLightIndex</c> is set to -1.
  152. /// The main light is the directional light assigned as Sun source in light settings or the brightest directional light.
  153. /// <seealso cref="CullingResults"/>
  154. /// </summary>
  155. public ref int mainLightIndex => ref frameData.Get<UniversalLightData>().mainLightIndex;
  156. /// <summary>
  157. /// The number of additional lights visible by the camera.
  158. /// </summary>
  159. public ref int additionalLightsCount => ref frameData.Get<UniversalLightData>().additionalLightsCount;
  160. /// <summary>
  161. /// Maximum amount of lights that can be shaded per-object. This value only affects forward rendering.
  162. /// </summary>
  163. public ref int maxPerObjectAdditionalLightsCount => ref frameData.Get<UniversalLightData>().maxPerObjectAdditionalLightsCount;
  164. /// <summary>
  165. /// List of visible lights returned by culling.
  166. /// </summary>
  167. public ref NativeArray<VisibleLight> visibleLights => ref frameData.Get<UniversalLightData>().visibleLights;
  168. /// <summary>
  169. /// True if additional lights should be shaded in vertex shader, otherwise additional lights will be shaded per pixel.
  170. /// </summary>
  171. public ref bool shadeAdditionalLightsPerVertex => ref frameData.Get<UniversalLightData>().shadeAdditionalLightsPerVertex;
  172. /// <summary>
  173. /// True if mixed lighting is supported.
  174. /// </summary>
  175. public ref bool supportsMixedLighting => ref frameData.Get<UniversalLightData>().supportsMixedLighting;
  176. /// <summary>
  177. /// True if box projection is enabled for reflection probes.
  178. /// </summary>
  179. public ref bool reflectionProbeBoxProjection => ref frameData.Get<UniversalLightData>().reflectionProbeBoxProjection;
  180. /// <summary>
  181. /// True if blending is enabled for reflection probes.
  182. /// </summary>
  183. public ref bool reflectionProbeBlending => ref frameData.Get<UniversalLightData>().reflectionProbeBlending;
  184. /// <summary>
  185. /// True if light layers are enabled.
  186. /// </summary>
  187. public ref bool supportsLightLayers => ref frameData.Get<UniversalLightData>().supportsLightLayers;
  188. /// <summary>
  189. /// True if additional lights enabled.
  190. /// </summary>
  191. public ref bool supportsAdditionalLights => ref frameData.Get<UniversalLightData>().supportsAdditionalLights;
  192. }
  193. /// <summary>
  194. /// Struct that holds settings related to camera.
  195. /// </summary>
  196. public struct CameraData
  197. {
  198. ContextContainer frameData;
  199. internal CameraData(ContextContainer frameData)
  200. {
  201. this.frameData = frameData;
  202. }
  203. internal UniversalCameraData universalCameraData => frameData.Get<UniversalCameraData>();
  204. internal void SetViewAndProjectionMatrix(Matrix4x4 viewMatrix, Matrix4x4 projectionMatrix)
  205. {
  206. frameData.Get<UniversalCameraData>().SetViewAndProjectionMatrix(viewMatrix, projectionMatrix);
  207. }
  208. internal void SetViewProjectionAndJitterMatrix(Matrix4x4 viewMatrix, Matrix4x4 projectionMatrix, Matrix4x4 jitterMatrix)
  209. {
  210. frameData.Get<UniversalCameraData>().SetViewProjectionAndJitterMatrix(viewMatrix, projectionMatrix, jitterMatrix);
  211. }
  212. // Helper function to populate builtin stereo matricies as well as URP stereo matricies
  213. internal void PushBuiltinShaderConstantsXR(RasterCommandBuffer cmd, bool renderIntoTexture)
  214. {
  215. frameData.Get<UniversalCameraData>().PushBuiltinShaderConstantsXR(cmd, renderIntoTexture);
  216. }
  217. /// <summary>
  218. /// Returns the camera view matrix.
  219. /// </summary>
  220. /// <param name="viewIndex"> View index in case of stereo rendering. By default <c>viewIndex</c> is set to 0. </param>
  221. /// <returns> The camera view matrix. </returns>
  222. public Matrix4x4 GetViewMatrix(int viewIndex = 0)
  223. {
  224. return frameData.Get<UniversalCameraData>().GetViewMatrix(viewIndex);
  225. }
  226. /// <summary>
  227. /// Returns the camera projection matrix. Might be jittered for temporal features.
  228. /// </summary>
  229. /// <param name="viewIndex"> View index in case of stereo rendering. By default <c>viewIndex</c> is set to 0. </param>
  230. /// <returns> The camera projection matrix. </returns>
  231. public Matrix4x4 GetProjectionMatrix(int viewIndex = 0)
  232. {
  233. return frameData.Get<UniversalCameraData>().GetProjectionMatrix(viewIndex);
  234. }
  235. internal Matrix4x4 GetProjectionMatrixNoJitter(int viewIndex = 0)
  236. {
  237. return frameData.Get<UniversalCameraData>().GetProjectionMatrixNoJitter(viewIndex);
  238. }
  239. /// <summary>
  240. /// Returns the camera GPU projection matrix. This contains platform specific changes to handle y-flip and reverse z. Includes camera jitter if required by active features.
  241. /// Similar to <c>GL.GetGPUProjectionMatrix</c> but queries URP internal state to know if the pipeline is rendering to render texture.
  242. /// For more info on platform differences regarding camera projection check: https://docs.unity3d.com/Manual/SL-PlatformDifferences.html
  243. /// </summary>
  244. /// <param name="viewIndex"> View index in case of stereo rendering. By default <c>viewIndex</c> is set to 0. </param>
  245. /// <seealso cref="GL.GetGPUProjectionMatrix(Matrix4x4, bool)"/>
  246. /// <returns></returns>
  247. public Matrix4x4 GetGPUProjectionMatrix(int viewIndex = 0)
  248. {
  249. return frameData.Get<UniversalCameraData>().GetGPUProjectionMatrix(viewIndex);
  250. }
  251. /// <summary>
  252. /// Returns the camera GPU projection matrix. This contains platform specific changes to handle y-flip and reverse z. Does not include any camera jitter.
  253. /// Similar to <c>GL.GetGPUProjectionMatrix</c> but queries URP internal state to know if the pipeline is rendering to render texture.
  254. /// For more info on platform differences regarding camera projection check: https://docs.unity3d.com/Manual/SL-PlatformDifferences.html
  255. /// </summary>
  256. /// <param name="viewIndex"> View index in case of stereo rendering. By default <c>viewIndex</c> is set to 0. </param>
  257. /// <seealso cref="GL.GetGPUProjectionMatrix(Matrix4x4, bool)"/>
  258. /// <returns></returns>
  259. public Matrix4x4 GetGPUProjectionMatrixNoJitter(int viewIndex = 0)
  260. {
  261. return frameData.Get<UniversalCameraData>().GetGPUProjectionMatrixNoJitter(viewIndex);
  262. }
  263. internal Matrix4x4 GetGPUProjectionMatrix(bool renderIntoTexture, int viewIndex = 0)
  264. {
  265. return frameData.Get<UniversalCameraData>().GetGPUProjectionMatrix(renderIntoTexture, viewIndex);
  266. }
  267. /// <summary>
  268. /// The camera component.
  269. /// </summary>
  270. public ref Camera camera => ref frameData.Get<UniversalCameraData>().camera;
  271. /// <summary>
  272. /// The camera history texture manager. Used to access camera history from a ScriptableRenderPass.
  273. /// </summary>
  274. /// <seealso cref="ScriptableRenderPass"/>
  275. public ref UniversalCameraHistory historyManager => ref frameData.Get<UniversalCameraData>().m_HistoryManager;
  276. /// <summary>
  277. /// The camera render type used for camera stacking.
  278. /// <see cref="CameraRenderType"/>
  279. /// </summary>
  280. public ref CameraRenderType renderType => ref frameData.Get<UniversalCameraData>().renderType;
  281. /// <summary>
  282. /// Controls the final target texture for a camera. If null camera will resolve rendering to screen.
  283. /// </summary>
  284. public ref RenderTexture targetTexture => ref frameData.Get<UniversalCameraData>().targetTexture;
  285. /// <summary>
  286. /// Render texture settings used to create intermediate camera textures for rendering.
  287. /// </summary>
  288. public ref RenderTextureDescriptor cameraTargetDescriptor => ref frameData.Get<UniversalCameraData>().cameraTargetDescriptor;
  289. internal ref Rect pixelRect => ref frameData.Get<UniversalCameraData>().pixelRect;
  290. internal ref bool useScreenCoordOverride => ref frameData.Get<UniversalCameraData>().useScreenCoordOverride;
  291. internal ref Vector4 screenSizeOverride => ref frameData.Get<UniversalCameraData>().screenSizeOverride;
  292. internal ref Vector4 screenCoordScaleBias => ref frameData.Get<UniversalCameraData>().screenCoordScaleBias;
  293. internal ref int pixelWidth => ref frameData.Get<UniversalCameraData>().pixelWidth;
  294. internal ref int pixelHeight => ref frameData.Get<UniversalCameraData>().pixelHeight;
  295. internal ref float aspectRatio => ref frameData.Get<UniversalCameraData>().aspectRatio;
  296. /// <summary>
  297. /// Render scale to apply when creating camera textures. Scaled extents are rounded down to integers.
  298. /// </summary>
  299. public ref float renderScale => ref frameData.Get<UniversalCameraData>().renderScale;
  300. internal ref ImageScalingMode imageScalingMode => ref frameData.Get<UniversalCameraData>().imageScalingMode;
  301. internal ref ImageUpscalingFilter upscalingFilter => ref frameData.Get<UniversalCameraData>().upscalingFilter;
  302. internal ref bool fsrOverrideSharpness => ref frameData.Get<UniversalCameraData>().fsrOverrideSharpness;
  303. internal ref float fsrSharpness => ref frameData.Get<UniversalCameraData>().fsrSharpness;
  304. internal ref HDRColorBufferPrecision hdrColorBufferPrecision => ref frameData.Get<UniversalCameraData>().hdrColorBufferPrecision;
  305. /// <summary>
  306. /// True if this camera should clear depth buffer. This setting only applies to cameras of type <c>CameraRenderType.Overlay</c>
  307. /// <seealso cref="CameraRenderType"/>
  308. /// </summary>
  309. public ref bool clearDepth => ref frameData.Get<UniversalCameraData>().clearDepth;
  310. /// <summary>
  311. /// The camera type.
  312. /// <seealso cref="UnityEngine.CameraType"/>
  313. /// </summary>
  314. public ref CameraType cameraType => ref frameData.Get<UniversalCameraData>().cameraType;
  315. /// <summary>
  316. /// True if this camera is drawing to a viewport that maps to the entire screen.
  317. /// </summary>
  318. public ref bool isDefaultViewport => ref frameData.Get<UniversalCameraData>().isDefaultViewport;
  319. /// <summary>
  320. /// True if this camera should render to high dynamic range color targets.
  321. /// </summary>
  322. public ref bool isHdrEnabled => ref frameData.Get<UniversalCameraData>().isHdrEnabled;
  323. /// <summary>
  324. /// True if this camera allow color conversion and encoding for high dynamic range displays.
  325. /// </summary>
  326. public ref bool allowHDROutput => ref frameData.Get<UniversalCameraData>().allowHDROutput;
  327. /// <summary>
  328. /// True if this camera writes the alpha channel. Requires to color target to have an alpha channel.
  329. /// </summary>
  330. public ref bool isAlphaOutputEnabled => ref frameData.Get<UniversalCameraData>().isAlphaOutputEnabled;
  331. /// <summary>
  332. /// True if this camera requires to write _CameraDepthTexture.
  333. /// </summary>
  334. public ref bool requiresDepthTexture => ref frameData.Get<UniversalCameraData>().requiresDepthTexture;
  335. /// <summary>
  336. /// True if this camera requires to copy camera color texture to _CameraOpaqueTexture.
  337. /// </summary>
  338. public ref bool requiresOpaqueTexture => ref frameData.Get<UniversalCameraData>().requiresOpaqueTexture;
  339. /// <summary>
  340. /// Returns true if post processing passes require depth texture.
  341. /// </summary>
  342. public ref bool postProcessingRequiresDepthTexture => ref frameData.Get<UniversalCameraData>().postProcessingRequiresDepthTexture;
  343. /// <summary>
  344. /// Returns true if XR rendering is enabled.
  345. /// </summary>
  346. public ref bool xrRendering => ref frameData.Get<UniversalCameraData>().xrRendering;
  347. internal bool requireSrgbConversion => frameData.Get<UniversalCameraData>().requireSrgbConversion;
  348. /// <summary>
  349. /// True if the camera rendering is for the scene window in the editor.
  350. /// </summary>
  351. public bool isSceneViewCamera => frameData.Get<UniversalCameraData>().isSceneViewCamera;
  352. /// <summary>
  353. /// True if the camera rendering is for the preview window in the editor.
  354. /// </summary>
  355. public bool isPreviewCamera => frameData.Get<UniversalCameraData>().isPreviewCamera;
  356. internal bool isRenderPassSupportedCamera => frameData.Get<UniversalCameraData>().isRenderPassSupportedCamera;
  357. internal bool resolveToScreen => frameData.Get<UniversalCameraData>().resolveToScreen;
  358. /// <summary>
  359. /// True if the Camera should output to an HDR display.
  360. /// </summary>
  361. public bool isHDROutputActive => frameData.Get<UniversalCameraData>().isHDROutputActive;
  362. /// <summary>
  363. /// HDR Display information about the current display this camera is rendering to.
  364. /// </summary>
  365. public HDROutputUtils.HDRDisplayInformation hdrDisplayInformation => frameData.Get<UniversalCameraData>().hdrDisplayInformation;
  366. /// <summary>
  367. /// HDR Display Color Gamut
  368. /// </summary>
  369. public ColorGamut hdrDisplayColorGamut => frameData.Get<UniversalCameraData>().hdrDisplayColorGamut;
  370. /// <summary>
  371. /// True if the Camera should render overlay UI.
  372. /// </summary>
  373. public bool rendersOverlayUI => frameData.Get<UniversalCameraData>().rendersOverlayUI;
  374. /// <summary>
  375. /// True is the handle has its content flipped on the y axis.
  376. /// This happens only with certain rendering APIs.
  377. /// On those platforms, any handle will have its content flipped unless rendering to a backbuffer, however,
  378. /// the scene view will always be flipped.
  379. /// When transitioning from a flipped space to a non-flipped space - or vice-versa - the content must be flipped
  380. /// in the shader:
  381. /// shouldPerformYFlip = IsHandleYFlipped(source) != IsHandleYFlipped(target)
  382. /// </summary>
  383. /// <param name="handle">Handle to check the flipped status on.</param>
  384. /// <returns>True is the content is flipped in y.</returns>
  385. public bool IsHandleYFlipped(RTHandle handle)
  386. {
  387. return frameData.Get<UniversalCameraData>().IsHandleYFlipped(handle);
  388. }
  389. /// <summary>
  390. /// True if the camera device projection matrix is flipped. This happens when the pipeline is rendering
  391. /// to a render texture in non OpenGL platforms. If you are doing a custom Blit pass to copy camera textures
  392. /// (_CameraColorTexture, _CameraDepthAttachment) you need to check this flag to know if you should flip the
  393. /// matrix when rendering with for cmd.Draw* and reading from camera textures.
  394. /// </summary>
  395. /// <returns> True if the camera device projection matrix is flipped. </returns>
  396. [Obsolete(DeprecationMessage.CompatibilityScriptingAPIObsolete, false)]
  397. public bool IsCameraProjectionMatrixFlipped()
  398. {
  399. return frameData.Get<UniversalCameraData>().IsCameraProjectionMatrixFlipped();
  400. }
  401. /// <summary>
  402. /// True if the render target's projection matrix is flipped. This happens when the pipeline is rendering
  403. /// to a render texture in non OpenGL platforms. If you are doing a custom Blit pass to copy camera textures
  404. /// (_CameraColorTexture, _CameraDepthAttachment) you need to check this flag to know if you should flip the
  405. /// matrix when rendering with for cmd.Draw* and reading from camera textures.
  406. /// </summary>
  407. /// <param name="color">Color render target to check whether the matrix is flipped.</param>
  408. /// <param name="depth">Depth render target which is used if color is null. By default <c>depth</c> is set to null.</param>
  409. /// <returns> True if the render target's projection matrix is flipped. </returns>
  410. public bool IsRenderTargetProjectionMatrixFlipped(RTHandle color, RTHandle depth = null)
  411. {
  412. return frameData.Get<UniversalCameraData>().IsRenderTargetProjectionMatrixFlipped(color, depth);
  413. }
  414. internal bool IsTemporalAAEnabled()
  415. {
  416. return frameData.Get<UniversalCameraData>().IsTemporalAAEnabled();
  417. }
  418. /// <summary>
  419. /// The sorting criteria used when drawing opaque objects by the internal URP render passes.
  420. /// When a GPU supports hidden surface removal, URP will rely on that information to avoid sorting opaque objects front to back and
  421. /// benefit for more optimal static batching.
  422. /// </summary>
  423. /// <seealso cref="SortingCriteria"/>
  424. public ref SortingCriteria defaultOpaqueSortFlags => ref frameData.Get<UniversalCameraData>().defaultOpaqueSortFlags;
  425. /// <summary>
  426. /// XRPass holds the render target information and a list of XRView.
  427. /// XRView contains the parameters required to render (projection and view matrices, viewport, etc)
  428. /// </summary>
  429. public XRPass xr
  430. {
  431. get => frameData.Get<UniversalCameraData>().xr;
  432. internal set => frameData.Get<UniversalCameraData>().xr = value;
  433. }
  434. internal XRPassUniversal xrUniversal => frameData.Get<UniversalCameraData>().xrUniversal;
  435. /// <summary>
  436. /// Maximum shadow distance visible to the camera. When set to zero shadows will be disable for that camera.
  437. /// </summary>
  438. public ref float maxShadowDistance => ref frameData.Get<UniversalCameraData>().maxShadowDistance;
  439. /// <summary>
  440. /// True if post-processing is enabled for this camera.
  441. /// </summary>
  442. public ref bool postProcessEnabled => ref frameData.Get<UniversalCameraData>().postProcessEnabled;
  443. /// <summary>
  444. /// Provides set actions to the renderer to be triggered at the end of the render loop for camera capture.
  445. /// </summary>
  446. public ref IEnumerator<Action<RenderTargetIdentifier, CommandBuffer>> captureActions => ref frameData.Get<UniversalCameraData>().captureActions;
  447. /// <summary>
  448. /// The camera volume layer mask.
  449. /// </summary>
  450. public ref LayerMask volumeLayerMask => ref frameData.Get<UniversalCameraData>().volumeLayerMask;
  451. /// <summary>
  452. /// The camera volume trigger.
  453. /// </summary>
  454. public ref Transform volumeTrigger => ref frameData.Get<UniversalCameraData>().volumeTrigger;
  455. /// <summary>
  456. /// If set to true, the integrated post-processing stack will replace any NaNs generated by render passes prior to post-processing with black/zero.
  457. /// Enabling this option will cause a noticeable performance impact. It should be used while in development mode to identify NaN issues.
  458. /// </summary>
  459. public ref bool isStopNaNEnabled => ref frameData.Get<UniversalCameraData>().isStopNaNEnabled;
  460. /// <summary>
  461. /// If set to true a final post-processing pass will be applied to apply dithering.
  462. /// This can be combined with post-processing antialiasing.
  463. /// <seealso cref="antialiasing"/>
  464. /// </summary>
  465. public ref bool isDitheringEnabled => ref frameData.Get<UniversalCameraData>().isDitheringEnabled;
  466. /// <summary>
  467. /// Controls the anti-alising mode used by the integrated post-processing stack.
  468. /// When any other value other than <c>AntialiasingMode.None</c> is chosen, a final post-processing pass will be applied to apply anti-aliasing.
  469. /// This pass can be combined with dithering.
  470. /// <see cref="AntialiasingMode"/>
  471. /// <seealso cref="isDitheringEnabled"/>
  472. /// </summary>
  473. public ref AntialiasingMode antialiasing => ref frameData.Get<UniversalCameraData>().antialiasing;
  474. /// <summary>
  475. /// Controls the anti-alising quality of the anti-aliasing mode.
  476. /// <see cref="antialiasingQuality"/>
  477. /// <seealso cref="AntialiasingMode"/>
  478. /// </summary>
  479. public ref AntialiasingQuality antialiasingQuality => ref frameData.Get<UniversalCameraData>().antialiasingQuality;
  480. /// <summary>
  481. /// Returns the current renderer used by this camera.
  482. /// <see cref="ScriptableRenderer"/>
  483. /// </summary>
  484. public ref ScriptableRenderer renderer => ref frameData.Get<UniversalCameraData>().renderer;
  485. /// <summary>
  486. /// True if this camera is resolving rendering to the final camera render target.
  487. /// When rendering a stack of cameras only the last camera in the stack will resolve to camera target.
  488. /// </summary>
  489. public ref bool resolveFinalTarget => ref frameData.Get<UniversalCameraData>().resolveFinalTarget;
  490. /// <summary>
  491. /// Camera position in world space.
  492. /// </summary>
  493. public ref Vector3 worldSpaceCameraPos => ref frameData.Get<UniversalCameraData>().worldSpaceCameraPos;
  494. /// <summary>
  495. /// Final background color in the active color space.
  496. /// </summary>
  497. public ref Color backgroundColor => ref frameData.Get<UniversalCameraData>().backgroundColor;
  498. /// <summary>
  499. /// Persistent TAA data, primarily for the accumulation texture.
  500. /// </summary>
  501. internal ref TaaHistory taaHistory => ref frameData.Get<UniversalCameraData>().taaHistory;
  502. // TAA settings.
  503. internal ref TemporalAA.Settings taaSettings => ref frameData.Get<UniversalCameraData>().taaSettings;
  504. // Post-process history reset has been triggered for this camera.
  505. internal bool resetHistory => frameData.Get<UniversalCameraData>().resetHistory;
  506. /// <summary>
  507. /// Camera at the top of the overlay camera stack
  508. /// </summary>
  509. public ref Camera baseCamera => ref frameData.Get<UniversalCameraData>().baseCamera;
  510. }
  511. /// <summary>
  512. /// Container struct for various data used for shadows in URP.
  513. /// </summary>
  514. public struct ShadowData
  515. {
  516. ContextContainer frameData;
  517. internal ShadowData(ContextContainer frameData)
  518. {
  519. this.frameData = frameData;
  520. }
  521. internal UniversalShadowData universalShadowData => frameData.Get<UniversalShadowData>();
  522. /// <summary>
  523. /// True if main light shadows are enabled.
  524. /// </summary>
  525. public ref bool supportsMainLightShadows => ref frameData.Get<UniversalShadowData>().supportsMainLightShadows;
  526. /// <summary>
  527. /// True if additional lights shadows are enabled in the URP Asset
  528. /// </summary>
  529. internal ref bool mainLightShadowsEnabled => ref frameData.Get<UniversalShadowData>().mainLightShadowsEnabled;
  530. /// <summary>
  531. /// The width of the main light shadow map.
  532. /// </summary>
  533. public ref int mainLightShadowmapWidth => ref frameData.Get<UniversalShadowData>().mainLightShadowmapWidth;
  534. /// <summary>
  535. /// The height of the main light shadow map.
  536. /// </summary>
  537. public ref int mainLightShadowmapHeight => ref frameData.Get<UniversalShadowData>().mainLightShadowmapHeight;
  538. /// <summary>
  539. /// The number of shadow cascades.
  540. /// </summary>
  541. public ref int mainLightShadowCascadesCount => ref frameData.Get<UniversalShadowData>().mainLightShadowCascadesCount;
  542. /// <summary>
  543. /// The split between cascades.
  544. /// </summary>
  545. public ref Vector3 mainLightShadowCascadesSplit => ref frameData.Get<UniversalShadowData>().mainLightShadowCascadesSplit;
  546. /// <summary>
  547. /// Main light last cascade shadow fade border.
  548. /// Value represents the width of shadow fade that ranges from 0 to 1.
  549. /// Where value 0 is used for no shadow fade.
  550. /// </summary>
  551. public ref float mainLightShadowCascadeBorder => ref frameData.Get<UniversalShadowData>().mainLightShadowCascadeBorder;
  552. /// <summary>
  553. /// True if additional lights shadows are enabled.
  554. /// </summary>
  555. public ref bool supportsAdditionalLightShadows => ref frameData.Get<UniversalShadowData>().supportsAdditionalLightShadows;
  556. /// <summary>
  557. /// True if additional lights shadows are enabled in the URP Asset
  558. /// </summary>
  559. internal ref bool additionalLightShadowsEnabled => ref frameData.Get<UniversalShadowData>().additionalLightShadowsEnabled;
  560. /// <summary>
  561. /// The width of the additional light shadow map.
  562. /// </summary>
  563. public ref int additionalLightsShadowmapWidth => ref frameData.Get<UniversalShadowData>().additionalLightsShadowmapWidth;
  564. /// <summary>
  565. /// The height of the additional light shadow map.
  566. /// </summary>
  567. public ref int additionalLightsShadowmapHeight => ref frameData.Get<UniversalShadowData>().additionalLightsShadowmapHeight;
  568. /// <summary>
  569. /// True if soft shadows are enabled.
  570. /// </summary>
  571. public ref bool supportsSoftShadows => ref frameData.Get<UniversalShadowData>().supportsSoftShadows;
  572. /// <summary>
  573. /// The number of bits used.
  574. /// </summary>
  575. public ref int shadowmapDepthBufferBits => ref frameData.Get<UniversalShadowData>().shadowmapDepthBufferBits;
  576. /// <summary>
  577. /// A list of shadow bias.
  578. /// </summary>
  579. public ref List<Vector4> bias => ref frameData.Get<UniversalShadowData>().bias;
  580. /// <summary>
  581. /// A list of resolution for the shadow maps.
  582. /// </summary>
  583. public ref List<int> resolution => ref frameData.Get<UniversalShadowData>().resolution;
  584. internal ref bool isKeywordAdditionalLightShadowsEnabled => ref frameData.Get<UniversalShadowData>().isKeywordAdditionalLightShadowsEnabled;
  585. internal ref bool isKeywordSoftShadowsEnabled => ref frameData.Get<UniversalShadowData>().isKeywordSoftShadowsEnabled;
  586. internal ref int mainLightShadowResolution => ref frameData.Get<UniversalShadowData>().mainLightShadowResolution;
  587. internal ref int mainLightRenderTargetWidth => ref frameData.Get<UniversalShadowData>().mainLightRenderTargetWidth;
  588. internal ref int mainLightRenderTargetHeight => ref frameData.Get<UniversalShadowData>().mainLightRenderTargetHeight;
  589. internal ref NativeArray<URPLightShadowCullingInfos> visibleLightsShadowCullingInfos => ref frameData.Get<UniversalShadowData>().visibleLightsShadowCullingInfos;
  590. internal ref AdditionalLightsShadowAtlasLayout shadowAtlasLayout => ref frameData.Get<UniversalShadowData>().shadowAtlasLayout;
  591. }
  592. /// <summary>
  593. /// Precomputed tile data.
  594. /// Tile left, right, bottom and top plane equations in view space.
  595. /// Normals are pointing out.
  596. /// </summary>
  597. public struct PreTile
  598. {
  599. /// <summary>
  600. /// The left plane.
  601. /// </summary>
  602. public Unity.Mathematics.float4 planeLeft;
  603. /// <summary>
  604. /// The right plane.
  605. /// </summary>
  606. public Unity.Mathematics.float4 planeRight;
  607. /// <summary>
  608. /// The bottom plane.
  609. /// </summary>
  610. public Unity.Mathematics.float4 planeBottom;
  611. /// <summary>
  612. /// The top plane.
  613. /// </summary>
  614. public Unity.Mathematics.float4 planeTop;
  615. }
  616. /// <summary>
  617. /// The tile data passed to the deferred shaders.
  618. /// </summary>
  619. public struct TileData
  620. {
  621. /// <summary>
  622. /// The tile ID.
  623. /// </summary>
  624. public uint tileID; // 2x 16 bits
  625. /// <summary>
  626. /// The list bit mask.
  627. /// </summary>
  628. public uint listBitMask; // 32 bits
  629. /// <summary>
  630. /// The relative light offset.
  631. /// </summary>
  632. public uint relLightOffset; // 16 bits is enough
  633. /// <summary>
  634. /// Unused variable.
  635. /// </summary>
  636. public uint unused;
  637. }
  638. /// <summary>
  639. /// The point/spot light data passed to the deferred shaders.
  640. /// </summary>
  641. public struct PunctualLightData
  642. {
  643. /// <summary>
  644. /// The world position.
  645. /// </summary>
  646. public Vector3 wsPos;
  647. /// <summary>
  648. /// The radius of the light.
  649. /// </summary>
  650. public float radius; // TODO remove? included in attenuation
  651. /// <summary>
  652. /// The color of the light.
  653. /// </summary>
  654. public Vector4 color;
  655. /// <summary>
  656. /// The attenuation of the light.
  657. /// </summary>
  658. public Vector4 attenuation; // .xy are used by DistanceAttenuation - .zw are used by AngleAttenuation (for SpotLights)
  659. /// <summary>
  660. /// The direction for spot lights.
  661. /// </summary>
  662. public Vector3 spotDirection; // for spotLights
  663. /// <summary>
  664. /// The flags used.
  665. /// </summary>
  666. public int flags;
  667. /// <summary>
  668. /// The occlusion probe info.
  669. /// </summary>
  670. public Vector4 occlusionProbeInfo;
  671. /// <summary>
  672. /// The layer mask used.
  673. /// </summary>
  674. public uint layerMask;
  675. }
  676. internal static class ShaderPropertyId
  677. {
  678. public static readonly int glossyEnvironmentColor = Shader.PropertyToID("_GlossyEnvironmentColor");
  679. public static readonly int subtractiveShadowColor = Shader.PropertyToID("_SubtractiveShadowColor");
  680. public static readonly int glossyEnvironmentCubeMap = Shader.PropertyToID("_GlossyEnvironmentCubeMap");
  681. public static readonly int glossyEnvironmentCubeMapHDR = Shader.PropertyToID("_GlossyEnvironmentCubeMap_HDR");
  682. public static readonly int ambientSkyColor = Shader.PropertyToID("unity_AmbientSky");
  683. public static readonly int ambientEquatorColor = Shader.PropertyToID("unity_AmbientEquator");
  684. public static readonly int ambientGroundColor = Shader.PropertyToID("unity_AmbientGround");
  685. public static readonly int time = Shader.PropertyToID("_Time");
  686. public static readonly int sinTime = Shader.PropertyToID("_SinTime");
  687. public static readonly int cosTime = Shader.PropertyToID("_CosTime");
  688. public static readonly int deltaTime = Shader.PropertyToID("unity_DeltaTime");
  689. public static readonly int timeParameters = Shader.PropertyToID("_TimeParameters");
  690. public static readonly int lastTimeParameters = Shader.PropertyToID("_LastTimeParameters");
  691. public static readonly int scaledScreenParams = Shader.PropertyToID("_ScaledScreenParams");
  692. public static readonly int worldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos");
  693. public static readonly int screenParams = Shader.PropertyToID("_ScreenParams");
  694. public static readonly int alphaToMaskAvailable = Shader.PropertyToID("_AlphaToMaskAvailable");
  695. public static readonly int projectionParams = Shader.PropertyToID("_ProjectionParams");
  696. public static readonly int zBufferParams = Shader.PropertyToID("_ZBufferParams");
  697. public static readonly int orthoParams = Shader.PropertyToID("unity_OrthoParams");
  698. public static readonly int globalMipBias = Shader.PropertyToID("_GlobalMipBias");
  699. public static readonly int screenSize = Shader.PropertyToID("_ScreenSize");
  700. public static readonly int screenCoordScaleBias = Shader.PropertyToID("_ScreenCoordScaleBias");
  701. public static readonly int screenSizeOverride = Shader.PropertyToID("_ScreenSizeOverride");
  702. public static readonly int viewMatrix = Shader.PropertyToID("unity_MatrixV");
  703. public static readonly int projectionMatrix = Shader.PropertyToID("glstate_matrix_projection");
  704. public static readonly int viewAndProjectionMatrix = Shader.PropertyToID("unity_MatrixVP");
  705. public static readonly int inverseViewMatrix = Shader.PropertyToID("unity_MatrixInvV");
  706. public static readonly int inverseProjectionMatrix = Shader.PropertyToID("unity_MatrixInvP");
  707. public static readonly int inverseViewAndProjectionMatrix = Shader.PropertyToID("unity_MatrixInvVP");
  708. public static readonly int cameraProjectionMatrix = Shader.PropertyToID("unity_CameraProjection");
  709. public static readonly int inverseCameraProjectionMatrix = Shader.PropertyToID("unity_CameraInvProjection");
  710. public static readonly int worldToCameraMatrix = Shader.PropertyToID("unity_WorldToCamera");
  711. public static readonly int cameraToWorldMatrix = Shader.PropertyToID("unity_CameraToWorld");
  712. public static readonly int shadowBias = Shader.PropertyToID("_ShadowBias");
  713. public static readonly int lightDirection = Shader.PropertyToID("_LightDirection");
  714. public static readonly int lightPosition = Shader.PropertyToID("_LightPosition");
  715. public static readonly int cameraWorldClipPlanes = Shader.PropertyToID("unity_CameraWorldClipPlanes");
  716. public static readonly int billboardNormal = Shader.PropertyToID("unity_BillboardNormal");
  717. public static readonly int billboardTangent = Shader.PropertyToID("unity_BillboardTangent");
  718. public static readonly int billboardCameraParams = Shader.PropertyToID("unity_BillboardCameraParams");
  719. public static readonly int previousViewProjectionNoJitter = Shader.PropertyToID("_PrevViewProjMatrix");
  720. public static readonly int viewProjectionNoJitter = Shader.PropertyToID("_NonJitteredViewProjMatrix");
  721. #if ENABLE_VR && ENABLE_XR_MODULE
  722. public static readonly int previousViewProjectionNoJitterStereo = Shader.PropertyToID("_PrevViewProjMatrixStereo");
  723. public static readonly int viewProjectionNoJitterStereo = Shader.PropertyToID("_NonJitteredViewProjMatrixStereo");
  724. #endif
  725. public static readonly int blitTexture = Shader.PropertyToID("_BlitTexture");
  726. public static readonly int blitScaleBias = Shader.PropertyToID("_BlitScaleBias");
  727. public static readonly int sourceTex = Shader.PropertyToID("_SourceTex");
  728. public static readonly int scaleBias = Shader.PropertyToID("_ScaleBias");
  729. public static readonly int scaleBiasRt = Shader.PropertyToID("_ScaleBiasRt");
  730. // This uniform is specific to the RTHandle system
  731. public static readonly int rtHandleScale = Shader.PropertyToID("_RTHandleScale");
  732. // Required for 2D Unlit Shadergraph master node as it doesn't currently support hidden properties.
  733. public static readonly int rendererColor = Shader.PropertyToID("_RendererColor");
  734. public static readonly int ditheringTexture = Shader.PropertyToID("_DitheringTexture");
  735. public static readonly int ditheringTextureInvSize = Shader.PropertyToID("_DitheringTextureInvSize");
  736. public static readonly int renderingLayerMaxInt = Shader.PropertyToID("_RenderingLayerMaxInt");
  737. public static readonly int renderingLayerRcpMaxInt = Shader.PropertyToID("_RenderingLayerRcpMaxInt");
  738. public static readonly int overlayUITexture = Shader.PropertyToID("_OverlayUITexture");
  739. public static readonly int hdrOutputLuminanceParams = Shader.PropertyToID("_HDROutputLuminanceParams");
  740. public static readonly int hdrOutputGradingParams = Shader.PropertyToID("_HDROutputGradingParams");
  741. }
  742. /// <summary>
  743. /// Settings used for Post Processing.
  744. /// </summary>
  745. public struct PostProcessingData
  746. {
  747. ContextContainer frameData;
  748. internal PostProcessingData(ContextContainer frameData)
  749. {
  750. this.frameData = frameData;
  751. }
  752. internal UniversalPostProcessingData universalPostProcessingData => frameData.Get<UniversalPostProcessingData>();
  753. /// <summary>
  754. /// The <c>ColorGradingMode</c> to use.
  755. /// </summary>
  756. /// <seealso cref="ColorGradingMode"/>
  757. public ref ColorGradingMode gradingMode => ref frameData.Get<UniversalPostProcessingData>().gradingMode;
  758. /// <summary>
  759. /// The size of the Look Up Table (LUT)
  760. /// </summary>
  761. public ref int lutSize => ref frameData.Get<UniversalPostProcessingData>().lutSize;
  762. /// <summary>
  763. /// True if fast approximation functions are used when converting between the sRGB and Linear color spaces, false otherwise.
  764. /// </summary>
  765. public ref bool useFastSRGBLinearConversion => ref frameData.Get<UniversalPostProcessingData>().useFastSRGBLinearConversion;
  766. /// <summary>
  767. /// Returns true if Screen Space Lens Flare are supported by this asset, false otherwise.
  768. /// </summary>
  769. public ref bool supportScreenSpaceLensFlare => ref frameData.Get<UniversalPostProcessingData>().supportScreenSpaceLensFlare;
  770. /// <summary>
  771. /// Returns true if Data Driven Lens Flare are supported by this asset, false otherwise.
  772. /// </summary>
  773. public ref bool supportDataDrivenLensFlare => ref frameData.Get<UniversalPostProcessingData>().supportDataDrivenLensFlare;
  774. }
  775. internal static class ShaderGlobalKeywords
  776. {
  777. public static GlobalKeyword MainLightShadows;
  778. public static GlobalKeyword MainLightShadowCascades;
  779. public static GlobalKeyword MainLightShadowScreen;
  780. public static GlobalKeyword CastingPunctualLightShadow;
  781. public static GlobalKeyword AdditionalLightsVertex;
  782. public static GlobalKeyword AdditionalLightsPixel;
  783. public static GlobalKeyword ForwardPlus;
  784. public static GlobalKeyword AdditionalLightShadows;
  785. public static GlobalKeyword ReflectionProbeBoxProjection;
  786. public static GlobalKeyword ReflectionProbeBlending;
  787. public static GlobalKeyword SoftShadows;
  788. public static GlobalKeyword SoftShadowsLow;
  789. public static GlobalKeyword SoftShadowsMedium;
  790. public static GlobalKeyword SoftShadowsHigh;
  791. public static GlobalKeyword MixedLightingSubtractive; // Backward compatibility
  792. public static GlobalKeyword LightmapShadowMixing;
  793. public static GlobalKeyword ShadowsShadowMask;
  794. public static GlobalKeyword LightLayers;
  795. public static GlobalKeyword RenderPassEnabled;
  796. public static GlobalKeyword BillboardFaceCameraPos;
  797. public static GlobalKeyword LightCookies;
  798. public static GlobalKeyword DepthNoMsaa;
  799. public static GlobalKeyword DepthMsaa2;
  800. public static GlobalKeyword DepthMsaa4;
  801. public static GlobalKeyword DepthMsaa8;
  802. public static GlobalKeyword DBufferMRT1;
  803. public static GlobalKeyword DBufferMRT2;
  804. public static GlobalKeyword DBufferMRT3;
  805. public static GlobalKeyword DecalNormalBlendLow;
  806. public static GlobalKeyword DecalNormalBlendMedium;
  807. public static GlobalKeyword DecalNormalBlendHigh;
  808. public static GlobalKeyword DecalLayers;
  809. public static GlobalKeyword WriteRenderingLayers;
  810. public static GlobalKeyword ScreenSpaceOcclusion;
  811. public static GlobalKeyword _SPOT;
  812. public static GlobalKeyword _DIRECTIONAL;
  813. public static GlobalKeyword _POINT;
  814. public static GlobalKeyword _DEFERRED_STENCIL;
  815. public static GlobalKeyword _DEFERRED_FIRST_LIGHT;
  816. public static GlobalKeyword _DEFERRED_MAIN_LIGHT;
  817. public static GlobalKeyword _GBUFFER_NORMALS_OCT;
  818. public static GlobalKeyword _DEFERRED_MIXED_LIGHTING;
  819. public static GlobalKeyword LIGHTMAP_ON;
  820. public static GlobalKeyword DYNAMICLIGHTMAP_ON;
  821. public static GlobalKeyword _ALPHATEST_ON;
  822. public static GlobalKeyword DIRLIGHTMAP_COMBINED;
  823. public static GlobalKeyword _DETAIL_MULX2;
  824. public static GlobalKeyword _DETAIL_SCALED;
  825. public static GlobalKeyword _CLEARCOAT;
  826. public static GlobalKeyword _CLEARCOATMAP;
  827. public static GlobalKeyword DEBUG_DISPLAY;
  828. public static GlobalKeyword LOD_FADE_CROSSFADE;
  829. public static GlobalKeyword USE_UNITY_CROSSFADE;
  830. public static GlobalKeyword _EMISSION;
  831. public static GlobalKeyword _RECEIVE_SHADOWS_OFF;
  832. public static GlobalKeyword _SURFACE_TYPE_TRANSPARENT;
  833. public static GlobalKeyword _ALPHAPREMULTIPLY_ON;
  834. public static GlobalKeyword _ALPHAMODULATE_ON;
  835. public static GlobalKeyword _NORMALMAP;
  836. public static GlobalKeyword _ADD_PRECOMPUTED_VELOCITY;
  837. public static GlobalKeyword EDITOR_VISUALIZATION;
  838. public static GlobalKeyword FoveatedRenderingNonUniformRaster;
  839. public static GlobalKeyword DisableTexture2DXArray;
  840. public static GlobalKeyword BlitSingleSlice;
  841. public static GlobalKeyword XROcclusionMeshCombined;
  842. public static GlobalKeyword SCREEN_COORD_OVERRIDE;
  843. public static GlobalKeyword DOWNSAMPLING_SIZE_2;
  844. public static GlobalKeyword DOWNSAMPLING_SIZE_4;
  845. public static GlobalKeyword DOWNSAMPLING_SIZE_8;
  846. public static GlobalKeyword DOWNSAMPLING_SIZE_16;
  847. public static GlobalKeyword EVALUATE_SH_MIXED;
  848. public static GlobalKeyword EVALUATE_SH_VERTEX;
  849. public static GlobalKeyword ProbeVolumeL1;
  850. public static GlobalKeyword ProbeVolumeL2;
  851. public static GlobalKeyword _OUTPUT_DEPTH;
  852. public static GlobalKeyword LinearToSRGBConversion;
  853. public static GlobalKeyword _ENABLE_ALPHA_OUTPUT;
  854. // TODO: Move following keywords to Local keywords?
  855. // https://docs.unity3d.com/ScriptReference/Rendering.LocalKeyword.html
  856. //public static GlobalKeyword TonemapACES;
  857. //public static GlobalKeyword TonemapNeutral;
  858. //public static GlobalKeyword UseFastSRGBLinearConversion;
  859. //public static GlobalKeyword SmaaLow;
  860. //public static GlobalKeyword SmaaMedium;
  861. //public static GlobalKeyword SmaaHigh;
  862. //public static GlobalKeyword PaniniGeneric;
  863. //public static GlobalKeyword PaniniUnitDistance;
  864. //public static GlobalKeyword HighQualitySampling;
  865. //public static GlobalKeyword BloomLQ;
  866. //public static GlobalKeyword BloomHQ;
  867. //public static GlobalKeyword BloomLQDirt;
  868. //public static GlobalKeyword BloomHQDirt;
  869. //public static GlobalKeyword UseRGBM;
  870. //public static GlobalKeyword Distortion;
  871. //public static GlobalKeyword ChromaticAberration;
  872. //public static GlobalKeyword HDRGrading;
  873. //public static GlobalKeyword FilmGrain;
  874. //public static GlobalKeyword Fxaa;
  875. //public static GlobalKeyword Dithering;
  876. //public static GlobalKeyword Rcas;
  877. //public static GlobalKeyword EasuRcasAndHDRInput;
  878. //public static GlobalKeyword Gamma20;
  879. //public static GlobalKeyword Gamma20AndHDRInput;
  880. //public static GlobalKeyword PointSampling;
  881. public static void InitializeShaderGlobalKeywords()
  882. {
  883. // Init all keywords upfront
  884. ShaderGlobalKeywords.MainLightShadows = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadows);
  885. ShaderGlobalKeywords.MainLightShadowCascades = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadowCascades);
  886. ShaderGlobalKeywords.MainLightShadowScreen = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadowScreen);
  887. ShaderGlobalKeywords.CastingPunctualLightShadow = GlobalKeyword.Create(ShaderKeywordStrings.CastingPunctualLightShadow);
  888. ShaderGlobalKeywords.AdditionalLightsVertex = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightsVertex);
  889. ShaderGlobalKeywords.AdditionalLightsPixel = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightsPixel);
  890. ShaderGlobalKeywords.ForwardPlus = GlobalKeyword.Create(ShaderKeywordStrings.ForwardPlus);
  891. ShaderGlobalKeywords.AdditionalLightShadows = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightShadows);
  892. ShaderGlobalKeywords.ReflectionProbeBoxProjection = GlobalKeyword.Create(ShaderKeywordStrings.ReflectionProbeBoxProjection);
  893. ShaderGlobalKeywords.ReflectionProbeBlending = GlobalKeyword.Create(ShaderKeywordStrings.ReflectionProbeBlending);
  894. ShaderGlobalKeywords.SoftShadows = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadows);
  895. ShaderGlobalKeywords.SoftShadowsLow = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsLow);
  896. ShaderGlobalKeywords.SoftShadowsMedium = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsMedium);
  897. ShaderGlobalKeywords.MixedLightingSubtractive = GlobalKeyword.Create(ShaderKeywordStrings.MixedLightingSubtractive);
  898. ShaderGlobalKeywords.LightmapShadowMixing = GlobalKeyword.Create(ShaderKeywordStrings.LightmapShadowMixing);
  899. ShaderGlobalKeywords.ShadowsShadowMask = GlobalKeyword.Create(ShaderKeywordStrings.ShadowsShadowMask);
  900. ShaderGlobalKeywords.LightLayers = GlobalKeyword.Create(ShaderKeywordStrings.LightLayers);
  901. ShaderGlobalKeywords.RenderPassEnabled = GlobalKeyword.Create(ShaderKeywordStrings.RenderPassEnabled);
  902. ShaderGlobalKeywords.BillboardFaceCameraPos = GlobalKeyword.Create(ShaderKeywordStrings.BillboardFaceCameraPos);
  903. ShaderGlobalKeywords.LightCookies = GlobalKeyword.Create(ShaderKeywordStrings.LightCookies);
  904. ShaderGlobalKeywords.DepthNoMsaa = GlobalKeyword.Create(ShaderKeywordStrings.DepthNoMsaa);
  905. ShaderGlobalKeywords.DepthMsaa2 = GlobalKeyword.Create(ShaderKeywordStrings.DepthMsaa2);
  906. ShaderGlobalKeywords.DepthMsaa4 = GlobalKeyword.Create(ShaderKeywordStrings.DepthMsaa4);
  907. ShaderGlobalKeywords.DepthMsaa8 = GlobalKeyword.Create(ShaderKeywordStrings.DepthMsaa8);
  908. ShaderGlobalKeywords.DBufferMRT1 = GlobalKeyword.Create(ShaderKeywordStrings.DBufferMRT1);
  909. ShaderGlobalKeywords.DBufferMRT2 = GlobalKeyword.Create(ShaderKeywordStrings.DBufferMRT2);
  910. ShaderGlobalKeywords.DBufferMRT3 = GlobalKeyword.Create(ShaderKeywordStrings.DBufferMRT3);
  911. ShaderGlobalKeywords.DecalNormalBlendLow = GlobalKeyword.Create(ShaderKeywordStrings.DecalNormalBlendLow);
  912. ShaderGlobalKeywords.DecalNormalBlendMedium = GlobalKeyword.Create(ShaderKeywordStrings.DecalNormalBlendMedium);
  913. ShaderGlobalKeywords.DecalNormalBlendHigh = GlobalKeyword.Create(ShaderKeywordStrings.DecalNormalBlendHigh);
  914. ShaderGlobalKeywords.DecalLayers = GlobalKeyword.Create(ShaderKeywordStrings.DecalLayers);
  915. ShaderGlobalKeywords.WriteRenderingLayers = GlobalKeyword.Create(ShaderKeywordStrings.WriteRenderingLayers);
  916. ShaderGlobalKeywords.ScreenSpaceOcclusion = GlobalKeyword.Create(ShaderKeywordStrings.ScreenSpaceOcclusion);
  917. ShaderGlobalKeywords._SPOT = GlobalKeyword.Create(ShaderKeywordStrings._SPOT);
  918. ShaderGlobalKeywords._DIRECTIONAL = GlobalKeyword.Create(ShaderKeywordStrings._DIRECTIONAL);
  919. ShaderGlobalKeywords._POINT = GlobalKeyword.Create(ShaderKeywordStrings._POINT);
  920. ShaderGlobalKeywords._DEFERRED_STENCIL = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_STENCIL);
  921. ShaderGlobalKeywords._DEFERRED_FIRST_LIGHT = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_FIRST_LIGHT);
  922. ShaderGlobalKeywords._DEFERRED_MAIN_LIGHT = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_MAIN_LIGHT);
  923. ShaderGlobalKeywords._GBUFFER_NORMALS_OCT = GlobalKeyword.Create(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
  924. ShaderGlobalKeywords._DEFERRED_MIXED_LIGHTING = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_MIXED_LIGHTING);
  925. ShaderGlobalKeywords.LIGHTMAP_ON = GlobalKeyword.Create(ShaderKeywordStrings.LIGHTMAP_ON);
  926. ShaderGlobalKeywords.DYNAMICLIGHTMAP_ON = GlobalKeyword.Create(ShaderKeywordStrings.DYNAMICLIGHTMAP_ON);
  927. ShaderGlobalKeywords._ALPHATEST_ON = GlobalKeyword.Create(ShaderKeywordStrings._ALPHATEST_ON);
  928. ShaderGlobalKeywords.DIRLIGHTMAP_COMBINED = GlobalKeyword.Create(ShaderKeywordStrings.DIRLIGHTMAP_COMBINED);
  929. ShaderGlobalKeywords._DETAIL_MULX2 = GlobalKeyword.Create(ShaderKeywordStrings._DETAIL_MULX2);
  930. ShaderGlobalKeywords._DETAIL_SCALED = GlobalKeyword.Create(ShaderKeywordStrings._DETAIL_SCALED);
  931. ShaderGlobalKeywords._CLEARCOAT = GlobalKeyword.Create(ShaderKeywordStrings._CLEARCOAT);
  932. ShaderGlobalKeywords._CLEARCOATMAP = GlobalKeyword.Create(ShaderKeywordStrings._CLEARCOATMAP);
  933. ShaderGlobalKeywords.DEBUG_DISPLAY = GlobalKeyword.Create(ShaderKeywordStrings.DEBUG_DISPLAY);
  934. ShaderGlobalKeywords.LOD_FADE_CROSSFADE = GlobalKeyword.Create(ShaderKeywordStrings.LOD_FADE_CROSSFADE);
  935. ShaderGlobalKeywords.USE_UNITY_CROSSFADE = GlobalKeyword.Create(ShaderKeywordStrings.USE_UNITY_CROSSFADE);
  936. ShaderGlobalKeywords._EMISSION = GlobalKeyword.Create(ShaderKeywordStrings._EMISSION);
  937. ShaderGlobalKeywords._RECEIVE_SHADOWS_OFF = GlobalKeyword.Create(ShaderKeywordStrings._RECEIVE_SHADOWS_OFF);
  938. ShaderGlobalKeywords._SURFACE_TYPE_TRANSPARENT = GlobalKeyword.Create(ShaderKeywordStrings._SURFACE_TYPE_TRANSPARENT);
  939. ShaderGlobalKeywords._ALPHAPREMULTIPLY_ON = GlobalKeyword.Create(ShaderKeywordStrings._ALPHAPREMULTIPLY_ON);
  940. ShaderGlobalKeywords._ALPHAMODULATE_ON = GlobalKeyword.Create(ShaderKeywordStrings._ALPHAMODULATE_ON);
  941. ShaderGlobalKeywords._NORMALMAP = GlobalKeyword.Create(ShaderKeywordStrings._NORMALMAP);
  942. ShaderGlobalKeywords._ADD_PRECOMPUTED_VELOCITY = GlobalKeyword.Create(ShaderKeywordStrings._ADD_PRECOMPUTED_VELOCITY);
  943. ShaderGlobalKeywords.EDITOR_VISUALIZATION = GlobalKeyword.Create(ShaderKeywordStrings.EDITOR_VISUALIZATION);
  944. ShaderGlobalKeywords.FoveatedRenderingNonUniformRaster = GlobalKeyword.Create(ShaderKeywordStrings.FoveatedRenderingNonUniformRaster);
  945. ShaderGlobalKeywords.DisableTexture2DXArray = GlobalKeyword.Create(ShaderKeywordStrings.DisableTexture2DXArray);
  946. ShaderGlobalKeywords.BlitSingleSlice = GlobalKeyword.Create(ShaderKeywordStrings.BlitSingleSlice);
  947. ShaderGlobalKeywords.XROcclusionMeshCombined = GlobalKeyword.Create(ShaderKeywordStrings.XROcclusionMeshCombined);
  948. ShaderGlobalKeywords.SCREEN_COORD_OVERRIDE = GlobalKeyword.Create(ShaderKeywordStrings.SCREEN_COORD_OVERRIDE);
  949. ShaderGlobalKeywords.DOWNSAMPLING_SIZE_2 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_2);
  950. ShaderGlobalKeywords.DOWNSAMPLING_SIZE_4 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_4);
  951. ShaderGlobalKeywords.DOWNSAMPLING_SIZE_8 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_8);
  952. ShaderGlobalKeywords.DOWNSAMPLING_SIZE_16 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_16);
  953. ShaderGlobalKeywords.EVALUATE_SH_MIXED = GlobalKeyword.Create(ShaderKeywordStrings.EVALUATE_SH_MIXED);
  954. ShaderGlobalKeywords.EVALUATE_SH_VERTEX = GlobalKeyword.Create(ShaderKeywordStrings.EVALUATE_SH_VERTEX);
  955. ShaderGlobalKeywords.ProbeVolumeL1 = GlobalKeyword.Create(ShaderKeywordStrings.ProbeVolumeL1);
  956. ShaderGlobalKeywords.ProbeVolumeL2 = GlobalKeyword.Create(ShaderKeywordStrings.ProbeVolumeL2);
  957. ShaderGlobalKeywords._OUTPUT_DEPTH = GlobalKeyword.Create(ShaderKeywordStrings._OUTPUT_DEPTH);
  958. ShaderGlobalKeywords.LinearToSRGBConversion = GlobalKeyword.Create(ShaderKeywordStrings.LinearToSRGBConversion);
  959. ShaderGlobalKeywords._ENABLE_ALPHA_OUTPUT = GlobalKeyword.Create(ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT);
  960. }
  961. }
  962. /// <summary>
  963. /// Container class for keywords used in URP shaders.
  964. /// </summary>
  965. public static class ShaderKeywordStrings
  966. {
  967. /// <summary> Keyword used for shadows without cascades. </summary>
  968. public const string MainLightShadows = "_MAIN_LIGHT_SHADOWS";
  969. /// <summary> Keyword used for shadows with cascades. </summary>
  970. public const string MainLightShadowCascades = "_MAIN_LIGHT_SHADOWS_CASCADE";
  971. /// <summary> Keyword used for screen space shadows. </summary>
  972. public const string MainLightShadowScreen = "_MAIN_LIGHT_SHADOWS_SCREEN";
  973. /// <summary> Keyword used during shadow map generation to differentiate between directional and punctual light shadows, as they use different formulas to apply Normal Bias. </summary>
  974. public const string CastingPunctualLightShadow = "_CASTING_PUNCTUAL_LIGHT_SHADOW";
  975. /// <summary> Keyword used for per vertex additional lights. </summary>
  976. public const string AdditionalLightsVertex = "_ADDITIONAL_LIGHTS_VERTEX";
  977. /// <summary> Keyword used for per pixel additional lights. </summary>
  978. public const string AdditionalLightsPixel = "_ADDITIONAL_LIGHTS";
  979. /// <summary> Keyword used for Forward+. </summary>
  980. internal const string ForwardPlus = "_FORWARD_PLUS";
  981. /// <summary> Keyword used for shadows on additional lights. </summary>
  982. public const string AdditionalLightShadows = "_ADDITIONAL_LIGHT_SHADOWS";
  983. /// <summary> Keyword used for Box Projection with Reflection Probes. </summary>
  984. public const string ReflectionProbeBoxProjection = "_REFLECTION_PROBE_BOX_PROJECTION";
  985. /// <summary> Keyword used for Reflection probe blending. </summary>
  986. public const string ReflectionProbeBlending = "_REFLECTION_PROBE_BLENDING";
  987. /// <summary> Keyword used for soft shadows. </summary>
  988. public const string SoftShadows = "_SHADOWS_SOFT";
  989. /// <summary> Keyword used for low quality soft shadows. </summary>
  990. public const string SoftShadowsLow = "_SHADOWS_SOFT_LOW";
  991. /// <summary> Keyword used for medium quality soft shadows. </summary>
  992. public const string SoftShadowsMedium = "_SHADOWS_SOFT_MEDIUM";
  993. /// <summary> Keyword used for high quality soft shadows. </summary>
  994. public const string SoftShadowsHigh = "_SHADOWS_SOFT_HIGH";
  995. /// <summary> Keyword used for Mixed Lights in Subtractive lighting mode. </summary>
  996. public const string MixedLightingSubtractive = "_MIXED_LIGHTING_SUBTRACTIVE"; // Backward compatibility
  997. /// <summary> Keyword used for mixing lightmap shadows. </summary>
  998. public const string LightmapShadowMixing = "LIGHTMAP_SHADOW_MIXING";
  999. /// <summary> Keyword used for Shadowmask. </summary>
  1000. public const string ShadowsShadowMask = "SHADOWS_SHADOWMASK";
  1001. /// <summary> Keyword used for Light Layers. </summary>
  1002. public const string LightLayers = "_LIGHT_LAYERS";
  1003. /// <summary> Keyword used for RenderPass. </summary>
  1004. public const string RenderPassEnabled = "_RENDER_PASS_ENABLED";
  1005. /// <summary> Keyword used for Billboard cameras. </summary>
  1006. public const string BillboardFaceCameraPos = "BILLBOARD_FACE_CAMERA_POS";
  1007. /// <summary> Keyword used for Light Cookies. </summary>
  1008. public const string LightCookies = "_LIGHT_COOKIES";
  1009. /// <summary> Keyword used for no Multi Sampling Anti-Aliasing (MSAA). </summary>
  1010. public const string DepthNoMsaa = "_DEPTH_NO_MSAA";
  1011. /// <summary> Keyword used for Multi Sampling Anti-Aliasing (MSAA) with 2 per pixel sample count. </summary>
  1012. public const string DepthMsaa2 = "_DEPTH_MSAA_2";
  1013. /// <summary> Keyword used for Multi Sampling Anti-Aliasing (MSAA) with 4 per pixel sample count. </summary>
  1014. public const string DepthMsaa4 = "_DEPTH_MSAA_4";
  1015. /// <summary> Keyword used for Multi Sampling Anti-Aliasing (MSAA) with 8 per pixel sample count. </summary>
  1016. public const string DepthMsaa8 = "_DEPTH_MSAA_8";
  1017. /// <summary> Keyword used for Linear to SRGB conversions. </summary>
  1018. public const string LinearToSRGBConversion = "_LINEAR_TO_SRGB_CONVERSION";
  1019. /// <summary> Keyword used for less expensive Linear to SRGB conversions. </summary>
  1020. internal const string UseFastSRGBLinearConversion = "_USE_FAST_SRGB_LINEAR_CONVERSION";
  1021. /// <summary> Keyword used for first target in the DBuffer. </summary>
  1022. public const string DBufferMRT1 = "_DBUFFER_MRT1";
  1023. /// <summary> Keyword used for second target in the DBuffer. </summary>
  1024. public const string DBufferMRT2 = "_DBUFFER_MRT2";
  1025. /// <summary> Keyword used for third target in the DBuffer. </summary>
  1026. public const string DBufferMRT3 = "_DBUFFER_MRT3";
  1027. /// <summary> Keyword used for low quality normal reconstruction in Decals. </summary>
  1028. public const string DecalNormalBlendLow = "_DECAL_NORMAL_BLEND_LOW";
  1029. /// <summary> Keyword used for medium quality normal reconstruction in Decals. </summary>
  1030. public const string DecalNormalBlendMedium = "_DECAL_NORMAL_BLEND_MEDIUM";
  1031. /// <summary> Keyword used for high quality normal reconstruction in Decals. </summary>
  1032. public const string DecalNormalBlendHigh = "_DECAL_NORMAL_BLEND_HIGH";
  1033. /// <summary> Keyword used for Decal Layers. </summary>
  1034. public const string DecalLayers = "_DECAL_LAYERS";
  1035. /// <summary> Keyword used for writing Rendering Layers. </summary>
  1036. public const string WriteRenderingLayers = "_WRITE_RENDERING_LAYERS";
  1037. /// <summary> Keyword used for low quality Subpixel Morphological Anti-aliasing (SMAA). </summary>
  1038. public const string SmaaLow = "_SMAA_PRESET_LOW";
  1039. /// <summary> Keyword used for medium quality Subpixel Morphological Anti-aliasing (SMAA). </summary>
  1040. public const string SmaaMedium = "_SMAA_PRESET_MEDIUM";
  1041. /// <summary> Keyword used for high quality Subpixel Morphological Anti-aliasing (SMAA). </summary>
  1042. public const string SmaaHigh = "_SMAA_PRESET_HIGH";
  1043. /// <summary> Keyword used for generic Panini Projection. </summary>
  1044. public const string PaniniGeneric = "_GENERIC";
  1045. /// <summary> Keyword used for unit distance Panini Projection. </summary>
  1046. public const string PaniniUnitDistance = "_UNIT_DISTANCE";
  1047. /// <summary> Keyword used for low quality Bloom. </summary>
  1048. public const string BloomLQ = "_BLOOM_LQ";
  1049. /// <summary> Keyword used for high quality Bloom. </summary>
  1050. public const string BloomHQ = "_BLOOM_HQ";
  1051. /// <summary> Keyword used for low quality Bloom dirt. </summary>
  1052. public const string BloomLQDirt = "_BLOOM_LQ_DIRT";
  1053. /// <summary> Keyword used for high quality Bloom dirt. </summary>
  1054. public const string BloomHQDirt = "_BLOOM_HQ_DIRT";
  1055. /// <summary> Keyword used for RGBM format for Bloom. </summary>
  1056. public const string UseRGBM = "_USE_RGBM";
  1057. /// <summary> Keyword used for Distortion. </summary>
  1058. public const string Distortion = "_DISTORTION";
  1059. /// <summary> Keyword used for Chromatic Aberration. </summary>
  1060. public const string ChromaticAberration = "_CHROMATIC_ABERRATION";
  1061. /// <summary> Keyword used for HDR Color Grading. </summary>
  1062. public const string HDRGrading = "_HDR_GRADING";
  1063. /// <summary> Keyword used for ACES Tonemapping. </summary>
  1064. public const string TonemapACES = "_TONEMAP_ACES";
  1065. /// <summary> Keyword used for Neutral Tonemapping. </summary>
  1066. public const string TonemapNeutral = "_TONEMAP_NEUTRAL";
  1067. /// <summary> Keyword used for Film Grain. </summary>
  1068. public const string FilmGrain = "_FILM_GRAIN";
  1069. /// <summary> Keyword used for Fast Approximate Anti-aliasing (FXAA). </summary>
  1070. public const string Fxaa = "_FXAA";
  1071. /// <summary> Keyword used for Dithering. </summary>
  1072. public const string Dithering = "_DITHERING";
  1073. /// <summary> Keyword used for Screen Space Occlusion, such as Screen Space Ambient Occlusion (SSAO). </summary>
  1074. public const string ScreenSpaceOcclusion = "_SCREEN_SPACE_OCCLUSION";
  1075. /// <summary> Keyword used for Point sampling when doing upsampling. </summary>
  1076. public const string PointSampling = "_POINT_SAMPLING";
  1077. /// <summary> Keyword used for Robust Contrast-Adaptive Sharpening (RCAS) when doing upsampling. </summary>
  1078. public const string Rcas = "_RCAS";
  1079. /// <summary> Keyword used for Robust Contrast-Adaptive Sharpening (RCAS) when doing upsampling, after EASU has ran and with HDR Dsiplay output. </summary>
  1080. public const string EasuRcasAndHDRInput = "_EASU_RCAS_AND_HDR_INPUT";
  1081. /// <summary> Keyword used for Gamma 2.0. </summary>
  1082. public const string Gamma20 = "_GAMMA_20";
  1083. /// <summary> Keyword used for Gamma 2.0 with HDR_INPUT. </summary>
  1084. public const string Gamma20AndHDRInput = "_GAMMA_20_AND_HDR_INPUT";
  1085. /// <summary> Keyword used for high quality sampling for Depth Of Field. </summary>
  1086. public const string HighQualitySampling = "_HIGH_QUALITY_SAMPLING";
  1087. /// <summary> Keyword used for Spot lights. </summary>
  1088. public const string _SPOT = "_SPOT";
  1089. /// <summary> Keyword used for Directional lights. </summary>
  1090. public const string _DIRECTIONAL = "_DIRECTIONAL";
  1091. /// <summary> Keyword used for Point lights. </summary>
  1092. public const string _POINT = "_POINT";
  1093. /// <summary> Keyword used for stencils when rendering with the Deferred rendering path. </summary>
  1094. public const string _DEFERRED_STENCIL = "_DEFERRED_STENCIL";
  1095. /// <summary> Keyword used for the first light when rendering with the Deferred rendering path. </summary>
  1096. public const string _DEFERRED_FIRST_LIGHT = "_DEFERRED_FIRST_LIGHT";
  1097. /// <summary> Keyword used for the main light when rendering with the Deferred rendering path. </summary>
  1098. public const string _DEFERRED_MAIN_LIGHT = "_DEFERRED_MAIN_LIGHT";
  1099. /// <summary> Keyword used for Accurate G-buffer normals when rendering with the Deferred rendering path. </summary>
  1100. public const string _GBUFFER_NORMALS_OCT = "_GBUFFER_NORMALS_OCT";
  1101. /// <summary> Keyword used for Mixed Lighting when rendering with the Deferred rendering path. </summary>
  1102. public const string _DEFERRED_MIXED_LIGHTING = "_DEFERRED_MIXED_LIGHTING";
  1103. /// <summary> Keyword used for Lightmaps. </summary>
  1104. public const string LIGHTMAP_ON = "LIGHTMAP_ON";
  1105. /// <summary> Keyword used for dynamic Lightmaps. </summary>
  1106. public const string DYNAMICLIGHTMAP_ON = "DYNAMICLIGHTMAP_ON";
  1107. /// <summary> Keyword used for Alpha testing. </summary>
  1108. public const string _ALPHATEST_ON = "_ALPHATEST_ON";
  1109. /// <summary> Keyword used for combined directional Lightmaps. </summary>
  1110. public const string DIRLIGHTMAP_COMBINED = "DIRLIGHTMAP_COMBINED";
  1111. /// <summary> Keyword used for 2x detail mapping. </summary>
  1112. public const string _DETAIL_MULX2 = "_DETAIL_MULX2";
  1113. /// <summary> Keyword used for scaled detail mapping. </summary>
  1114. public const string _DETAIL_SCALED = "_DETAIL_SCALED";
  1115. /// <summary> Keyword used for Clear Coat. </summary>
  1116. public const string _CLEARCOAT = "_CLEARCOAT";
  1117. /// <summary> Keyword used for Clear Coat maps. </summary>
  1118. public const string _CLEARCOATMAP = "_CLEARCOATMAP";
  1119. /// <summary> Keyword used for Debug Display. </summary>
  1120. public const string DEBUG_DISPLAY = "DEBUG_DISPLAY";
  1121. /// <summary> Keyword used for LOD Crossfade. </summary>
  1122. public const string LOD_FADE_CROSSFADE = "LOD_FADE_CROSSFADE";
  1123. /// <summary> Keyword used for LOD Crossfade with ShaderGraph shaders. </summary>
  1124. public const string USE_UNITY_CROSSFADE = "USE_UNITY_CROSSFADE";
  1125. /// <summary> Keyword used for Emission. </summary>
  1126. public const string _EMISSION = "_EMISSION";
  1127. /// <summary> Keyword used for receiving shadows. </summary>
  1128. public const string _RECEIVE_SHADOWS_OFF = "_RECEIVE_SHADOWS_OFF";
  1129. /// <summary> Keyword used for opaque or transparent surface types. </summary>
  1130. public const string _SURFACE_TYPE_TRANSPARENT = "_SURFACE_TYPE_TRANSPARENT";
  1131. /// <summary> Keyword used for Alpha premultiply. </summary>
  1132. public const string _ALPHAPREMULTIPLY_ON = "_ALPHAPREMULTIPLY_ON";
  1133. /// <summary> Keyword used for Alpha modulate. </summary>
  1134. public const string _ALPHAMODULATE_ON = "_ALPHAMODULATE_ON";
  1135. /// <summary> Keyword used for Normal maps. </summary>
  1136. public const string _NORMALMAP = "_NORMALMAP";
  1137. /// <summary> Keyword used for Alembic precomputed velocity. </summary>
  1138. public const string _ADD_PRECOMPUTED_VELOCITY = "_ADD_PRECOMPUTED_VELOCITY";
  1139. /// <summary> Keyword used for editor visualization. </summary>
  1140. public const string EDITOR_VISUALIZATION = "EDITOR_VISUALIZATION";
  1141. /// <summary> Keyword used for foveated rendering. </summary>
  1142. public const string FoveatedRenderingNonUniformRaster = "_FOVEATED_RENDERING_NON_UNIFORM_RASTER";
  1143. /// <summary> Keyword used for disabling Texture 2D Arrays. </summary>
  1144. public const string DisableTexture2DXArray = "DISABLE_TEXTURE2D_X_ARRAY";
  1145. /// <summary> Keyword used for Single Slice Blits. </summary>
  1146. public const string BlitSingleSlice = "BLIT_SINGLE_SLICE";
  1147. /// <summary> Keyword used for rendering a combined mesh for XR. </summary>
  1148. public const string XROcclusionMeshCombined = "XR_OCCLUSION_MESH_COMBINED";
  1149. /// <summary> Keyword used for applying scale and bias. </summary>
  1150. public const string SCREEN_COORD_OVERRIDE = "SCREEN_COORD_OVERRIDE";
  1151. /// <summary> Keyword used for half size downsampling. </summary>
  1152. public const string DOWNSAMPLING_SIZE_2 = "DOWNSAMPLING_SIZE_2";
  1153. /// <summary> Keyword used for quarter size downsampling. </summary>
  1154. public const string DOWNSAMPLING_SIZE_4 = "DOWNSAMPLING_SIZE_4";
  1155. /// <summary> Keyword used for eighth size downsampling. </summary>
  1156. public const string DOWNSAMPLING_SIZE_8 = "DOWNSAMPLING_SIZE_8";
  1157. /// <summary> Keyword used for sixteenth size downsampling. </summary>
  1158. public const string DOWNSAMPLING_SIZE_16 = "DOWNSAMPLING_SIZE_16";
  1159. /// <summary> Keyword used for mixed Spherical Harmonic (SH) evaluation in URP Lit shaders.</summary>
  1160. public const string EVALUATE_SH_MIXED = "EVALUATE_SH_MIXED";
  1161. /// <summary> Keyword used for vertex Spherical Harmonic (SH) evaluation in URP Lit shaders.</summary>
  1162. public const string EVALUATE_SH_VERTEX = "EVALUATE_SH_VERTEX";
  1163. /// <summary> Keyword used for APV with SH L1 </summary>
  1164. public const string ProbeVolumeL1 = "PROBE_VOLUMES_L1";
  1165. /// <summary> Keyword used for APV with SH L2 </summary>
  1166. public const string ProbeVolumeL2 = "PROBE_VOLUMES_L2";
  1167. /// <summary> Keyword used for opting out of lightmap texture arrays, when using BatchRendererGroup. </summary>
  1168. public const string USE_LEGACY_LIGHTMAPS = "USE_LEGACY_LIGHTMAPS";
  1169. /// <summary> Keyword used for CopyDepth pass. </summary>
  1170. public const string _OUTPUT_DEPTH = "_OUTPUT_DEPTH";
  1171. /// <summary> Keyword used for enable alpha output. Used in post processing. </summary>
  1172. public const string _ENABLE_ALPHA_OUTPUT = "_ENABLE_ALPHA_OUTPUT";
  1173. }
  1174. public sealed partial class UniversalRenderPipeline
  1175. {
  1176. // Holds light direction for directional lights or position for punctual lights.
  1177. // When w is set to 1.0, it means it's a punctual light.
  1178. static Vector4 k_DefaultLightPosition = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
  1179. static Vector4 k_DefaultLightColor = Color.black;
  1180. // Default light attenuation is setup in a particular way that it causes
  1181. // directional lights to return 1.0 for both distance and angle attenuation
  1182. static Vector4 k_DefaultLightAttenuation = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
  1183. static Vector4 k_DefaultLightSpotDirection = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
  1184. static Vector4 k_DefaultLightsProbeChannel = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);
  1185. static List<Vector4> m_ShadowBiasData = new List<Vector4>();
  1186. static List<int> m_ShadowResolutionData = new List<int>();
  1187. /// <summary>
  1188. /// Checks if a camera is a game camera.
  1189. /// </summary>
  1190. /// <param name="camera">Camera to check state from.</param>
  1191. /// <returns>true if given camera is a game camera, false otherwise.</returns>
  1192. public static bool IsGameCamera(Camera camera)
  1193. {
  1194. if (camera == null)
  1195. throw new ArgumentNullException("camera");
  1196. return camera.cameraType == CameraType.Game || camera.cameraType == CameraType.VR;
  1197. }
  1198. /// <summary>
  1199. /// Returns the current render pipeline asset for the current quality setting.
  1200. /// If no render pipeline asset is assigned in QualitySettings, then returns the one assigned in GraphicsSettings.
  1201. /// </summary>
  1202. public static UniversalRenderPipelineAsset asset
  1203. {
  1204. get => GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
  1205. }
  1206. Comparison<Camera> cameraComparison = (camera1, camera2) => { return (int)camera1.depth - (int)camera2.depth; };
  1207. #if UNITY_2021_1_OR_NEWER
  1208. void SortCameras(List<Camera> cameras)
  1209. {
  1210. if (cameras.Count > 1)
  1211. cameras.Sort(cameraComparison);
  1212. }
  1213. #else
  1214. void SortCameras(Camera[] cameras)
  1215. {
  1216. if (cameras.Length > 1)
  1217. Array.Sort(cameras, cameraComparison);
  1218. }
  1219. #endif
  1220. internal static GraphicsFormat MakeRenderTextureGraphicsFormat(bool isHdrEnabled, HDRColorBufferPrecision requestHDRColorBufferPrecision, bool needsAlpha)
  1221. {
  1222. if (isHdrEnabled)
  1223. {
  1224. // TODO: we need a proper format scoring system. Score formats, sort, pick first or pick first supported (if not in score).
  1225. // UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
  1226. // For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
  1227. if (!needsAlpha && requestHDRColorBufferPrecision != HDRColorBufferPrecision._64Bits && SystemInfo.IsFormatSupported(GraphicsFormat.B10G11R11_UFloatPack32, GraphicsFormatUsage.Blend))
  1228. return GraphicsFormat.B10G11R11_UFloatPack32;
  1229. if (SystemInfo.IsFormatSupported(GraphicsFormat.R16G16B16A16_SFloat, GraphicsFormatUsage.Blend))
  1230. return GraphicsFormat.R16G16B16A16_SFloat;
  1231. return SystemInfo.GetGraphicsFormat(DefaultFormat.HDR); // This might actually be a LDR format on old devices.
  1232. }
  1233. return SystemInfo.GetGraphicsFormat(DefaultFormat.LDR);
  1234. }
  1235. // Returns a UNORM based render texture format
  1236. // When supported by the device, this function will prefer formats with higher precision, but the same bit-depth
  1237. // NOTE: This function does not guarantee that the returned format will contain an alpha channel.
  1238. internal static GraphicsFormat MakeUnormRenderTextureGraphicsFormat()
  1239. {
  1240. // UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
  1241. // For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
  1242. if (SystemInfo.IsFormatSupported(GraphicsFormat.A2B10G10R10_UNormPack32, GraphicsFormatUsage.Blend))
  1243. return GraphicsFormat.A2B10G10R10_UNormPack32;
  1244. else
  1245. return GraphicsFormat.R8G8B8A8_UNorm;
  1246. }
  1247. internal static RenderTextureDescriptor CreateRenderTextureDescriptor(Camera camera, UniversalCameraData cameraData,
  1248. bool isHdrEnabled, HDRColorBufferPrecision requestHDRColorBufferPrecision, int msaaSamples, bool needsAlpha, bool requiresOpaqueTexture)
  1249. {
  1250. RenderTextureDescriptor desc;
  1251. if (camera.targetTexture == null)
  1252. {
  1253. desc = new RenderTextureDescriptor(cameraData.scaledWidth, cameraData.scaledHeight);
  1254. desc.graphicsFormat = MakeRenderTextureGraphicsFormat(isHdrEnabled, requestHDRColorBufferPrecision, needsAlpha);
  1255. desc.depthBufferBits = 32;
  1256. desc.msaaSamples = msaaSamples;
  1257. desc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear);
  1258. }
  1259. else
  1260. {
  1261. desc = camera.targetTexture.descriptor;
  1262. desc.msaaSamples = msaaSamples;
  1263. desc.width = cameraData.scaledWidth;
  1264. desc.height = cameraData.scaledHeight;
  1265. if (camera.cameraType == CameraType.SceneView && !isHdrEnabled)
  1266. {
  1267. desc.graphicsFormat = SystemInfo.GetGraphicsFormat(DefaultFormat.LDR);
  1268. }
  1269. // SystemInfo.SupportsRenderTextureFormat(camera.targetTexture.descriptor.colorFormat)
  1270. // will assert on R8_SINT since it isn't a valid value of RenderTextureFormat.
  1271. // If this is fixed then we can implement debug statement to the user explaining why some
  1272. // RenderTextureFormats available resolves in a black render texture when no warning or error
  1273. // is given.
  1274. }
  1275. desc.enableRandomWrite = false;
  1276. desc.bindMS = false;
  1277. desc.useDynamicScale = camera.allowDynamicResolution;
  1278. // check that the requested MSAA samples count is supported by the current platform. If it's not supported,
  1279. // replace the requested desc.msaaSamples value with the actual value the engine falls back to
  1280. desc.msaaSamples = SystemInfo.GetRenderTextureSupportedMSAASampleCount(desc);
  1281. // if the target platform doesn't support storing multisampled RTs and we are doing any offscreen passes, using a Load load action on the subsequent passes
  1282. // will result in loading Resolved data, which on some platforms is discarded, resulting in losing the results of the previous passes.
  1283. // As a workaround we disable MSAA to make sure that the results of previous passes are stored. (fix for Case 1247423).
  1284. if (!SystemInfo.supportsStoreAndResolveAction)
  1285. desc.msaaSamples = 1;
  1286. return desc;
  1287. }
  1288. private static Lightmapping.RequestLightsDelegate lightsDelegate = (Light[] requests, NativeArray<LightDataGI> lightsOutput) =>
  1289. {
  1290. LightDataGI lightData = new LightDataGI();
  1291. #if UNITY_EDITOR
  1292. // Always extract lights in the Editor.
  1293. for (int i = 0; i < requests.Length; i++)
  1294. {
  1295. Light light = requests[i];
  1296. var additionalLightData = light.GetUniversalAdditionalLightData();
  1297. LightmapperUtils.Extract(light, out Cookie cookie);
  1298. switch (light.type)
  1299. {
  1300. case LightType.Directional:
  1301. DirectionalLight directionalLight = new DirectionalLight();
  1302. LightmapperUtils.Extract(light, ref directionalLight);
  1303. if (light.cookie != null)
  1304. {
  1305. // Size == 1 / Scale
  1306. cookie.sizes = additionalLightData.lightCookieSize;
  1307. // Offset, Map cookie UV offset to light position on along local axes.
  1308. if (additionalLightData.lightCookieOffset != Vector2.zero)
  1309. {
  1310. var r = light.transform.right * additionalLightData.lightCookieOffset.x;
  1311. var u = light.transform.up * additionalLightData.lightCookieOffset.y;
  1312. var offset = r + u;
  1313. directionalLight.position += offset;
  1314. }
  1315. }
  1316. lightData.Init(ref directionalLight, ref cookie);
  1317. break;
  1318. case LightType.Point:
  1319. PointLight pointLight = new PointLight();
  1320. LightmapperUtils.Extract(light, ref pointLight);
  1321. lightData.Init(ref pointLight, ref cookie);
  1322. break;
  1323. case LightType.Spot:
  1324. SpotLight spotLight = new SpotLight();
  1325. LightmapperUtils.Extract(light, ref spotLight);
  1326. spotLight.innerConeAngle = light.innerSpotAngle * Mathf.Deg2Rad;
  1327. spotLight.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle;
  1328. lightData.Init(ref spotLight, ref cookie);
  1329. break;
  1330. case LightType.Rectangle:
  1331. RectangleLight rectangleLight = new RectangleLight();
  1332. LightmapperUtils.Extract(light, ref rectangleLight);
  1333. rectangleLight.mode = LightMode.Baked;
  1334. lightData.Init(ref rectangleLight);
  1335. break;
  1336. case LightType.Disc:
  1337. DiscLight discLight = new DiscLight();
  1338. LightmapperUtils.Extract(light, ref discLight);
  1339. discLight.mode = LightMode.Baked;
  1340. lightData.Init(ref discLight);
  1341. break;
  1342. default:
  1343. lightData.InitNoBake(light.GetInstanceID());
  1344. break;
  1345. }
  1346. lightData.falloff = FalloffType.InverseSquared;
  1347. lightsOutput[i] = lightData;
  1348. }
  1349. #else
  1350. // If Enlighten realtime GI isn't active, we don't extract lights.
  1351. if (SupportedRenderingFeatures.active.enlighten == false || ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0)
  1352. {
  1353. for (int i = 0; i < requests.Length; i++)
  1354. {
  1355. Light light = requests[i];
  1356. lightData.InitNoBake(light.GetInstanceID());
  1357. lightsOutput[i] = lightData;
  1358. }
  1359. }
  1360. else
  1361. {
  1362. for (int i = 0; i < requests.Length; i++)
  1363. {
  1364. Light light = requests[i];
  1365. switch (light.type)
  1366. {
  1367. case LightType.Directional:
  1368. DirectionalLight directionalLight = new DirectionalLight();
  1369. LightmapperUtils.Extract(light, ref directionalLight);
  1370. lightData.Init(ref directionalLight);
  1371. break;
  1372. case LightType.Point:
  1373. PointLight pointLight = new PointLight();
  1374. LightmapperUtils.Extract(light, ref pointLight);
  1375. lightData.Init(ref pointLight);
  1376. break;
  1377. case LightType.Spot:
  1378. SpotLight spotLight = new SpotLight();
  1379. LightmapperUtils.Extract(light, ref spotLight);
  1380. spotLight.innerConeAngle = light.innerSpotAngle * Mathf.Deg2Rad;
  1381. spotLight.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle;
  1382. lightData.Init(ref spotLight);
  1383. break;
  1384. case LightType.Rectangle:
  1385. // Rect area light is baked only in URP.
  1386. lightData.InitNoBake(light.GetInstanceID());
  1387. break;
  1388. case LightType.Disc:
  1389. // Disc light is baked only.
  1390. lightData.InitNoBake(light.GetInstanceID());
  1391. break;
  1392. default:
  1393. lightData.InitNoBake(light.GetInstanceID());
  1394. break;
  1395. }
  1396. lightData.falloff = FalloffType.InverseSquared;
  1397. lightsOutput[i] = lightData;
  1398. }
  1399. }
  1400. #endif
  1401. };
  1402. // Called from DeferredLights.cs too
  1403. /// <summary>
  1404. /// Calculates the attenuation for a given light and also direction for spot lights.
  1405. /// </summary>
  1406. /// <param name="lightType">The type of light.</param>
  1407. /// <param name="lightRange">The range of the light.</param>
  1408. /// <param name="lightLocalToWorldMatrix">The local to world light matrix.</param>
  1409. /// <param name="spotAngle">The spotlight angle.</param>
  1410. /// <param name="innerSpotAngle">The spotlight inner angle.</param>
  1411. /// <param name="lightAttenuation">The light attenuation.</param>
  1412. /// <param name="lightSpotDir">The spot light direction.</param>
  1413. public static void GetLightAttenuationAndSpotDirection(
  1414. LightType lightType, float lightRange, Matrix4x4 lightLocalToWorldMatrix,
  1415. float spotAngle, float? innerSpotAngle,
  1416. out Vector4 lightAttenuation, out Vector4 lightSpotDir)
  1417. {
  1418. // Default is directional
  1419. lightAttenuation = k_DefaultLightAttenuation;
  1420. lightSpotDir = k_DefaultLightSpotDirection;
  1421. if (lightType != LightType.Directional)
  1422. {
  1423. GetPunctualLightDistanceAttenuation(lightRange, ref lightAttenuation);
  1424. if (lightType == LightType.Spot)
  1425. {
  1426. GetSpotDirection(ref lightLocalToWorldMatrix, out lightSpotDir);
  1427. GetSpotAngleAttenuation(spotAngle, innerSpotAngle, ref lightAttenuation);
  1428. }
  1429. }
  1430. }
  1431. internal static void GetPunctualLightDistanceAttenuation(float lightRange, ref Vector4 lightAttenuation)
  1432. {
  1433. // Light attenuation in universal matches the unity vanilla one (HINT_NICE_QUALITY).
  1434. // attenuation = 1.0 / distanceToLightSqr
  1435. // The smoothing factor makes sure that the light intensity is zero at the light range limit.
  1436. // (We used to offer two different smoothing factors.)
  1437. // The current smoothing factor matches the one used in the Unity lightmapper.
  1438. // smoothFactor = (1.0 - saturate((distanceSqr * 1.0 / lightRangeSqr)^2))^2
  1439. float lightRangeSqr = lightRange * lightRange;
  1440. float fadeStartDistanceSqr = 0.8f * 0.8f * lightRangeSqr;
  1441. float fadeRangeSqr = (fadeStartDistanceSqr - lightRangeSqr);
  1442. float lightRangeSqrOverFadeRangeSqr = -lightRangeSqr / fadeRangeSqr;
  1443. float oneOverLightRangeSqr = 1.0f / Mathf.Max(0.0001f, lightRangeSqr);
  1444. // On all devices: Use the smoothing factor that matches the GI.
  1445. lightAttenuation.x = oneOverLightRangeSqr;
  1446. lightAttenuation.y = lightRangeSqrOverFadeRangeSqr;
  1447. }
  1448. internal static void GetSpotAngleAttenuation(
  1449. float spotAngle, float? innerSpotAngle,
  1450. ref Vector4 lightAttenuation)
  1451. {
  1452. // Spot Attenuation with a linear falloff can be defined as
  1453. // (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)
  1454. // This can be rewritten as
  1455. // invAngleRange = 1.0 / (cosInnerAngle - cosOuterAngle)
  1456. // SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
  1457. // If we precompute the terms in a MAD instruction
  1458. float cosOuterAngle = Mathf.Cos(Mathf.Deg2Rad * spotAngle * 0.5f);
  1459. // We need to do a null check for particle lights
  1460. // This should be changed in the future
  1461. // Particle lights will use an inline function
  1462. float cosInnerAngle;
  1463. if (innerSpotAngle.HasValue)
  1464. cosInnerAngle = Mathf.Cos(innerSpotAngle.Value * Mathf.Deg2Rad * 0.5f);
  1465. else
  1466. cosInnerAngle = Mathf.Cos((2.0f * Mathf.Atan(Mathf.Tan(spotAngle * 0.5f * Mathf.Deg2Rad) * (64.0f - 18.0f) / 64.0f)) * 0.5f);
  1467. float smoothAngleRange = Mathf.Max(0.001f, cosInnerAngle - cosOuterAngle);
  1468. float invAngleRange = 1.0f / smoothAngleRange;
  1469. float add = -cosOuterAngle * invAngleRange;
  1470. lightAttenuation.z = invAngleRange;
  1471. lightAttenuation.w = add;
  1472. }
  1473. internal static void GetSpotDirection(ref Matrix4x4 lightLocalToWorldMatrix, out Vector4 lightSpotDir)
  1474. {
  1475. Vector4 dir = lightLocalToWorldMatrix.GetColumn(2);
  1476. lightSpotDir = new Vector4(-dir.x, -dir.y, -dir.z, 0.0f);
  1477. }
  1478. /// <summary>
  1479. /// Initializes common light constants.
  1480. /// </summary>
  1481. /// <param name="lights">List of lights to iterate.</param>
  1482. /// <param name="lightIndex">The index of the light.</param>
  1483. /// <param name="lightPos">The position of the light.</param>
  1484. /// <param name="lightColor">The color of the light.</param>
  1485. /// <param name="lightAttenuation">The attenuation of the light.</param>
  1486. /// <param name="lightSpotDir">The direction of the light.</param>
  1487. /// <param name="lightOcclusionProbeChannel">The occlusion probe channel for the light.</param>
  1488. public static void InitializeLightConstants_Common(NativeArray<VisibleLight> lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightAttenuation, out Vector4 lightSpotDir, out Vector4 lightOcclusionProbeChannel)
  1489. {
  1490. lightPos = k_DefaultLightPosition;
  1491. lightColor = k_DefaultLightColor;
  1492. lightOcclusionProbeChannel = k_DefaultLightsProbeChannel;
  1493. lightAttenuation = k_DefaultLightAttenuation; // Directional by default.
  1494. lightSpotDir = k_DefaultLightSpotDirection;
  1495. // When no lights are visible, main light will be set to -1.
  1496. // In this case we initialize it to default values and return
  1497. if (lightIndex < 0)
  1498. return;
  1499. // Avoid memcpys. Pass by ref and locals for multiple uses.
  1500. ref VisibleLight lightData = ref lights.UnsafeElementAtMutable(lightIndex);
  1501. var light = lightData.light;
  1502. var lightLocalToWorld = lightData.localToWorldMatrix;
  1503. var lightType = lightData.lightType;
  1504. if (lightType == LightType.Directional)
  1505. {
  1506. Vector4 dir = -lightLocalToWorld.GetColumn(2);
  1507. lightPos = new Vector4(dir.x, dir.y, dir.z, 0.0f);
  1508. }
  1509. else
  1510. {
  1511. Vector4 pos = lightLocalToWorld.GetColumn(3);
  1512. lightPos = new Vector4(pos.x, pos.y, pos.z, 1.0f);
  1513. GetPunctualLightDistanceAttenuation(lightData.range, ref lightAttenuation);
  1514. if (lightType == LightType.Spot)
  1515. {
  1516. GetSpotAngleAttenuation(lightData.spotAngle, light?.innerSpotAngle, ref lightAttenuation);
  1517. GetSpotDirection(ref lightLocalToWorld, out lightSpotDir);
  1518. }
  1519. }
  1520. // VisibleLight.finalColor already returns color in active color space
  1521. lightColor = lightData.finalColor;
  1522. if (light != null && light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed &&
  1523. 0 <= light.bakingOutput.occlusionMaskChannel &&
  1524. light.bakingOutput.occlusionMaskChannel < 4)
  1525. {
  1526. lightOcclusionProbeChannel[light.bakingOutput.occlusionMaskChannel] = 1.0f;
  1527. }
  1528. }
  1529. }
  1530. // URP Profile Id
  1531. // - Scopes using this enum are automatically picked up by the performance testing framework.
  1532. // - You can use [HideInDebugUI] attribute to hide a given id from the Detailed Stats section of Rendering Debugger.
  1533. internal enum URPProfileId
  1534. {
  1535. // CPU
  1536. UniversalRenderTotal,
  1537. UpdateVolumeFramework,
  1538. RenderCameraStack,
  1539. // GPU
  1540. AdditionalLightsShadow,
  1541. ColorGradingLUT,
  1542. CopyColor,
  1543. CopyDepth,
  1544. DepthNormalPrepass,
  1545. DepthPrepass,
  1546. UpdateReflectionProbeAtlas,
  1547. // DrawObjectsPass
  1548. DrawOpaqueObjects,
  1549. DrawTransparentObjects,
  1550. DrawScreenSpaceUI,
  1551. //Full Record Render Graph
  1552. RecordRenderGraph,
  1553. // RenderObjectsPass
  1554. //RenderObjects,
  1555. LightCookies,
  1556. MainLightShadow,
  1557. ResolveShadows,
  1558. SSAO,
  1559. // PostProcessPass
  1560. StopNaNs,
  1561. SMAA,
  1562. GaussianDepthOfField,
  1563. BokehDepthOfField,
  1564. TemporalAA,
  1565. MotionBlur,
  1566. PaniniProjection,
  1567. UberPostProcess,
  1568. Bloom,
  1569. LensFlareDataDrivenComputeOcclusion,
  1570. LensFlareDataDriven,
  1571. LensFlareScreenSpace,
  1572. DrawMotionVectors,
  1573. DrawFullscreen,
  1574. // PostProcessPass RenderGraph
  1575. [HideInDebugUI] RG_SetupPostFX,
  1576. [HideInDebugUI] RG_StopNaNs,
  1577. [HideInDebugUI] RG_SMAAMaterialSetup,
  1578. [HideInDebugUI] RG_SMAAEdgeDetection,
  1579. [HideInDebugUI] RG_SMAABlendWeight,
  1580. [HideInDebugUI] RG_SMAANeighborhoodBlend,
  1581. [HideInDebugUI] RG_SetupDoF,
  1582. [HideInDebugUI] RG_DOFComputeCOC,
  1583. [HideInDebugUI] RG_DOFDownscalePrefilter,
  1584. [HideInDebugUI] RG_DOFBlurH,
  1585. [HideInDebugUI] RG_DOFBlurV,
  1586. [HideInDebugUI] RG_DOFBlurBokeh,
  1587. [HideInDebugUI] RG_DOFPostFilter,
  1588. [HideInDebugUI] RG_DOFComposite,
  1589. [HideInDebugUI] RG_TAA,
  1590. [HideInDebugUI] RG_TAACopyHistory,
  1591. [HideInDebugUI] RG_MotionBlur,
  1592. [HideInDebugUI] RG_BloomSetup,
  1593. [HideInDebugUI] RG_BloomPrefilter,
  1594. [HideInDebugUI] RG_BloomDownsample,
  1595. [HideInDebugUI] RG_BloomUpsample,
  1596. [HideInDebugUI] RG_UberPostSetupBloomPass,
  1597. [HideInDebugUI] RG_UberPost,
  1598. [HideInDebugUI] RG_FinalSetup,
  1599. [HideInDebugUI] RG_FinalFSRScale,
  1600. [HideInDebugUI] RG_FinalBlit,
  1601. FinalBlit
  1602. }
  1603. // Internal class to detect and cache runtime platform information.
  1604. // TODO: refine the logic to provide platform abstraction. Eg, we should divide platforms based on capabilities and perf budget.
  1605. // TODO: isXRMobile is a bad category. Alignment and refactor needed.
  1606. // TODO: Compress all the query data into "isXRMobile" style booleans and enums.
  1607. internal static class PlatformAutoDetect
  1608. {
  1609. /// <summary>
  1610. /// Detect and cache runtime platform information. This function should only be called once when creating the URP.
  1611. /// </summary>
  1612. internal static void Initialize()
  1613. {
  1614. bool isRunningMobile = false;
  1615. #if ENABLE_VR && ENABLE_VR_MODULE
  1616. #if PLATFORM_WINRT || PLATFORM_ANDROID
  1617. isRunningMobile = IsRunningXRMobile();
  1618. #endif
  1619. #endif
  1620. isXRMobile = isRunningMobile;
  1621. isShaderAPIMobileDefined = GraphicsSettings.HasShaderDefine(BuiltinShaderDefine.SHADER_API_MOBILE);
  1622. isSwitch = Application.platform == RuntimePlatform.Switch;
  1623. }
  1624. #if ENABLE_VR && ENABLE_VR_MODULE
  1625. #if PLATFORM_WINRT || PLATFORM_ANDROID
  1626. // XR mobile platforms are not treated as dedicated mobile platforms in Core. Handle them specially here. (Quest and HL).
  1627. private static List<XR.XRDisplaySubsystem> displaySubsystemList = new List<XR.XRDisplaySubsystem>();
  1628. private static bool IsRunningXRMobile()
  1629. {
  1630. var platform = Application.platform;
  1631. if (platform == RuntimePlatform.WSAPlayerX86 || platform == RuntimePlatform.WSAPlayerARM || platform == RuntimePlatform.WSAPlayerX64 || platform == RuntimePlatform.Android)
  1632. {
  1633. XR.XRDisplaySubsystem display = null;
  1634. SubsystemManager.GetSubsystems(displaySubsystemList);
  1635. if (displaySubsystemList.Count > 0)
  1636. display = displaySubsystemList[0];
  1637. if (display != null)
  1638. return true;
  1639. }
  1640. return false;
  1641. }
  1642. #endif
  1643. #endif
  1644. /// <summary>
  1645. /// If true, the runtime platform is an XR mobile platform.
  1646. /// </summary>
  1647. internal static bool isXRMobile { get; private set; } = false;
  1648. /// <summary>
  1649. /// If true, then SHADER_API_MOBILE has been defined in URP Shaders.
  1650. /// </summary>
  1651. internal static bool isShaderAPIMobileDefined { get; private set; } = false;
  1652. /// <summary>
  1653. /// If true, then the runtime platform is set to Switch.
  1654. /// </summary>
  1655. internal static bool isSwitch { get; private set; } = false;
  1656. /// <summary>
  1657. /// Gives the SH evaluation mode when set to automatically detect.
  1658. /// </summary>
  1659. /// <param name="mode">The current SH evaluation mode.</param>
  1660. /// <returns>Returns the SH evaluation mode to use.</returns>
  1661. internal static ShEvalMode ShAutoDetect(ShEvalMode mode)
  1662. {
  1663. if (mode == ShEvalMode.Auto)
  1664. {
  1665. if (isXRMobile || isShaderAPIMobileDefined || isSwitch)
  1666. return ShEvalMode.PerVertex;
  1667. else
  1668. return ShEvalMode.PerPixel;
  1669. }
  1670. return mode;
  1671. }
  1672. }
  1673. }