Tanoda
GrabArea.cs
Go to the documentation of this file.
1using UnityEngine;
2
4{
8 public static class GrabArea
9 {
13 public enum GrabTextureWrapMode
14 {
15 Clamp,
16 Repeat,
17 Clip
18 }
19
20 #region PrivateField
21
22 private const string GRAB_AREA_MATERIAL = "Es.InkPainter.Effective.GrabArea";
23 private const string CLIP = "_ClipTex";
24 private const string TARGET = "_TargetTex";
25 private const string CLIP_SCALE = "_ClipScale";
26 private const string CLIP_UV = "_ClipUV";
27 private const string ROTATE = "_Rotate";
28
29 private const string WM_CLAMP = "WRAP_MODE_CLAMP";
30 private const string WM_REPEAT = "WRAP_MODE_REPEAT";
31 private const string WM_CLIP = "WRAP_MODE_CLIP";
32
33 private const string ALPHA_REPLACE = "ALPHA_REPLACE";
34 private const string ALPHA_NOT_REPLACE = "ALPHA_NOT_REPLACE";
35
36 private static Material grabAreaMaterial;
37
38 #endregion PrivateField
39
40 #region PublicMethod
41
53 public static void Clip(Texture clipTexture, float clipScale, Texture grabTargetTexture, Vector2 targetUV,
54 float rotateAngle, GrabTextureWrapMode wrapMode, RenderTexture dst, bool replaceAlpha = true)
55 {
56 if (grabAreaMaterial == null)
57 InitGrabAreaMaterial();
58 SetGrabAreaProperty(clipTexture, clipScale, grabTargetTexture, targetUV, rotateAngle, wrapMode,
59 replaceAlpha);
60 var tmp = RenderTexture.GetTemporary(clipTexture.width, clipTexture.height, 0);
61 Graphics.Blit(clipTexture, tmp, grabAreaMaterial);
62 Graphics.Blit(tmp, dst);
63 RenderTexture.ReleaseTemporary(tmp);
64 }
65
66 #endregion PublicMethod
67
68 #region PrivateMethod
69
73 private static void InitGrabAreaMaterial()
74 {
75 grabAreaMaterial = new Material(Resources.Load<Material>(GRAB_AREA_MATERIAL));
76 }
77
87 private static void SetGrabAreaProperty(Texture clip, float clipScale, Texture grabTarget, Vector2 targetUV,
88 float rotateAngle, GrabTextureWrapMode wrapMpde, bool replaceAlpha)
89 {
90 grabAreaMaterial.SetTexture(CLIP, clip);
91 grabAreaMaterial.SetTexture(TARGET, grabTarget);
92 grabAreaMaterial.SetFloat(CLIP_SCALE, clipScale);
93 grabAreaMaterial.SetFloat(ROTATE, rotateAngle);
94 grabAreaMaterial.SetVector(CLIP_UV, targetUV);
95
96 foreach (var key in grabAreaMaterial.shaderKeywords)
97 grabAreaMaterial.DisableKeyword(key);
98 switch (wrapMpde)
99 {
100 case GrabTextureWrapMode.Clamp:
101 grabAreaMaterial.EnableKeyword(WM_CLAMP);
102 break;
103
104 case GrabTextureWrapMode.Repeat:
105 grabAreaMaterial.EnableKeyword(WM_REPEAT);
106 break;
107
108 case GrabTextureWrapMode.Clip:
109 grabAreaMaterial.EnableKeyword(WM_CLIP);
110 break;
111
112 default:
113 break;
114 }
115
116 switch (replaceAlpha)
117 {
118 case true:
119 grabAreaMaterial.EnableKeyword(ALPHA_REPLACE);
120 break;
121 case false:
122 grabAreaMaterial.EnableKeyword(ALPHA_NOT_REPLACE);
123 break;
124 }
125 }
126
127 #endregion PrivateMethod
128 }
129}