OutlineRenderer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. // Copyright (C) 2019-2021 Alexander Bogarsukov. All rights reserved.
  2. // See the LICENSE.md file in the project root for more information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. using UnityEngine;
  7. using UnityEngine.Rendering;
  8. using UnityEngine.XR;
  9. namespace UnityFx.Outline
  10. {
  11. /// <summary>
  12. /// Helper class for outline rendering with <see cref="CommandBuffer"/>.
  13. /// </summary>
  14. /// <remarks>
  15. /// <para>The class can be used on its own or as part of a higher level systems. It is used
  16. /// by higher level outline implementations (<see cref="OutlineEffect"/> and
  17. /// <see cref="OutlineBehaviour"/>). It is fully compatible with Unity post processing stack as well.</para>
  18. /// <para>The class implements <see cref="IDisposable"/> to be used inside <see langword="using"/>
  19. /// block as shown in the code samples. Disposing <see cref="OutlineRenderer"/> does not dispose
  20. /// the corresponding <see cref="CommandBuffer"/>.</para>
  21. /// <para>Command buffer is not cleared before rendering. It is user responsibility to do so if needed.</para>
  22. /// </remarks>
  23. /// <example>
  24. /// var commandBuffer = new CommandBuffer();
  25. ///
  26. /// using (var renderer = new OutlineRenderer(commandBuffer, resources))
  27. /// {
  28. /// renderer.Render(renderers, settings);
  29. /// }
  30. ///
  31. /// camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, commandBuffer);
  32. /// </example>
  33. /// <seealso cref="OutlineResources"/>
  34. public readonly struct OutlineRenderer : IDisposable
  35. {
  36. #region data
  37. private readonly TextureDimension _rtDimention;
  38. private readonly RenderTargetIdentifier _rt;
  39. private readonly RenderTargetIdentifier _depth;
  40. private readonly CommandBuffer _commandBuffer;
  41. private readonly OutlineResources _resources;
  42. #endregion
  43. #region interface
  44. /// <summary>
  45. /// A default <see cref="CameraEvent"/> outline rendering should be assosiated with.
  46. /// </summary>
  47. public const CameraEvent RenderEvent = CameraEvent.AfterSkybox;
  48. /// <summary>
  49. /// A default render texture format for the outline effect.
  50. /// </summary>
  51. public const RenderTextureFormat RtFormat = RenderTextureFormat.R8;
  52. /// <summary>
  53. /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
  54. /// </summary>
  55. /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
  56. /// <param name="resources">Outline resources.</param>
  57. /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
  58. public OutlineRenderer(CommandBuffer cmd, OutlineResources resources)
  59. : this(cmd, resources, BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.Depth, Vector2Int.zero)
  60. {
  61. }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
  64. /// </summary>
  65. /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
  66. /// <param name="resources">Outline resources.</param>
  67. /// <param name="renderingPath">The rendering path of target camera (<see cref="Camera.actualRenderingPath"/>).</param>
  68. /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
  69. public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderingPath renderingPath)
  70. : this(cmd, resources, BuiltinRenderTextureType.CameraTarget, GetBuiltinDepth(renderingPath), Vector2Int.zero)
  71. {
  72. }
  73. /// <summary>
  74. /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
  75. /// </summary>
  76. /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
  77. /// <param name="resources">Outline resources.</param>
  78. /// <param name="dst">Render target.</param>
  79. /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
  80. public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst)
  81. : this(cmd, resources, dst, BuiltinRenderTextureType.Depth, Vector2Int.zero)
  82. {
  83. }
  84. /// <summary>
  85. /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
  86. /// </summary>
  87. /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
  88. /// <param name="dst">Render target.</param>
  89. /// <param name="renderingPath">The rendering path of target camera (<see cref="Camera.actualRenderingPath"/>).</param>
  90. /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
  91. public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst, RenderingPath renderingPath, Vector2Int rtSize)
  92. : this(cmd, resources, dst, GetBuiltinDepth(renderingPath), rtSize)
  93. {
  94. }
  95. /// <summary>
  96. /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
  97. /// </summary>
  98. /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
  99. /// <param name="resources">Outline resources.</param>
  100. /// <param name="dst">Render target.</param>
  101. /// <param name="depth">Depth dexture to use.</param>
  102. /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
  103. public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst, RenderTargetIdentifier depth, Vector2Int rtSize)
  104. {
  105. if (cmd is null)
  106. {
  107. throw new ArgumentNullException(nameof(cmd));
  108. }
  109. if (resources is null)
  110. {
  111. throw new ArgumentNullException(nameof(resources));
  112. }
  113. if (rtSize.x <= 0)
  114. {
  115. rtSize.x = -1;
  116. }
  117. if (rtSize.y <= 0)
  118. {
  119. rtSize.y = -1;
  120. }
  121. if (XRSettings.enabled)
  122. {
  123. var rtDesc = XRSettings.eyeTextureDesc;
  124. rtDesc.shadowSamplingMode = ShadowSamplingMode.None;
  125. rtDesc.depthBufferBits = 0;
  126. rtDesc.colorFormat = RtFormat;
  127. cmd.GetTemporaryRT(resources.MaskTexId, rtDesc, FilterMode.Bilinear);
  128. cmd.GetTemporaryRT(resources.TempTexId, rtDesc, FilterMode.Bilinear);
  129. _rtDimention = rtDesc.dimension;
  130. }
  131. else
  132. {
  133. cmd.GetTemporaryRT(resources.MaskTexId, rtSize.x, rtSize.y, 0, FilterMode.Bilinear, RtFormat);
  134. cmd.GetTemporaryRT(resources.TempTexId, rtSize.x, rtSize.y, 0, FilterMode.Bilinear, RtFormat);
  135. _rtDimention = TextureDimension.Tex2D;
  136. }
  137. _rt = dst;
  138. _depth = depth;
  139. _commandBuffer = cmd;
  140. _resources = resources;
  141. }
  142. /// <summary>
  143. /// Initializes a new instance of the <see cref="OutlineRenderer"/> struct.
  144. /// </summary>
  145. /// <param name="cmd">A <see cref="CommandBuffer"/> to render the effect to. It should be cleared manually (if needed) before passing to this method.</param>
  146. /// <param name="resources">Outline resources.</param>
  147. /// <param name="dst">Render target.</param>
  148. /// <param name="depth">Depth dexture to use.</param>
  149. /// <param name="rtDesc">Render texture decsriptor.</param>
  150. /// <exception cref="ArgumentNullException">Thrown if <paramref name="cmd"/> is <see langword="null"/>.</exception>
  151. public OutlineRenderer(CommandBuffer cmd, OutlineResources resources, RenderTargetIdentifier dst, RenderTargetIdentifier depth, RenderTextureDescriptor rtDesc)
  152. {
  153. if (cmd is null)
  154. {
  155. throw new ArgumentNullException(nameof(cmd));
  156. }
  157. if (resources is null)
  158. {
  159. throw new ArgumentNullException(nameof(resources));
  160. }
  161. if (rtDesc.width <= 0)
  162. {
  163. rtDesc.width = -1;
  164. }
  165. if (rtDesc.height <= 0)
  166. {
  167. rtDesc.height = -1;
  168. }
  169. if (rtDesc.dimension == TextureDimension.None || rtDesc.dimension == TextureDimension.Unknown)
  170. {
  171. rtDesc.dimension = TextureDimension.Tex2D;
  172. }
  173. rtDesc.shadowSamplingMode = ShadowSamplingMode.None;
  174. rtDesc.depthBufferBits = 0;
  175. rtDesc.colorFormat = RtFormat;
  176. rtDesc.msaaSamples = 1;
  177. cmd.GetTemporaryRT(resources.MaskTexId, rtDesc, FilterMode.Bilinear);
  178. cmd.GetTemporaryRT(resources.TempTexId, rtDesc, FilterMode.Bilinear);
  179. _rtDimention = rtDesc.dimension;
  180. _rt = dst;
  181. _depth = depth;
  182. _commandBuffer = cmd;
  183. _resources = resources;
  184. }
  185. /// <summary>
  186. /// Renders outline around a single object.
  187. /// </summary>
  188. /// <param name="obj">An object to be outlined.</param>
  189. /// <seealso cref="Render(IReadOnlyList{OutlineRenderObject})"/>
  190. public void Render(OutlineRenderObject obj)
  191. {
  192. Render(obj.Renderers, obj.OutlineSettings, obj.Tag);
  193. }
  194. /// <summary>
  195. /// Renders outline around multiple <paramref name="objects"/>.
  196. /// </summary>
  197. /// <param name="objects">An object to be outlined.</param>
  198. /// <exception cref="ArgumentNullException">Thrown if <paramref name="objects"/> is <see langword="null"/>.</exception>
  199. /// <seealso cref="Render(OutlineRenderObject)"/>
  200. public void Render(IReadOnlyList<OutlineRenderObject> objects)
  201. {
  202. if (objects is null)
  203. {
  204. throw new ArgumentNullException(nameof(objects));
  205. }
  206. for (var i = 0; i < objects.Count; i++)
  207. {
  208. Render(objects[i]);
  209. }
  210. }
  211. /// <summary>
  212. /// Renders outline around multiple <paramref name="renderers"/>.
  213. /// </summary>
  214. /// <param name="renderers">One or more renderers representing a single object to be outlined.</param>
  215. /// <param name="settings">Outline settings.</param>
  216. /// <param name="sampleName">Optional name of the sample (visible in profiler).</param>
  217. /// <exception cref="ArgumentNullException">Thrown if any of the arguments is <see langword="null"/>.</exception>
  218. /// <seealso cref="Render(Renderer, IOutlineSettings, string)"/>
  219. public void Render(IReadOnlyList<Renderer> renderers, IOutlineSettings settings, string sampleName = null)
  220. {
  221. if (renderers is null)
  222. {
  223. throw new ArgumentNullException(nameof(renderers));
  224. }
  225. if (settings is null)
  226. {
  227. throw new ArgumentNullException(nameof(settings));
  228. }
  229. if (renderers.Count > 0)
  230. {
  231. // NOTE: Remove BeginSample/EndSample for now (https://github.com/Arvtesh/UnityFx.Outline/issues/44).
  232. //if (string.IsNullOrEmpty(sampleName))
  233. //{
  234. // sampleName = renderers[0].name;
  235. //}
  236. //_commandBuffer.BeginSample(sampleName);
  237. {
  238. RenderObjectClear(settings.OutlineRenderMode);
  239. for (var i = 0; i < renderers.Count; ++i)
  240. {
  241. DrawRenderer(renderers[i], settings);
  242. }
  243. RenderOutline(settings);
  244. }
  245. //_commandBuffer.EndSample(sampleName);
  246. }
  247. }
  248. /// <summary>
  249. /// Renders outline around a single <paramref name="renderer"/>.
  250. /// </summary>
  251. /// <param name="renderer">A <see cref="Renderer"/> representing an object to be outlined.</param>
  252. /// <param name="settings">Outline settings.</param>
  253. /// <param name="sampleName">Optional name of the sample (visible in profiler).</param>
  254. /// <exception cref="ArgumentNullException">Thrown if any of the arguments is <see langword="null"/>.</exception>
  255. /// <seealso cref="Render(IReadOnlyList{Renderer}, IOutlineSettings, string)"/>
  256. public void Render(Renderer renderer, IOutlineSettings settings, string sampleName = null)
  257. {
  258. if (renderer is null)
  259. {
  260. throw new ArgumentNullException(nameof(renderer));
  261. }
  262. if (settings is null)
  263. {
  264. throw new ArgumentNullException(nameof(settings));
  265. }
  266. // NOTE: Remove BeginSample/EndSample for now (https://github.com/Arvtesh/UnityFx.Outline/issues/44).
  267. //if (string.IsNullOrEmpty(sampleName))
  268. //{
  269. // sampleName = renderer.name;
  270. //}
  271. // NOTE: Remove this for now (https://github.com/Arvtesh/UnityFx.Outline/issues/44).
  272. //_commandBuffer.BeginSample(sampleName);
  273. {
  274. RenderObjectClear(settings.OutlineRenderMode);
  275. DrawRenderer(renderer, settings);
  276. RenderOutline(settings);
  277. }
  278. //_commandBuffer.EndSample(sampleName);
  279. }
  280. /// <summary>
  281. /// Specialized render target setup. Do not use if not sure.
  282. /// </summary>
  283. public void RenderObjectClear(OutlineRenderFlags flags)
  284. {
  285. // NOTE: Use the camera depth buffer when rendering the mask. Shader only reads from the depth buffer (ZWrite Off).
  286. if ((flags & OutlineRenderFlags.EnableDepthTesting) != 0)
  287. {
  288. if (_rtDimention == TextureDimension.Tex2DArray)
  289. {
  290. // NOTE: Need to use this SetRenderTarget overload for XR, otherwise single pass instanced rendering does not function properly.
  291. _commandBuffer.SetRenderTarget(_resources.MaskTex, _depth, 0, CubemapFace.Unknown, -1);
  292. }
  293. else
  294. {
  295. _commandBuffer.SetRenderTarget(_resources.MaskTex, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, _depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.DontCare);
  296. }
  297. }
  298. else
  299. {
  300. if (_rtDimention == TextureDimension.Tex2DArray)
  301. {
  302. _commandBuffer.SetRenderTarget(_resources.MaskTex, 0, CubemapFace.Unknown, -1);
  303. }
  304. else
  305. {
  306. _commandBuffer.SetRenderTarget(_resources.MaskTex, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  307. }
  308. }
  309. _commandBuffer.ClearRenderTarget(false, true, Color.clear);
  310. }
  311. /// <summary>
  312. /// Renders outline. Do not use if not sure.
  313. /// </summary>
  314. public void RenderOutline(IOutlineSettings settings)
  315. {
  316. var mat = _resources.OutlineMaterial;
  317. var props = _resources.GetProperties(settings);
  318. _commandBuffer.SetGlobalFloatArray(_resources.GaussSamplesId, _resources.GetGaussSamples(settings.OutlineWidth));
  319. if (_rtDimention == TextureDimension.Tex2DArray)
  320. {
  321. // HPass
  322. _commandBuffer.SetRenderTarget(_resources.TempTex, 0, CubemapFace.Unknown, -1);
  323. Blit(_resources.MaskTex, OutlineResources.OutlineShaderHPassId, mat, props);
  324. // VPassBlend
  325. _commandBuffer.SetRenderTarget(_rt, 0, CubemapFace.Unknown, -1);
  326. Blit(_resources.TempTex, OutlineResources.OutlineShaderVPassId, mat, props);
  327. }
  328. else
  329. {
  330. // HPass
  331. _commandBuffer.SetRenderTarget(_resources.TempTex, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
  332. Blit(_resources.MaskTex, OutlineResources.OutlineShaderHPassId, mat, props);
  333. // VPassBlend
  334. _commandBuffer.SetRenderTarget(_rt, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
  335. Blit(_resources.TempTex, OutlineResources.OutlineShaderVPassId, mat, props);
  336. }
  337. }
  338. #endregion
  339. #region IDisposable
  340. /// <summary>
  341. /// Finalizes the effect rendering and releases temporary textures used. Should only be called once.
  342. /// </summary>
  343. public void Dispose()
  344. {
  345. _commandBuffer.ReleaseTemporaryRT(_resources.TempTexId);
  346. _commandBuffer.ReleaseTemporaryRT(_resources.MaskTexId);
  347. }
  348. #endregion
  349. #region implementation
  350. private void DrawRenderer(Renderer renderer, IOutlineSettings settings)
  351. {
  352. if (renderer && renderer.enabled && renderer.isVisible && renderer.gameObject.activeInHierarchy)
  353. {
  354. // NOTE: Accessing Renderer.sharedMaterials triggers GC.Alloc. That's why we use a temporary
  355. // list of materials, cached with the outline resources.
  356. renderer.GetSharedMaterials(_resources.TmpMaterials);
  357. if (_resources.TmpMaterials.Count > 0)
  358. {
  359. if (settings.IsAlphaTestingEnabled())
  360. {
  361. for (var i = 0; i < _resources.TmpMaterials.Count; ++i)
  362. {
  363. var mat = _resources.TmpMaterials[i];
  364. // Use material cutoff value if available.
  365. if (mat.HasProperty(_resources.AlphaCutoffId))
  366. {
  367. _commandBuffer.SetGlobalFloat(_resources.AlphaCutoffId, mat.GetFloat(_resources.AlphaCutoffId));
  368. }
  369. else
  370. {
  371. _commandBuffer.SetGlobalFloat(_resources.AlphaCutoffId, settings.OutlineAlphaCutoff);
  372. }
  373. _commandBuffer.SetGlobalTexture(_resources.MainTexId, _resources.TmpMaterials[i].mainTexture);
  374. _commandBuffer.DrawRenderer(renderer, _resources.RenderMaterial, i, OutlineResources.RenderShaderAlphaTestPassId);
  375. }
  376. }
  377. else
  378. {
  379. for (var i = 0; i < _resources.TmpMaterials.Count; ++i)
  380. {
  381. _commandBuffer.DrawRenderer(renderer, _resources.RenderMaterial, i, OutlineResources.RenderShaderDefaultPassId);
  382. }
  383. }
  384. }
  385. else
  386. {
  387. // NOTE: No materials set for renderer means we should still render outline for it.
  388. _commandBuffer.DrawRenderer(renderer, _resources.RenderMaterial, 0, OutlineResources.RenderShaderDefaultPassId);
  389. }
  390. }
  391. }
  392. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  393. private void Blit(RenderTargetIdentifier src, int shaderPass, Material mat, MaterialPropertyBlock props)
  394. {
  395. // Set source texture as _MainTex to match Blit behavior.
  396. _commandBuffer.SetGlobalTexture(_resources.MainTexId, src);
  397. // NOTE: SystemInfo.graphicsShaderLevel check is not enough sometimes (esp. on mobiles), so there is SystemInfo.supportsInstancing
  398. // check and a flag for forcing DrawMesh.
  399. if (SystemInfo.graphicsShaderLevel >= 35 && SystemInfo.supportsInstancing && !_resources.UseFullscreenTriangleMesh)
  400. {
  401. _commandBuffer.DrawProcedural(Matrix4x4.identity, mat, shaderPass, MeshTopology.Triangles, 3, 1, props);
  402. }
  403. else
  404. {
  405. _commandBuffer.DrawMesh(_resources.FullscreenTriangleMesh, Matrix4x4.identity, mat, 0, shaderPass, props);
  406. }
  407. }
  408. private static RenderTargetIdentifier GetBuiltinDepth(RenderingPath renderingPath)
  409. {
  410. return (renderingPath == RenderingPath.DeferredShading || renderingPath == RenderingPath.DeferredLighting) ? BuiltinRenderTextureType.ResolvedDepth : BuiltinRenderTextureType.Depth;
  411. }
  412. #endregion
  413. }
  414. }