EdgeDetection.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using UnityEngine;
  3. namespace UnityStandardAssets.ImageEffects
  4. {
  5. [ExecuteInEditMode]
  6. [RequireComponent (typeof (Camera))]
  7. [AddComponentMenu ("Image Effects/Edge Detection/Edge Detection")]
  8. public class EdgeDetection : PostEffectsBase
  9. {
  10. public enum EdgeDetectMode
  11. {
  12. TriangleDepthNormals = 0,
  13. RobertsCrossDepthNormals = 1,
  14. SobelDepth = 2,
  15. SobelDepthThin = 3,
  16. TriangleLuminance = 4,
  17. }
  18. public EdgeDetectMode mode = EdgeDetectMode.SobelDepthThin;
  19. public float sensitivityDepth = 1.0f;
  20. public float sensitivityNormals = 1.0f;
  21. public float lumThreshold = 0.2f;
  22. public float edgeExp = 1.0f;
  23. public float sampleDist = 1.0f;
  24. public float edgesOnly = 0.0f;
  25. public Color edgesOnlyBgColor = Color.white;
  26. public Shader edgeDetectShader;
  27. private Material edgeDetectMaterial = null;
  28. private EdgeDetectMode oldMode = EdgeDetectMode.SobelDepthThin;
  29. public override bool CheckResources ()
  30. {
  31. CheckSupport (true);
  32. edgeDetectMaterial = CheckShaderAndCreateMaterial (edgeDetectShader,edgeDetectMaterial);
  33. if (mode != oldMode)
  34. SetCameraFlag ();
  35. oldMode = mode;
  36. if (!isSupported)
  37. ReportAutoDisable ();
  38. return isSupported;
  39. }
  40. new void Start ()
  41. {
  42. oldMode = mode;
  43. }
  44. void SetCameraFlag ()
  45. {
  46. if (mode == EdgeDetectMode.SobelDepth || mode == EdgeDetectMode.SobelDepthThin)
  47. GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
  48. else if (mode == EdgeDetectMode.TriangleDepthNormals || mode == EdgeDetectMode.RobertsCrossDepthNormals)
  49. GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals;
  50. }
  51. void OnEnable ()
  52. {
  53. SetCameraFlag();
  54. }
  55. [ImageEffectOpaque]
  56. void OnRenderImage (RenderTexture source, RenderTexture destination)
  57. {
  58. if (CheckResources () == false)
  59. {
  60. Graphics.Blit (source, destination);
  61. return;
  62. }
  63. Vector2 sensitivity = new Vector2 (sensitivityDepth, sensitivityNormals);
  64. edgeDetectMaterial.SetVector ("_Sensitivity", new Vector4 (sensitivity.x, sensitivity.y, 1.0f, sensitivity.y));
  65. edgeDetectMaterial.SetFloat ("_BgFade", edgesOnly);
  66. edgeDetectMaterial.SetFloat ("_SampleDistance", sampleDist);
  67. edgeDetectMaterial.SetVector ("_BgColor", edgesOnlyBgColor);
  68. edgeDetectMaterial.SetFloat ("_Exponent", edgeExp);
  69. edgeDetectMaterial.SetFloat ("_Threshold", lumThreshold);
  70. Graphics.Blit (source, destination, edgeDetectMaterial, (int) mode);
  71. }
  72. }
  73. }