OutlineEffect.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. // Copyright (c) 2015 José Guerreiro. All rights reserved.
  3. //
  4. // MIT license, see http://www.opensource.org/licenses/mit-license.php
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. */
  24. using UnityEngine;
  25. using System.Collections.Generic;
  26. using UnityEngine.Rendering;
  27. //using UnityEngine.VR;
  28. namespace cakeslice
  29. {
  30. [DisallowMultipleComponent]
  31. [RequireComponent(typeof(Camera))]
  32. /* [ExecuteInEditMode] */
  33. public class OutlineEffect : MonoBehaviour
  34. {
  35. /* #if UNITY_EDITOR
  36. private void OnValidate()
  37. {
  38. CreateMaterialsIfNeeded();
  39. }
  40. #endif */
  41. public static OutlineEffect Instance { get; private set; }
  42. private readonly LinkedSet<Outline> outlines = new LinkedSet<Outline>();
  43. [Range(1.0f, 6.0f)]
  44. public float lineThickness = 1.25f;
  45. [Range(0, 10)]
  46. public float lineIntensity = .5f;
  47. [Range(0, 1)]
  48. public float fillAmount = 0.2f;
  49. public Color lineColor0 = Color.red;
  50. public Color lineColor1 = Color.green;
  51. public Color lineColor2 = Color.blue;
  52. public bool additiveRendering = false;
  53. public bool backfaceCulling = true;
  54. public Color fillColor = Color.blue;
  55. public bool useFillColor = false;
  56. [Header("These settings can affect performance!")]
  57. public bool cornerOutlines = false;
  58. public bool addLinesBetweenColors = false;
  59. [Header("Advanced settings")]
  60. public bool scaleWithScreenSize = true;
  61. [Range(0.0f, 1.0f)]
  62. public float alphaCutoff = .5f;
  63. public bool flipY = false;
  64. public Camera sourceCamera;
  65. public bool autoEnableOutlines = false;
  66. [HideInInspector]
  67. public Camera outlineCamera;
  68. Material outline1Material;
  69. Material outline2Material;
  70. Material outline3Material;
  71. Material outlineEraseMaterial;
  72. Shader outlineShader;
  73. Shader outlineBufferShader;
  74. [HideInInspector]
  75. public Material outlineShaderMaterial;
  76. [HideInInspector]
  77. public RenderTexture renderTexture;
  78. [HideInInspector]
  79. public RenderTexture extraRenderTexture;
  80. CommandBuffer commandBuffer;
  81. Material GetMaterialFromID(int ID)
  82. {
  83. if (ID == 0)
  84. return outline1Material;
  85. else if (ID == 1)
  86. return outline2Material;
  87. else if (ID == 2)
  88. return outline3Material;
  89. else
  90. return outline1Material;
  91. }
  92. List<Material> materialBuffer = new List<Material>();
  93. Material CreateMaterial(Color emissionColor)
  94. {
  95. Material m = new Material(outlineBufferShader);
  96. m.SetColor("_Color", emissionColor);
  97. m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
  98. m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
  99. m.SetInt("_ZWrite", 0);
  100. m.DisableKeyword("_ALPHATEST_ON");
  101. m.EnableKeyword("_ALPHABLEND_ON");
  102. m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
  103. m.renderQueue = 3000;
  104. return m;
  105. }
  106. private void Awake()
  107. {
  108. if (Instance != null)
  109. {
  110. Destroy(this);
  111. throw new System.Exception("you can only have one outline camera in the scene");
  112. }
  113. Instance = this;
  114. }
  115. void Start()
  116. {
  117. CreateMaterialsIfNeeded();
  118. UpdateMaterialsPublicProperties();
  119. if (sourceCamera == null)
  120. {
  121. sourceCamera = GetComponent<Camera>();
  122. if (sourceCamera == null)
  123. sourceCamera = Camera.main;
  124. }
  125. if (outlineCamera == null)
  126. {
  127. foreach (Camera c in GetComponentsInChildren<Camera>())
  128. {
  129. if (c.name == "Outline Camera")
  130. {
  131. outlineCamera = c;
  132. c.enabled = false;
  133. break;
  134. }
  135. }
  136. if (outlineCamera == null)
  137. {
  138. GameObject cameraGameObject = new GameObject("Outline Camera");
  139. cameraGameObject.transform.parent = sourceCamera.transform;
  140. outlineCamera = cameraGameObject.AddComponent<Camera>();
  141. outlineCamera.enabled = false;
  142. }
  143. }
  144. if (renderTexture != null)
  145. renderTexture.Release();
  146. if (extraRenderTexture != null)
  147. renderTexture.Release();
  148. renderTexture = new RenderTexture(sourceCamera.pixelWidth, sourceCamera.pixelHeight, 16, RenderTextureFormat.Default);
  149. extraRenderTexture = new RenderTexture(sourceCamera.pixelWidth, sourceCamera.pixelHeight, 16, RenderTextureFormat.Default);
  150. UpdateOutlineCameraFromSource();
  151. commandBuffer = new CommandBuffer();
  152. outlineCamera.AddCommandBuffer(CameraEvent.BeforeImageEffects, commandBuffer);
  153. }
  154. bool RenderTheNextFrame;
  155. public void OnPreRender()
  156. {
  157. if (commandBuffer == null)
  158. return;
  159. // The first frame during which there are no outlines, we still need to render
  160. // to clear out any outlines that were being rendered on the previous frame
  161. if (outlines.Count == 0)
  162. {
  163. if (!RenderTheNextFrame)
  164. return;
  165. RenderTheNextFrame = false;
  166. }
  167. else
  168. {
  169. RenderTheNextFrame = true;
  170. }
  171. CreateMaterialsIfNeeded();
  172. if (renderTexture == null || renderTexture.width != sourceCamera.pixelWidth || renderTexture.height != sourceCamera.pixelHeight)
  173. {
  174. if (renderTexture != null)
  175. renderTexture.Release();
  176. if (extraRenderTexture != null)
  177. renderTexture.Release();
  178. renderTexture = new RenderTexture(sourceCamera.pixelWidth, sourceCamera.pixelHeight, 16, RenderTextureFormat.Default);
  179. extraRenderTexture = new RenderTexture(sourceCamera.pixelWidth, sourceCamera.pixelHeight, 16, RenderTextureFormat.Default);
  180. outlineCamera.targetTexture = renderTexture;
  181. }
  182. UpdateMaterialsPublicProperties();
  183. UpdateOutlineCameraFromSource();
  184. outlineCamera.targetTexture = renderTexture;
  185. commandBuffer.SetRenderTarget(renderTexture);
  186. commandBuffer.Clear();
  187. foreach (Outline outline in outlines)
  188. {
  189. LayerMask l = sourceCamera.cullingMask;
  190. if (outline != null && l == (l | (1 << outline.gameObject.layer)))
  191. {
  192. for (int v = 0; v < outline.SharedMaterials.Length; v++)
  193. {
  194. Material m = null;
  195. if (outline.SharedMaterials[v].HasProperty("_MainTex") && outline.SharedMaterials[v].mainTexture != null && outline.SharedMaterials[v])
  196. {
  197. foreach (Material g in materialBuffer)
  198. {
  199. if (g.mainTexture == outline.SharedMaterials[v].mainTexture)
  200. {
  201. if (outline.eraseRenderer && g.color == outlineEraseMaterial.color)
  202. m = g;
  203. else if (!outline.eraseRenderer && g.color == GetMaterialFromID(outline.color).color)
  204. m = g;
  205. }
  206. }
  207. if (m == null)
  208. {
  209. if (outline.eraseRenderer)
  210. m = new Material(outlineEraseMaterial);
  211. else
  212. m = new Material(GetMaterialFromID(outline.color));
  213. m.mainTexture = outline.SharedMaterials[v].mainTexture;
  214. materialBuffer.Add(m);
  215. }
  216. }
  217. else
  218. {
  219. if (outline.eraseRenderer)
  220. m = outlineEraseMaterial;
  221. else
  222. m = GetMaterialFromID(outline.color);
  223. }
  224. if (backfaceCulling)
  225. m.SetInt("_Culling", (int)UnityEngine.Rendering.CullMode.Back);
  226. else
  227. m.SetInt("_Culling", (int)UnityEngine.Rendering.CullMode.Off);
  228. MeshFilter mL = outline.MeshFilter;
  229. SkinnedMeshRenderer sMR = outline.SkinnedMeshRenderer;
  230. SpriteRenderer sR = outline.SpriteRenderer;
  231. if (mL)
  232. {
  233. if (mL.sharedMesh != null)
  234. {
  235. if (v < mL.sharedMesh.subMeshCount)
  236. commandBuffer.DrawRenderer(outline.Renderer, m, v, 0);
  237. }
  238. }
  239. else if (sMR)
  240. {
  241. if (sMR.sharedMesh != null)
  242. {
  243. if (v < sMR.sharedMesh.subMeshCount)
  244. commandBuffer.DrawRenderer(outline.Renderer, m, v, 0);
  245. }
  246. }
  247. else if (sR)
  248. {
  249. commandBuffer.DrawRenderer(outline.Renderer, m, v, 0);
  250. }
  251. }
  252. }
  253. }
  254. outlineCamera.Render();
  255. }
  256. private void OnEnable()
  257. {
  258. Outline[] o = FindObjectsOfType<Outline>();
  259. if (autoEnableOutlines)
  260. {
  261. foreach (Outline oL in o)
  262. {
  263. oL.enabled = false;
  264. oL.enabled = true;
  265. }
  266. }
  267. else
  268. {
  269. foreach (Outline oL in o)
  270. {
  271. if (!outlines.Contains(oL))
  272. outlines.Add(oL);
  273. }
  274. }
  275. }
  276. void OnDestroy()
  277. {
  278. if (renderTexture != null)
  279. renderTexture.Release();
  280. if (extraRenderTexture != null)
  281. extraRenderTexture.Release();
  282. DestroyMaterials();
  283. }
  284. [ImageEffectOpaque]
  285. void OnRenderImage(RenderTexture source, RenderTexture destination)
  286. {
  287. if (outlineShaderMaterial != null)
  288. {
  289. outlineShaderMaterial.SetTexture("_OutlineSource", renderTexture);
  290. if (addLinesBetweenColors)
  291. {
  292. Graphics.Blit(source, extraRenderTexture, outlineShaderMaterial, 0);
  293. outlineShaderMaterial.SetTexture("_OutlineSource", extraRenderTexture);
  294. }
  295. Graphics.Blit(source, destination, outlineShaderMaterial, 1);
  296. }
  297. }
  298. private void CreateMaterialsIfNeeded()
  299. {
  300. if (outlineShader == null)
  301. outlineShader = Resources.Load<Shader>("OutlineShader");
  302. if (outlineBufferShader == null)
  303. {
  304. outlineBufferShader = Resources.Load<Shader>("OutlineBufferShader");
  305. }
  306. if (outlineShaderMaterial == null)
  307. {
  308. outlineShaderMaterial = new Material(outlineShader);
  309. outlineShaderMaterial.hideFlags = HideFlags.HideAndDontSave;
  310. UpdateMaterialsPublicProperties();
  311. }
  312. if (outlineEraseMaterial == null)
  313. outlineEraseMaterial = CreateMaterial(new Color(0, 0, 0, 0));
  314. if (outline1Material == null)
  315. outline1Material = CreateMaterial(new Color(1, 0, 0, 0));
  316. if (outline2Material == null)
  317. outline2Material = CreateMaterial(new Color(0, 1, 0, 0));
  318. if (outline3Material == null)
  319. outline3Material = CreateMaterial(new Color(0, 0, 1, 0));
  320. }
  321. private void DestroyMaterials()
  322. {
  323. foreach (Material m in materialBuffer)
  324. DestroyImmediate(m);
  325. materialBuffer.Clear();
  326. DestroyImmediate(outlineShaderMaterial);
  327. DestroyImmediate(outlineEraseMaterial);
  328. DestroyImmediate(outline1Material);
  329. DestroyImmediate(outline2Material);
  330. DestroyImmediate(outline3Material);
  331. outlineShader = null;
  332. outlineBufferShader = null;
  333. outlineShaderMaterial = null;
  334. outlineEraseMaterial = null;
  335. outline1Material = null;
  336. outline2Material = null;
  337. outline3Material = null;
  338. }
  339. public void UpdateMaterialsPublicProperties()
  340. {
  341. if (outlineShaderMaterial)
  342. {
  343. float scalingFactor = 1;
  344. if (scaleWithScreenSize)
  345. {
  346. // If Screen.height gets bigger, outlines gets thicker
  347. scalingFactor = Screen.height / 360.0f;
  348. }
  349. // If scaling is too small (height less than 360 pixels), make sure you still render the outlines, but render them with 1 thickness
  350. if (scaleWithScreenSize && scalingFactor < 1)
  351. {
  352. if (UnityEngine.XR.XRSettings.isDeviceActive && sourceCamera.stereoTargetEye != StereoTargetEyeMask.None)
  353. {
  354. outlineShaderMaterial.SetFloat("_LineThicknessX", (1 / 1000.0f) * (1.0f / UnityEngine.XR.XRSettings.eyeTextureWidth) * 1000.0f);
  355. outlineShaderMaterial.SetFloat("_LineThicknessY", (1 / 1000.0f) * (1.0f / UnityEngine.XR.XRSettings.eyeTextureHeight) * 1000.0f);
  356. }
  357. else
  358. {
  359. outlineShaderMaterial.SetFloat("_LineThicknessX", (1 / 1000.0f) * (1.0f / Screen.width) * 1000.0f);
  360. outlineShaderMaterial.SetFloat("_LineThicknessY", (1 / 1000.0f) * (1.0f / Screen.height) * 1000.0f);
  361. }
  362. }
  363. else
  364. {
  365. if (UnityEngine.XR.XRSettings.isDeviceActive && sourceCamera.stereoTargetEye != StereoTargetEyeMask.None)
  366. {
  367. outlineShaderMaterial.SetFloat("_LineThicknessX", scalingFactor * (lineThickness / 1000.0f) * (1.0f / UnityEngine.XR.XRSettings.eyeTextureWidth) * 1000.0f);
  368. outlineShaderMaterial.SetFloat("_LineThicknessY", scalingFactor * (lineThickness / 1000.0f) * (1.0f / UnityEngine.XR.XRSettings.eyeTextureHeight) * 1000.0f);
  369. }
  370. else
  371. {
  372. outlineShaderMaterial.SetFloat("_LineThicknessX", scalingFactor * (lineThickness / 1000.0f) * (1.0f / Screen.width) * 1000.0f);
  373. outlineShaderMaterial.SetFloat("_LineThicknessY", scalingFactor * (lineThickness / 1000.0f) * (1.0f / Screen.height) * 1000.0f);
  374. }
  375. }
  376. outlineShaderMaterial.SetFloat("_LineIntensity", lineIntensity);
  377. outlineShaderMaterial.SetFloat("_FillAmount", fillAmount);
  378. outlineShaderMaterial.SetColor("_FillColor", fillColor);
  379. outlineShaderMaterial.SetFloat("_UseFillColor", useFillColor ? 1 : 0);
  380. outlineShaderMaterial.SetColor("_LineColor1", lineColor0 * lineColor0);
  381. outlineShaderMaterial.SetColor("_LineColor2", lineColor1 * lineColor1);
  382. outlineShaderMaterial.SetColor("_LineColor3", lineColor2 * lineColor2);
  383. if (flipY)
  384. outlineShaderMaterial.SetInt("_FlipY", 1);
  385. else
  386. outlineShaderMaterial.SetInt("_FlipY", 0);
  387. if (!additiveRendering)
  388. outlineShaderMaterial.SetInt("_Dark", 1);
  389. else
  390. outlineShaderMaterial.SetInt("_Dark", 0);
  391. if (cornerOutlines)
  392. outlineShaderMaterial.SetInt("_CornerOutlines", 1);
  393. else
  394. outlineShaderMaterial.SetInt("_CornerOutlines", 0);
  395. Shader.SetGlobalFloat("_OutlineAlphaCutoff", alphaCutoff);
  396. }
  397. }
  398. void UpdateOutlineCameraFromSource()
  399. {
  400. outlineCamera.CopyFrom(sourceCamera);
  401. outlineCamera.renderingPath = RenderingPath.Forward;
  402. outlineCamera.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 0.0f);
  403. outlineCamera.clearFlags = CameraClearFlags.SolidColor;
  404. outlineCamera.rect = new Rect(0, 0, 1, 1);
  405. outlineCamera.cullingMask = 0;
  406. outlineCamera.targetTexture = renderTexture;
  407. outlineCamera.enabled = false;
  408. #if UNITY_5_6_OR_NEWER
  409. outlineCamera.allowHDR = false;
  410. #else
  411. outlineCamera.hdr = false;
  412. #endif
  413. }
  414. public void AddOutline(Outline outline)
  415. => outlines.Add(outline);
  416. public void RemoveOutline(Outline outline)
  417. => outlines.Remove(outline);
  418. }
  419. }