RuntimeUtilities.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5. using System.Reflection;
  6. using System.Text;
  7. using UnityEngine.Assertions;
  8. #if UNITY_EDITOR
  9. using UnityEditor;
  10. #endif
  11. namespace UnityEngine.Rendering.PostProcessing
  12. {
  13. using SceneManagement;
  14. using UnityObject = UnityEngine.Object;
  15. /// <summary>
  16. /// A set of runtime utilities used by the post-processing stack.
  17. /// </summary>
  18. public static class RuntimeUtilities
  19. {
  20. #region Textures
  21. static Texture2D m_WhiteTexture;
  22. /// <summary>
  23. /// A 1x1 white texture.
  24. /// </summary>
  25. /// <remarks>
  26. /// This texture is only created once and recycled afterward. You shouldn't modify it.
  27. /// </remarks>
  28. public static Texture2D whiteTexture
  29. {
  30. get
  31. {
  32. if (m_WhiteTexture == null)
  33. {
  34. m_WhiteTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false) { name = "White Texture" };
  35. m_WhiteTexture.SetPixel(0, 0, Color.white);
  36. m_WhiteTexture.Apply();
  37. }
  38. return m_WhiteTexture;
  39. }
  40. }
  41. static Texture3D m_WhiteTexture3D;
  42. /// <summary>
  43. /// A 1x1x1 white texture.
  44. /// </summary>
  45. /// <remarks>
  46. /// This texture is only created once and recycled afterward. You shouldn't modify it.
  47. /// </remarks>
  48. public static Texture3D whiteTexture3D
  49. {
  50. get
  51. {
  52. if (m_WhiteTexture3D == null)
  53. {
  54. m_WhiteTexture3D = new Texture3D(1, 1, 1, TextureFormat.ARGB32, false) { name = "White Texture 3D" };
  55. m_WhiteTexture3D.SetPixels(new Color[] { Color.white });
  56. m_WhiteTexture3D.Apply();
  57. }
  58. return m_WhiteTexture3D;
  59. }
  60. }
  61. static Texture2D m_BlackTexture;
  62. /// <summary>
  63. /// A 1x1 black texture.
  64. /// </summary>
  65. /// <remarks>
  66. /// This texture is only created once and recycled afterward. You shouldn't modify it.
  67. /// </remarks>
  68. public static Texture2D blackTexture
  69. {
  70. get
  71. {
  72. if (m_BlackTexture == null)
  73. {
  74. m_BlackTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false) { name = "Black Texture" };
  75. m_BlackTexture.SetPixel(0, 0, Color.black);
  76. m_BlackTexture.Apply();
  77. }
  78. return m_BlackTexture;
  79. }
  80. }
  81. static Texture3D m_BlackTexture3D;
  82. /// <summary>
  83. /// A 1x1x1 black texture.
  84. /// </summary>
  85. /// <remarks>
  86. /// This texture is only created once and recycled afterward. You shouldn't modify it.
  87. /// </remarks>
  88. public static Texture3D blackTexture3D
  89. {
  90. get
  91. {
  92. if (m_BlackTexture3D == null)
  93. {
  94. m_BlackTexture3D = new Texture3D(1, 1, 1, TextureFormat.ARGB32, false) { name = "Black Texture 3D" };
  95. m_BlackTexture3D.SetPixels(new Color[] { Color.black });
  96. m_BlackTexture3D.Apply();
  97. }
  98. return m_BlackTexture3D;
  99. }
  100. }
  101. static Texture2D m_TransparentTexture;
  102. /// <summary>
  103. /// A 1x1 transparent texture.
  104. /// </summary>
  105. /// <remarks>
  106. /// This texture is only created once and recycled afterward. You shouldn't modify it.
  107. /// </remarks>
  108. public static Texture2D transparentTexture
  109. {
  110. get
  111. {
  112. if (m_TransparentTexture == null)
  113. {
  114. m_TransparentTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false) { name = "Transparent Texture" };
  115. m_TransparentTexture.SetPixel(0, 0, Color.clear);
  116. m_TransparentTexture.Apply();
  117. }
  118. return m_TransparentTexture;
  119. }
  120. }
  121. static Texture3D m_TransparentTexture3D;
  122. /// <summary>
  123. /// A 1x1x1 transparent texture.
  124. /// </summary>
  125. /// <remarks>
  126. /// This texture is only created once and recycled afterward. You shouldn't modify it.
  127. /// </remarks>
  128. public static Texture3D transparentTexture3D
  129. {
  130. get
  131. {
  132. if (m_TransparentTexture3D == null)
  133. {
  134. m_TransparentTexture3D = new Texture3D(1, 1, 1, TextureFormat.ARGB32, false) { name = "Transparent Texture 3D" };
  135. m_TransparentTexture3D.SetPixels(new Color[] { Color.clear });
  136. m_TransparentTexture3D.Apply();
  137. }
  138. return m_TransparentTexture3D;
  139. }
  140. }
  141. static Dictionary<int, Texture2D> m_LutStrips = new Dictionary<int, Texture2D>();
  142. /// <summary>
  143. /// Gets a 2D lookup table for color grading use. Its size will be <c>width = height * height</c>.
  144. /// </summary>
  145. /// <param name="size">The height of the lookup table</param>
  146. /// <returns>A 2D lookup table</returns>
  147. /// <remarks>
  148. /// Lookup tables are recycled and only created once per size. You shouldn't modify them.
  149. /// </remarks>
  150. public static Texture2D GetLutStrip(int size)
  151. {
  152. Texture2D texture;
  153. if (!m_LutStrips.TryGetValue(size, out texture))
  154. {
  155. int width = size * size;
  156. int height = size;
  157. var pixels = new Color[width * height];
  158. float inv = 1f / (size - 1f);
  159. for (int z = 0; z < size; z++)
  160. {
  161. var offset = z * size;
  162. var b = z * inv;
  163. for (int y = 0; y < size; y++)
  164. {
  165. var g = y * inv;
  166. for (int x = 0; x < size; x++)
  167. {
  168. var r = x * inv;
  169. pixels[y * width + offset + x] = new Color(r, g, b);
  170. }
  171. }
  172. }
  173. var format = TextureFormat.RGBAHalf;
  174. if (!format.IsSupported())
  175. format = TextureFormat.ARGB32;
  176. texture = new Texture2D(size * size, size, format, false, true)
  177. {
  178. name = "Strip Lut" + size,
  179. hideFlags = HideFlags.DontSave,
  180. filterMode = FilterMode.Bilinear,
  181. wrapMode = TextureWrapMode.Clamp,
  182. anisoLevel = 0
  183. };
  184. texture.SetPixels(pixels);
  185. texture.Apply();
  186. m_LutStrips.Add(size, texture);
  187. }
  188. return texture;
  189. }
  190. #endregion
  191. #region Rendering
  192. internal static PostProcessResources s_Resources;
  193. static Mesh s_FullscreenTriangle;
  194. /// <summary>
  195. /// A fullscreen triangle mesh.
  196. /// </summary>
  197. public static Mesh fullscreenTriangle
  198. {
  199. get
  200. {
  201. if (s_FullscreenTriangle != null)
  202. return s_FullscreenTriangle;
  203. s_FullscreenTriangle = new Mesh { name = "Fullscreen Triangle" };
  204. // Because we have to support older platforms (GLES2/3, DX9 etc) we can't do all of
  205. // this directly in the vertex shader using vertex ids :(
  206. s_FullscreenTriangle.SetVertices(new List<Vector3>
  207. {
  208. new Vector3(-1f, -1f, 0f),
  209. new Vector3(-1f, 3f, 0f),
  210. new Vector3( 3f, -1f, 0f)
  211. });
  212. s_FullscreenTriangle.SetIndices(new [] { 0, 1, 2 }, MeshTopology.Triangles, 0, false);
  213. s_FullscreenTriangle.UploadMeshData(false);
  214. return s_FullscreenTriangle;
  215. }
  216. }
  217. static Material s_CopyStdMaterial;
  218. /// <summary>
  219. /// A simple copy material to use with the builtin pipelines.
  220. /// </summary>
  221. public static Material copyStdMaterial
  222. {
  223. get
  224. {
  225. if (s_CopyStdMaterial != null)
  226. return s_CopyStdMaterial;
  227. Assert.IsNotNull(s_Resources);
  228. var shader = s_Resources.shaders.copyStd;
  229. s_CopyStdMaterial = new Material(shader)
  230. {
  231. name = "PostProcess - CopyStd",
  232. hideFlags = HideFlags.HideAndDontSave
  233. };
  234. return s_CopyStdMaterial;
  235. }
  236. }
  237. static Material s_CopyStdFromDoubleWideMaterial;
  238. /// <summary>
  239. /// A double-wide copy material to use with VR and the builtin pipelines.
  240. /// </summary>
  241. public static Material copyStdFromDoubleWideMaterial
  242. {
  243. get
  244. {
  245. if (s_CopyStdFromDoubleWideMaterial != null)
  246. return s_CopyStdFromDoubleWideMaterial;
  247. Assert.IsNotNull(s_Resources);
  248. var shader = s_Resources.shaders.copyStdFromDoubleWide;
  249. s_CopyStdFromDoubleWideMaterial = new Material(shader)
  250. {
  251. name = "PostProcess - CopyStdFromDoubleWide",
  252. hideFlags = HideFlags.HideAndDontSave
  253. };
  254. return s_CopyStdFromDoubleWideMaterial;
  255. }
  256. }
  257. static Material s_CopyMaterial;
  258. /// <summary>
  259. /// A simple copy material independent from the rendering pipeline.
  260. /// </summary>
  261. public static Material copyMaterial
  262. {
  263. get
  264. {
  265. if (s_CopyMaterial != null)
  266. return s_CopyMaterial;
  267. Assert.IsNotNull(s_Resources);
  268. var shader = s_Resources.shaders.copy;
  269. s_CopyMaterial = new Material(shader)
  270. {
  271. name = "PostProcess - Copy",
  272. hideFlags = HideFlags.HideAndDontSave
  273. };
  274. return s_CopyMaterial;
  275. }
  276. }
  277. static Material s_CopyFromTexArrayMaterial;
  278. /// <summary>
  279. /// A copy material with a texture array slice as a source for the builtin pipelines.
  280. /// </summary>
  281. public static Material copyFromTexArrayMaterial
  282. {
  283. get
  284. {
  285. if (s_CopyFromTexArrayMaterial != null)
  286. return s_CopyFromTexArrayMaterial;
  287. Assert.IsNotNull(s_Resources);
  288. var shader = s_Resources.shaders.copyStdFromTexArray;
  289. s_CopyFromTexArrayMaterial = new Material(shader)
  290. {
  291. name = "PostProcess - CopyFromTexArray",
  292. hideFlags = HideFlags.HideAndDontSave
  293. };
  294. return s_CopyFromTexArrayMaterial;
  295. }
  296. }
  297. static PropertySheet s_CopySheet;
  298. /// <summary>
  299. /// A pre-configured <see cref="PropertySheet"/> for <see cref="copyMaterial"/>.
  300. /// </summary>
  301. public static PropertySheet copySheet
  302. {
  303. get
  304. {
  305. if (s_CopySheet == null)
  306. s_CopySheet = new PropertySheet(copyMaterial);
  307. return s_CopySheet;
  308. }
  309. }
  310. static PropertySheet s_CopyFromTexArraySheet;
  311. /// <summary>
  312. /// A pre-configured <see cref="PropertySheet"/> for <see cref="copyFromTexArrayMaterial"/>.
  313. /// </summary>
  314. public static PropertySheet copyFromTexArraySheet
  315. {
  316. get
  317. {
  318. if (s_CopyFromTexArraySheet == null)
  319. s_CopyFromTexArraySheet = new PropertySheet(copyFromTexArrayMaterial);
  320. return s_CopyFromTexArraySheet;
  321. }
  322. }
  323. /// <summary>
  324. /// Sets the current render target using specified <see cref="RenderBufferLoadAction"/>.
  325. /// </summary>
  326. /// <param name="cmd">The command buffer to set the render target on</param>
  327. /// <param name="rt">The render target to set</param>
  328. /// <param name="loadAction">The load action</param>
  329. /// <param name="storeAction">The store action</param>
  330. /// <remarks>
  331. /// <see cref="RenderBufferLoadAction"/> are only used on Unity 2018.2 or newer.
  332. /// </remarks>
  333. public static void SetRenderTargetWithLoadStoreAction(this CommandBuffer cmd, RenderTargetIdentifier rt, RenderBufferLoadAction loadAction, RenderBufferStoreAction storeAction)
  334. {
  335. #if UNITY_2018_2_OR_NEWER
  336. cmd.SetRenderTarget(rt, loadAction, storeAction);
  337. #else
  338. cmd.SetRenderTarget(rt);
  339. #endif
  340. }
  341. /// <summary>
  342. /// Sets the current render target and its depth using specified <see cref="RenderBufferLoadAction"/>.
  343. /// </summary>
  344. /// <param name="cmd">The command buffer to set the render target on</param>
  345. /// <param name="color">The render target to set as color</param>
  346. /// <param name="colorLoadAction">The load action for the color render target</param>
  347. /// <param name="colorStoreAction">The store action for the color render target</param>
  348. /// <param name="depth">The render target to set as depth</param>
  349. /// <param name="depthLoadAction">The load action for the depth render target</param>
  350. /// <param name="depthStoreAction">The store action for the depth render target</param>
  351. public static void SetRenderTargetWithLoadStoreAction(this CommandBuffer cmd,
  352. RenderTargetIdentifier color, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction,
  353. RenderTargetIdentifier depth, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction)
  354. {
  355. #if UNITY_2018_2_OR_NEWER
  356. cmd.SetRenderTarget(color, colorLoadAction, colorStoreAction, depth, depthLoadAction, depthStoreAction);
  357. #else
  358. cmd.SetRenderTarget(color, depth);
  359. #endif
  360. }
  361. /// <summary>
  362. /// Does a copy of source to destination using a fullscreen triangle.
  363. /// </summary>
  364. /// <param name="cmd">The command buffer to use</param>
  365. /// <param name="source">The source render target</param>
  366. /// <param name="destination">The destination render target</param>
  367. /// <param name="clear">Should the destination target be cleared?</param>
  368. /// <param name="viewport">An optional viewport to consider for the blit</param>
  369. public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, bool clear = false, Rect? viewport = null)
  370. {
  371. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  372. cmd.SetRenderTargetWithLoadStoreAction(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  373. if (viewport != null)
  374. cmd.SetViewport(viewport.Value);
  375. if (clear)
  376. cmd.ClearRenderTarget(true, true, Color.clear);
  377. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, copyMaterial, 0, 0);
  378. }
  379. /// <summary>
  380. /// Blits a fullscreen triangle using a given material.
  381. /// </summary>
  382. /// <param name="cmd">The command buffer to use</param>
  383. /// <param name="source">The source render target</param>
  384. /// <param name="destination">The destination render target</param>
  385. /// <param name="propertySheet">The property sheet to use</param>
  386. /// <param name="pass">The pass from the material to use</param>
  387. /// <param name="loadAction">The load action for this blit</param>
  388. /// <param name="viewport">An optional viewport to consider for the blit</param>
  389. public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, PropertySheet propertySheet, int pass, RenderBufferLoadAction loadAction, Rect? viewport = null)
  390. {
  391. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  392. #if UNITY_2018_2_OR_NEWER
  393. bool clear = (loadAction == RenderBufferLoadAction.Clear);
  394. #else
  395. bool clear = false;
  396. #endif
  397. cmd.SetRenderTargetWithLoadStoreAction(destination, clear ? RenderBufferLoadAction.DontCare : loadAction, RenderBufferStoreAction.Store);
  398. if (viewport != null)
  399. cmd.SetViewport(viewport.Value);
  400. if (clear)
  401. cmd.ClearRenderTarget(true, true, Color.clear);
  402. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
  403. }
  404. /// <summary>
  405. /// Blits a fullscreen triangle using a given material.
  406. /// </summary>
  407. /// <param name="cmd">The command buffer to use</param>
  408. /// <param name="source">The source render target</param>
  409. /// <param name="destination">The destination render target</param>
  410. /// <param name="propertySheet">The property sheet to use</param>
  411. /// <param name="pass">The pass from the material to use</param>
  412. /// <param name="clear">Should the destination target be cleared?</param>
  413. /// <param name="viewport">An optional viewport to consider for the blit</param>
  414. public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, PropertySheet propertySheet, int pass, bool clear = false, Rect? viewport = null)
  415. {
  416. #if UNITY_2018_2_OR_NEWER
  417. cmd.BlitFullscreenTriangle(source, destination, propertySheet, pass, clear ? RenderBufferLoadAction.Clear : RenderBufferLoadAction.DontCare, viewport);
  418. #else
  419. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  420. cmd.SetRenderTargetWithLoadStoreAction(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  421. if (viewport != null)
  422. cmd.SetViewport(viewport.Value);
  423. if (clear)
  424. cmd.ClearRenderTarget(true, true, Color.clear);
  425. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
  426. #endif
  427. }
  428. /// <summary>
  429. /// Blits a fullscreen triangle from a double-wide source.
  430. /// </summary>
  431. /// <param name="cmd">The command buffer to use</param>
  432. /// <param name="source">The source render target</param>
  433. /// <param name="destination">The destination render target</param>
  434. /// <param name="material">The material to use for the blit</param>
  435. /// <param name="pass">The pass from the material to use</param>
  436. /// <param name="eye">The target eye</param>
  437. public static void BlitFullscreenTriangleFromDoubleWide(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, Material material, int pass, int eye)
  438. {
  439. Vector4 uvScaleOffset = new Vector4(0.5f, 1.0f, 0, 0);
  440. if (eye == 1)
  441. uvScaleOffset.z = 0.5f;
  442. cmd.SetGlobalVector(ShaderIDs.UVScaleOffset, uvScaleOffset);
  443. cmd.BuiltinBlit(source, destination, material, pass);
  444. }
  445. /// <summary>
  446. /// Blits a fullscreen triangle to a double-wide destination.
  447. /// </summary>
  448. /// <param name="cmd">The command buffer to use</param>
  449. /// <param name="source">The source render target</param>
  450. /// <param name="destination">The destination render target</param>
  451. /// <param name="propertySheet">The property sheet to use</param>
  452. /// <param name="pass">The pass from the material to use</param>
  453. /// <param name="eye">The target eye</param>
  454. public static void BlitFullscreenTriangleToDoubleWide(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, PropertySheet propertySheet, int pass, int eye)
  455. {
  456. Vector4 posScaleOffset = new Vector4(0.5f, 1.0f, -0.5f, 0);
  457. if (eye == 1)
  458. posScaleOffset.z = 0.5f;
  459. propertySheet.EnableKeyword("STEREO_DOUBLEWIDE_TARGET");
  460. propertySheet.properties.SetVector(ShaderIDs.PosScaleOffset, posScaleOffset);
  461. cmd.BlitFullscreenTriangle(source, destination, propertySheet, 0);
  462. }
  463. /// <summary>
  464. /// Blits a fullscreen triangle using a given material.
  465. /// </summary>
  466. /// <param name="cmd">The command buffer to use</param>
  467. /// <param name="source">The source texture array</param>
  468. /// <param name="destination">The destination render target</param>
  469. /// <param name="propertySheet">The property sheet to use</param>
  470. /// <param name="pass">The pass from the material to use</param>
  471. /// <param name="clear">Should the destination target be cleared?</param>
  472. /// <param name="depthSlice">The slice to use for the texture array</param>
  473. public static void BlitFullscreenTriangleFromTexArray(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, PropertySheet propertySheet, int pass, bool clear = false, int depthSlice = -1)
  474. {
  475. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  476. cmd.SetGlobalFloat(ShaderIDs.DepthSlice, depthSlice);
  477. cmd.SetRenderTargetWithLoadStoreAction(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  478. if (clear)
  479. cmd.ClearRenderTarget(true, true, Color.clear);
  480. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
  481. }
  482. /// <summary>
  483. /// Blits a fullscreen triangle using a given material.
  484. /// </summary>
  485. /// <param name="cmd">The command buffer to use</param>
  486. /// <param name="source">The source render target</param>
  487. /// <param name="destination">The destination render target</param>
  488. /// <param name="depth">The depth render target</param>
  489. /// <param name="propertySheet">The property sheet to use</param>
  490. /// <param name="pass">The pass from the material to use</param>
  491. /// <param name="clear">Should the destination target be cleared?</param>
  492. /// <param name="depthSlice">The array slice to consider as a source</param>
  493. public static void BlitFullscreenTriangleToTexArray(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, PropertySheet propertySheet, int pass, bool clear = false, int depthSlice = -1)
  494. {
  495. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  496. cmd.SetGlobalFloat(ShaderIDs.DepthSlice, depthSlice);
  497. cmd.SetRenderTarget(destination, 0, CubemapFace.Unknown, -1);
  498. if (clear)
  499. cmd.ClearRenderTarget(true, true, Color.clear);
  500. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
  501. }
  502. /// <summary>
  503. /// Blits a fullscreen triangle using a given material.
  504. /// </summary>
  505. /// <param name="cmd">The command buffer to use</param>
  506. /// <param name="source">The source render target</param>
  507. /// <param name="destination">The destination render target</param>
  508. /// <param name="depth">The depth render target</param>
  509. /// <param name="propertySheet">The property sheet to use</param>
  510. /// <param name="pass">The pass from the material to use</param>
  511. /// <param name="clear">Should the destination target be cleared?</param>
  512. /// <param name="viewport">An optional viewport to consider for the blit</param>
  513. public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination, RenderTargetIdentifier depth, PropertySheet propertySheet, int pass, bool clear = false, Rect? viewport = null)
  514. {
  515. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  516. if (clear)
  517. {
  518. cmd.SetRenderTargetWithLoadStoreAction(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
  519. depth, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  520. cmd.ClearRenderTarget(true, true, Color.clear);
  521. }
  522. else
  523. {
  524. cmd.SetRenderTargetWithLoadStoreAction(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
  525. depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
  526. }
  527. if (viewport != null)
  528. cmd.SetViewport(viewport.Value);
  529. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
  530. }
  531. /// <summary>
  532. /// Blits a fullscreen triangle using a given material.
  533. /// </summary>
  534. /// <param name="cmd">The command buffer to use</param>
  535. /// <param name="source">The source render target</param>
  536. /// <param name="destinations">An array of destinations render targets</param>
  537. /// <param name="depth">The depth render target</param>
  538. /// <param name="propertySheet">The property sheet to use</param>
  539. /// <param name="pass">The pass from the material to use</param>
  540. /// <param name="clear">Should the destination target be cleared?</param>
  541. /// <param name="viewport">An optional viewport to consider for the blit</param>
  542. public static void BlitFullscreenTriangle(this CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier[] destinations, RenderTargetIdentifier depth, PropertySheet propertySheet, int pass, bool clear = false, Rect? viewport = null)
  543. {
  544. cmd.SetGlobalTexture(ShaderIDs.MainTex, source);
  545. cmd.SetRenderTarget(destinations, depth);
  546. if (viewport != null)
  547. cmd.SetViewport(viewport.Value);
  548. if (clear)
  549. cmd.ClearRenderTarget(true, true, Color.clear);
  550. cmd.DrawMesh(fullscreenTriangle, Matrix4x4.identity, propertySheet.material, 0, pass, propertySheet.properties);
  551. }
  552. /// <summary>
  553. /// Does a copy of source to destination using the builtin blit command.
  554. /// </summary>
  555. /// <param name="cmd">The command buffer to use</param>
  556. /// <param name="source">The source render target</param>
  557. /// <param name="destination">The destination render target</param>
  558. public static void BuiltinBlit(this CommandBuffer cmd, Rendering.RenderTargetIdentifier source, RenderTargetIdentifier destination)
  559. {
  560. #if UNITY_2018_2_OR_NEWER
  561. cmd.SetRenderTarget(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  562. destination = BuiltinRenderTextureType.CurrentActive;
  563. #endif
  564. cmd.Blit(source, destination);
  565. }
  566. /// <summary>
  567. /// Blits a fullscreen quad using the builtin blit command and a given material.
  568. /// </summary>
  569. /// <param name="cmd">The command buffer to use</param>
  570. /// <param name="source">The source render target</param>
  571. /// <param name="destination">The destination render target</param>
  572. /// <param name="mat">The material to use for the blit</param>
  573. /// <param name="pass">The pass from the material to use</param>
  574. public static void BuiltinBlit(this CommandBuffer cmd, Rendering.RenderTargetIdentifier source, RenderTargetIdentifier destination, Material mat, int pass = 0)
  575. {
  576. #if UNITY_2018_2_OR_NEWER
  577. cmd.SetRenderTarget(destination, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  578. destination = BuiltinRenderTextureType.CurrentActive;
  579. #endif
  580. cmd.Blit(source, destination, mat, pass);
  581. }
  582. // Fast basic copy texture if available, falls back to blit copy if not
  583. // Assumes that both textures have the exact same type and format
  584. /// <summary>
  585. /// Copies the content of a texture into the other. Both textures must have the same size
  586. /// and format or this method will fail.
  587. /// </summary>
  588. /// <param name="cmd">The command buffer to use</param>
  589. /// <param name="source">The source render target</param>
  590. /// <param name="destination">The destination render target</param>
  591. /// <remarks>
  592. /// If the CopyTexture command isn't supported on the target platform it will revert to a
  593. /// fullscreen blit command instead.
  594. /// </remarks>
  595. public static void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination)
  596. {
  597. if (SystemInfo.copyTextureSupport > CopyTextureSupport.None)
  598. {
  599. cmd.CopyTexture(source, destination);
  600. return;
  601. }
  602. cmd.BlitFullscreenTriangle(source, destination);
  603. }
  604. // TODO: Generalize the GetTemporaryRT and Blit commands in order to support
  605. // RT Arrays for Stereo Instancing/MultiView
  606. #endregion
  607. #region Unity specifics & misc methods
  608. /// <summary>
  609. /// Returns <c>true</c> if a scriptable render pipeline is currently in use, <c>false</c>
  610. /// otherwise.
  611. /// </summary>
  612. public static bool scriptableRenderPipelineActive
  613. {
  614. get { return GraphicsSettings.renderPipelineAsset != null; } // 5.6+ only
  615. }
  616. /// <summary>
  617. /// Returns <c>true</c> if deferred shading is supported on the target platform,
  618. /// <c>false</c> otherwise.
  619. /// </summary>
  620. public static bool supportsDeferredShading
  621. {
  622. get { return scriptableRenderPipelineActive || GraphicsSettings.GetShaderMode(BuiltinShaderType.DeferredShading) != BuiltinShaderMode.Disabled; }
  623. }
  624. /// <summary>
  625. /// Returns <c>true</c> if <see cref="DepthTextureMode.DepthNormals"/> is supported on the
  626. /// target platform, <c>false</c> otherwise.
  627. /// </summary>
  628. public static bool supportsDepthNormals
  629. {
  630. get { return scriptableRenderPipelineActive || GraphicsSettings.GetShaderMode(BuiltinShaderType.DepthNormals) != BuiltinShaderMode.Disabled; }
  631. }
  632. #if UNITY_EDITOR
  633. /// <summary>
  634. /// Returns <c>true</c> if single-pass stereo rendering is selected, <c>false</c> otherwise.
  635. /// </summary>
  636. /// <remarks>
  637. /// This property only works in the editor.
  638. /// </remarks>
  639. public static bool isSinglePassStereoSelected
  640. {
  641. get
  642. {
  643. return PlayerSettings.virtualRealitySupported
  644. && PlayerSettings.stereoRenderingPath == UnityEditor.StereoRenderingPath.SinglePass;
  645. }
  646. }
  647. #endif
  648. /// <summary>
  649. /// Returns <c>true</c> if single-pass stereo rendering is active, <c>false</c> otherwise.
  650. /// </summary>
  651. /// <remarks>
  652. /// This property only works in the editor.
  653. /// </remarks>
  654. // TODO: Check for SPSR support at runtime
  655. public static bool isSinglePassStereoEnabled
  656. {
  657. get
  658. {
  659. #if UNITY_EDITOR
  660. return isSinglePassStereoSelected && Application.isPlaying;
  661. #elif UNITY_SWITCH
  662. return false;
  663. #elif UNITY_2017_2_OR_NEWER
  664. return UnityEngine.XR.XRSettings.eyeTextureDesc.vrUsage == VRTextureUsage.TwoEyes;
  665. #else
  666. return false;
  667. #endif
  668. }
  669. }
  670. /// <summary>
  671. /// Returns <c>true</c> if VR is enabled, <c>false</c> otherwise.
  672. /// </summary>
  673. public static bool isVREnabled
  674. {
  675. get
  676. {
  677. #if UNITY_EDITOR
  678. return UnityEditor.PlayerSettings.virtualRealitySupported;
  679. #elif UNITY_XBOXONE || UNITY_SWITCH
  680. return false;
  681. #elif UNITY_2017_2_OR_NEWER
  682. return UnityEngine.XR.XRSettings.enabled;
  683. #elif UNITY_5_6_OR_NEWER
  684. return UnityEngine.VR.VRSettings.enabled;
  685. #endif
  686. }
  687. }
  688. /// <summary>
  689. /// Returns <c>true</c> if the target platform is Android and the selected API is OpenGL,
  690. /// <c>false</c> otherwise.
  691. /// </summary>
  692. public static bool isAndroidOpenGL
  693. {
  694. get { return Application.platform == RuntimePlatform.Android && SystemInfo.graphicsDeviceType != GraphicsDeviceType.Vulkan; }
  695. }
  696. /// <summary>
  697. /// Gets the default HDR render texture format for the current target platform.
  698. /// </summary>
  699. public static RenderTextureFormat defaultHDRRenderTextureFormat
  700. {
  701. get
  702. {
  703. #if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SWITCH || UNITY_EDITOR
  704. RenderTextureFormat format = RenderTextureFormat.RGB111110Float;
  705. #if UNITY_EDITOR
  706. var target = EditorUserBuildSettings.activeBuildTarget;
  707. if (target != BuildTarget.Android && target != BuildTarget.iOS && target != BuildTarget.tvOS && target != BuildTarget.Switch)
  708. return RenderTextureFormat.DefaultHDR;
  709. #endif // UNITY_EDITOR
  710. if (format.IsSupported())
  711. return format;
  712. #endif // UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SWITCH || UNITY_EDITOR
  713. return RenderTextureFormat.DefaultHDR;
  714. }
  715. }
  716. /// <summary>
  717. /// Checks if a given render texture format is a floating-point format.
  718. /// </summary>
  719. /// <param name="format">The format to test</param>
  720. /// <returns><c>true</c> if the format is floating-point, <c>false</c> otherwise</returns>
  721. public static bool isFloatingPointFormat(RenderTextureFormat format)
  722. {
  723. return format == RenderTextureFormat.DefaultHDR || format == RenderTextureFormat.ARGBHalf || format == RenderTextureFormat.ARGBFloat ||
  724. format == RenderTextureFormat.RGFloat || format == RenderTextureFormat.RGHalf ||
  725. format == RenderTextureFormat.RFloat || format == RenderTextureFormat.RHalf ||
  726. format == RenderTextureFormat.RGB111110Float;
  727. }
  728. /// <summary>
  729. /// Properly destroys a given Unity object.
  730. /// </summary>
  731. /// <param name="obj">The object to destroy</param>
  732. public static void Destroy(UnityObject obj)
  733. {
  734. if (obj != null)
  735. {
  736. #if UNITY_EDITOR
  737. if (Application.isPlaying)
  738. UnityObject.Destroy(obj);
  739. else
  740. UnityObject.DestroyImmediate(obj);
  741. #else
  742. UnityObject.Destroy(obj);
  743. #endif
  744. }
  745. }
  746. /// <summary>
  747. /// Returns <c>true</c> if the current color space setting is set to <c>Linear</c>,
  748. /// <c>false</c> otherwise.
  749. /// </summary>
  750. public static bool isLinearColorSpace
  751. {
  752. get { return QualitySettings.activeColorSpace == ColorSpace.Linear; }
  753. }
  754. /// <summary>
  755. /// Checks if resolved depth is available on the current target platform.
  756. /// </summary>
  757. /// <param name="camera">A rendering camera</param>
  758. /// <returns><c>true</c> if resolved depth is available, <c>false</c> otherwise</returns>
  759. public static bool IsResolvedDepthAvailable(Camera camera)
  760. {
  761. // AFAIK resolved depth is only available on D3D11/12 via BuiltinRenderTextureType.ResolvedDepth
  762. // TODO: Is there more proper way to determine this? What about SRPs?
  763. var gtype = SystemInfo.graphicsDeviceType;
  764. return camera.actualRenderingPath == RenderingPath.DeferredShading &&
  765. (gtype == GraphicsDeviceType.Direct3D11 || gtype == GraphicsDeviceType.Direct3D12 || gtype == GraphicsDeviceType.XboxOne);
  766. }
  767. /// <summary>
  768. /// Properly destroys a given profile.
  769. /// </summary>
  770. /// <param name="profile">The profile to destroy</param>
  771. /// <param name="destroyEffects">Should we destroy all the embedded settings?</param>
  772. public static void DestroyProfile(PostProcessProfile profile, bool destroyEffects)
  773. {
  774. if (destroyEffects)
  775. {
  776. foreach (var effect in profile.settings)
  777. Destroy(effect);
  778. }
  779. Destroy(profile);
  780. }
  781. /// <summary>
  782. /// Properly destroys a volume.
  783. /// </summary>
  784. /// <param name="volume">The volume to destroy</param>
  785. /// <param name="destroyProfile">Should we destroy the attached profile?</param>
  786. /// <param name="destroyGameObject">Should we destroy the volume Game Object?</param>
  787. public static void DestroyVolume(PostProcessVolume volume, bool destroyProfile, bool destroyGameObject = false)
  788. {
  789. if (destroyProfile)
  790. DestroyProfile(volume.profileRef, true);
  791. var gameObject = volume.gameObject;
  792. Destroy(volume);
  793. if (destroyGameObject)
  794. Destroy(gameObject);
  795. }
  796. /// <summary>
  797. /// Checks if a post-processing layer is active.
  798. /// </summary>
  799. /// <param name="layer">The layer to check; can be <c>null</c></param>
  800. /// <returns><c>true</c> if the layer is enabled, <c>false</c> otherwise</returns>
  801. public static bool IsPostProcessingActive(PostProcessLayer layer)
  802. {
  803. return layer != null
  804. && layer.enabled;
  805. }
  806. /// <summary>
  807. /// Checks if temporal anti-aliasing is active on a given post-process layer.
  808. /// </summary>
  809. /// <param name="layer">The layer to check</param>
  810. /// <returns><c>true</c> if temporal anti-aliasing is active, <c>false</c> otherwise</returns>
  811. public static bool IsTemporalAntialiasingActive(PostProcessLayer layer)
  812. {
  813. return IsPostProcessingActive(layer)
  814. && layer.antialiasingMode == PostProcessLayer.Antialiasing.TemporalAntialiasing
  815. && layer.temporalAntialiasing.IsSupported();
  816. }
  817. /// <summary>
  818. /// Gets all scene objects in the hierarchy, including inactive objects. This method is slow
  819. /// on large scenes and should be used with extreme caution.
  820. /// </summary>
  821. /// <typeparam name="T">The component to look for</typeparam>
  822. /// <returns>A list of all components of type <c>T</c> in the scene</returns>
  823. public static IEnumerable<T> GetAllSceneObjects<T>()
  824. where T : Component
  825. {
  826. var queue = new Queue<Transform>();
  827. var roots = SceneManager.GetActiveScene().GetRootGameObjects();
  828. foreach (var root in roots)
  829. {
  830. queue.Enqueue(root.transform);
  831. var comp = root.GetComponent<T>();
  832. if (comp != null)
  833. yield return comp;
  834. }
  835. while (queue.Count > 0)
  836. {
  837. foreach (Transform child in queue.Dequeue())
  838. {
  839. queue.Enqueue(child);
  840. var comp = child.GetComponent<T>();
  841. if (comp != null)
  842. yield return comp;
  843. }
  844. }
  845. }
  846. /// <summary>
  847. /// Creates an instance of a class if it's <c>null</c>.
  848. /// </summary>
  849. /// <typeparam name="T">The type to create</typeparam>
  850. /// <param name="obj">A reference to an instance to check and create if needed</param>
  851. public static void CreateIfNull<T>(ref T obj)
  852. where T : class, new()
  853. {
  854. if (obj == null)
  855. obj = new T();
  856. }
  857. #endregion
  858. #region Maths
  859. /// <summary>
  860. /// Returns the base-2 exponential function of <paramref name="x"/>, which is <c>2</c>
  861. /// raised to the power <paramref name="x"/>.
  862. /// </summary>
  863. /// <param name="x">Value of the exponent</param>
  864. /// <returns>The base-2 exponential function of <paramref name="x"/></returns>
  865. public static float Exp2(float x)
  866. {
  867. return Mathf.Exp(x * 0.69314718055994530941723212145818f);
  868. }
  869. /// <summary>
  870. /// Gets a jittered perspective projection matrix for a given camera.
  871. /// </summary>
  872. /// <param name="camera">The camera to build the projection matrix for</param>
  873. /// <param name="offset">The jitter offset</param>
  874. /// <returns>A jittered projection matrix</returns>
  875. public static Matrix4x4 GetJitteredPerspectiveProjectionMatrix(Camera camera, Vector2 offset)
  876. {
  877. float near = camera.nearClipPlane;
  878. float far = camera.farClipPlane;
  879. float vertical = Mathf.Tan(0.5f * Mathf.Deg2Rad * camera.fieldOfView) * near;
  880. float horizontal = vertical * camera.aspect;
  881. offset.x *= horizontal / (0.5f * camera.pixelWidth);
  882. offset.y *= vertical / (0.5f * camera.pixelHeight);
  883. var matrix = camera.projectionMatrix;
  884. matrix[0, 2] += offset.x / horizontal;
  885. matrix[1, 2] += offset.y / vertical;
  886. return matrix;
  887. }
  888. /// <summary>
  889. /// Gets a jittered orthographic projection matrix for a given camera.
  890. /// </summary>
  891. /// <param name="camera">The camera to build the orthographic matrix for</param>
  892. /// <param name="offset">The jitter offset</param>
  893. /// <returns>A jittered projection matrix</returns>
  894. public static Matrix4x4 GetJitteredOrthographicProjectionMatrix(Camera camera, Vector2 offset)
  895. {
  896. float vertical = camera.orthographicSize;
  897. float horizontal = vertical * camera.aspect;
  898. offset.x *= horizontal / (0.5f * camera.pixelWidth);
  899. offset.y *= vertical / (0.5f * camera.pixelHeight);
  900. float left = offset.x - horizontal;
  901. float right = offset.x + horizontal;
  902. float top = offset.y + vertical;
  903. float bottom = offset.y - vertical;
  904. return Matrix4x4.Ortho(left, right, bottom, top, camera.nearClipPlane, camera.farClipPlane);
  905. }
  906. /// <summary>
  907. /// Gets a jittered perspective projection matrix from an original projection matrix.
  908. /// </summary>
  909. /// <param name="context">The current render context</param>
  910. /// <param name="origProj">The original projection matrix</param>
  911. /// <param name="jitter">The jitter offset</param>
  912. /// <returns>A jittered projection matrix</returns>
  913. public static Matrix4x4 GenerateJitteredProjectionMatrixFromOriginal(PostProcessRenderContext context, Matrix4x4 origProj, Vector2 jitter)
  914. {
  915. #if UNITY_2017_2_OR_NEWER
  916. var planes = origProj.decomposeProjection;
  917. float vertFov = Math.Abs(planes.top) + Math.Abs(planes.bottom);
  918. float horizFov = Math.Abs(planes.left) + Math.Abs(planes.right);
  919. var planeJitter = new Vector2(jitter.x * horizFov / context.screenWidth,
  920. jitter.y * vertFov / context.screenHeight);
  921. planes.left += planeJitter.x;
  922. planes.right += planeJitter.x;
  923. planes.top += planeJitter.y;
  924. planes.bottom += planeJitter.y;
  925. var jitteredMatrix = Matrix4x4.Frustum(planes);
  926. return jitteredMatrix;
  927. #else
  928. var rTan = (1.0f + origProj[0, 2]) / origProj[0, 0];
  929. var lTan = (-1.0f + origProj[0, 2]) / origProj[0, 0];
  930. var tTan = (1.0f + origProj[1, 2]) / origProj[1, 1];
  931. var bTan = (-1.0f + origProj[1, 2]) / origProj[1, 1];
  932. float tanVertFov = Math.Abs(tTan) + Math.Abs(bTan);
  933. float tanHorizFov = Math.Abs(lTan) + Math.Abs(rTan);
  934. jitter.x *= tanHorizFov / context.screenWidth;
  935. jitter.y *= tanVertFov / context.screenHeight;
  936. float left = jitter.x + lTan;
  937. float right = jitter.x + rTan;
  938. float top = jitter.y + tTan;
  939. float bottom = jitter.y + bTan;
  940. var jitteredMatrix = new Matrix4x4();
  941. jitteredMatrix[0, 0] = 2f / (right - left);
  942. jitteredMatrix[0, 1] = 0f;
  943. jitteredMatrix[0, 2] = (right + left) / (right - left);
  944. jitteredMatrix[0, 3] = 0f;
  945. jitteredMatrix[1, 0] = 0f;
  946. jitteredMatrix[1, 1] = 2f / (top - bottom);
  947. jitteredMatrix[1, 2] = (top + bottom) / (top - bottom);
  948. jitteredMatrix[1, 3] = 0f;
  949. jitteredMatrix[2, 0] = 0f;
  950. jitteredMatrix[2, 1] = 0f;
  951. jitteredMatrix[2, 2] = origProj[2, 2];
  952. jitteredMatrix[2, 3] = origProj[2, 3];
  953. jitteredMatrix[3, 0] = 0f;
  954. jitteredMatrix[3, 1] = 0f;
  955. jitteredMatrix[3, 2] = -1f;
  956. jitteredMatrix[3, 3] = 0f;
  957. return jitteredMatrix;
  958. #endif
  959. }
  960. #endregion
  961. #region Reflection
  962. static IEnumerable<Type> m_AssemblyTypes;
  963. /// <summary>
  964. /// Gets all currently available assembly types.
  965. /// </summary>
  966. /// <returns>A list of all currently available assembly types</returns>
  967. /// <remarks>
  968. /// This method is slow and should be use with extreme caution.
  969. /// </remarks>
  970. public static IEnumerable<Type> GetAllAssemblyTypes()
  971. {
  972. if (m_AssemblyTypes == null)
  973. {
  974. m_AssemblyTypes = AppDomain.CurrentDomain.GetAssemblies()
  975. .SelectMany(t =>
  976. {
  977. // Ugly hack to handle mis-versioned dlls
  978. var innerTypes = new Type[0];
  979. try
  980. {
  981. innerTypes = t.GetTypes();
  982. }
  983. catch { }
  984. return innerTypes;
  985. });
  986. }
  987. return m_AssemblyTypes;
  988. }
  989. /// <summary>
  990. /// Helper method to get the first attribute of type <c>T</c> on a given type.
  991. /// </summary>
  992. /// <typeparam name="T">The attribute type to look for</typeparam>
  993. /// <param name="type">The type to explore</param>
  994. /// <returns>The attribute found</returns>
  995. public static T GetAttribute<T>(this Type type) where T : Attribute
  996. {
  997. Assert.IsTrue(type.IsDefined(typeof(T), false), "Attribute not found");
  998. return (T)type.GetCustomAttributes(typeof(T), false)[0];
  999. }
  1000. /// <summary>
  1001. /// Returns all attributes set on a specific member.
  1002. /// </summary>
  1003. /// <typeparam name="TType">The class type where the member is defined</typeparam>
  1004. /// <typeparam name="TValue">The member type</typeparam>
  1005. /// <param name="expr">An expression path to the member</param>
  1006. /// <returns>An array of attributes</returns>
  1007. /// <remarks>
  1008. /// This method doesn't return inherited attributes, only explicit ones.
  1009. /// </remarks>
  1010. public static Attribute[] GetMemberAttributes<TType, TValue>(Expression<Func<TType, TValue>> expr)
  1011. {
  1012. Expression body = expr;
  1013. if (body is LambdaExpression)
  1014. body = ((LambdaExpression)body).Body;
  1015. switch (body.NodeType)
  1016. {
  1017. case ExpressionType.MemberAccess:
  1018. var fi = (FieldInfo)((MemberExpression)body).Member;
  1019. return fi.GetCustomAttributes(false).Cast<Attribute>().ToArray();
  1020. default:
  1021. throw new InvalidOperationException();
  1022. }
  1023. }
  1024. /// <summary>
  1025. /// Returns a string path from an expression. This is mostly used to retrieve serialized
  1026. /// properties without hardcoding the field path as a string and thus allowing proper
  1027. /// refactoring features.
  1028. /// </summary>
  1029. /// <typeparam name="TType">The class type where the member is defined</typeparam>
  1030. /// <typeparam name="TValue">The member type</typeparam>
  1031. /// <param name="expr">An expression path fo the member</param>
  1032. /// <returns>A string representation of the expression path</returns>
  1033. public static string GetFieldPath<TType, TValue>(Expression<Func<TType, TValue>> expr)
  1034. {
  1035. MemberExpression me;
  1036. switch (expr.Body.NodeType)
  1037. {
  1038. case ExpressionType.MemberAccess:
  1039. me = expr.Body as MemberExpression;
  1040. break;
  1041. default:
  1042. throw new InvalidOperationException();
  1043. }
  1044. var members = new List<string>();
  1045. while (me != null)
  1046. {
  1047. members.Add(me.Member.Name);
  1048. me = me.Expression as MemberExpression;
  1049. }
  1050. var sb = new StringBuilder();
  1051. for (int i = members.Count - 1; i >= 0; i--)
  1052. {
  1053. sb.Append(members[i]);
  1054. if (i > 0) sb.Append('.');
  1055. }
  1056. return sb.ToString();
  1057. }
  1058. #endregion
  1059. }
  1060. }