-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathRTUtils.cs
More file actions
331 lines (263 loc) · 11.6 KB
/
RTUtils.cs
File metadata and controls
331 lines (263 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
///
/// RTUtils by Nothke
///
/// RenderTexture utilities for direct drawing meshes, texts and sprites and converting to Texture2D.
/// Requires BlitQuad shader.
///
/// ============================================================================
///
/// MIT License
///
/// Copyright(c) 2021 Ivan Notaroš
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///
/// ============================================================================
///
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
namespace Nothke.Utils
{
public static class RTUtils
{
#region Quad creation
static Mesh quad;
public static Mesh GetQuad()
{
if (quad)
return quad;
Mesh mesh = new Mesh();
float width = 1;
float height = 1;
Vector3[] vertices = new Vector3[4]
{
new Vector3(0, 0, 0),
new Vector3(width, 0, 0),
new Vector3(0, height, 0),
new Vector3(width, height, 0)
};
mesh.vertices = vertices;
int[] tris = new int[6]
{
// lower left triangle
0, 2, 1,
// upper right triangle
2, 3, 1
};
mesh.triangles = tris;
Vector2[] uv = new Vector2[4]
{
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(0, 1),
new Vector2(1, 1)
};
mesh.uv = uv;
quad = mesh;
return quad;
}
static Shader blitShader;
public static Shader GetBlitShader()
{
if (blitShader)
return blitShader;
const string SHADER_NAME = "Sprites/Default";
var shader = Shader.Find(SHADER_NAME);
if (!shader)
Debug.LogError(SHADER_NAME + " shader not found, did you forget to include it in the project settings?");
blitShader = shader;
return blitShader;
}
static Material blitMaterial;
public static Material GetBlitMaterial()
{
if (blitMaterial)
return blitMaterial;
blitMaterial = new Material(GetBlitShader());
return blitMaterial;
}
#endregion
static RenderTexture prevRT;
public static void BeginOrthoRendering(this RenderTexture rt, float zBegin = -100, float zEnd = 100)
{
// Create an orthographic matrix (for 2D rendering)
Matrix4x4 projectionMatrix = Matrix4x4.Ortho(0, 1, 0, 1, zBegin, zEnd);
rt.BeginRendering(projectionMatrix);
}
public static void BeginPixelRendering(this RenderTexture rt, float zBegin = -100, float zEnd = 100)
{
Matrix4x4 projectionMatrix = Matrix4x4.Ortho(0, rt.width, 0, rt.height, zBegin, zEnd);
rt.BeginRendering(projectionMatrix);
}
public static void BeginPerspectiveRendering(
this RenderTexture rt, float fov, in Vector3 position, in Quaternion rotation,
float zNear = 0.01f, float zFar = 1000f)
{
float aspect = (float)rt.width / rt.height;
Matrix4x4 projectionMatrix = Matrix4x4.Perspective(fov, aspect, zNear, zFar);
Matrix4x4 viewMatrix = Matrix4x4.TRS(position, rotation, new Vector3(1, 1, -1));
Matrix4x4 cameraMatrix = (projectionMatrix * viewMatrix.inverse);
rt.BeginRendering(cameraMatrix);
}
public static void BeginRendering(this RenderTexture rt, Matrix4x4 projectionMatrix)
{
// This fixes flickering (by @guycalledfrank)
// (because there's some switching back and forth between cameras, I don't fully understand)
if (Camera.current != null)
projectionMatrix *= Camera.current.worldToCameraMatrix.inverse;
// Remember the current texture and make our own active
prevRT = RenderTexture.active;
RenderTexture.active = rt;
// Push the projection matrix
GL.PushMatrix();
GL.LoadProjectionMatrix(projectionMatrix);
}
public static void EndRendering(this RenderTexture rt)
{
// Pop the projection matrix to set it back to the previous one
GL.PopMatrix();
// Revert culling
GL.invertCulling = false;
// Re-set the RenderTexture to the last used one
RenderTexture.active = prevRT;
}
public static void DrawMesh(this RenderTexture rt, Mesh mesh, Material material, in Matrix4x4 objectMatrix, int pass = 0)
{
bool canRender = material.SetPass(pass);
if (canRender)
Graphics.DrawMeshNow(mesh, objectMatrix);
}
public static void DrawTMPText(this RenderTexture rt, TMP_Text text, in Vector2 position, float size)
{
float aspect = (float)rt.width / rt.height;
Vector3 scale = new Vector3(size, size * aspect, 1);
Matrix4x4 matrix = Matrix4x4.TRS(position, Quaternion.identity, scale);
rt.DrawTMPText(text, matrix);
}
public static void DrawTMPText(this RenderTexture rt, TMP_Text text, in Matrix4x4 matrix)
{
Material material = text.fontSharedMaterial;
rt.DrawMesh(text.mesh, material, matrix);
}
#region Blit once functions
/// <summary>
/// Draws a mesh to render texture.
/// Position is defined in camera view 0-1 space where 0,0 is in bottom left corner.
/// <para>
/// For non-square textures, aspect ratio will be calculated so that the 0-1 space fits in the width.
/// Meaning that, for example, wider than square texture will have larger font size per texture area.
/// </para>
/// </summary>
/// <param name="rt"></param>
/// <param name="text"></param>
/// <param name="pos"></param>
/// <param name="size"></param>
/// <param name="clear"></param>
/// <param name="clearColor"></param>
public static void BlitTMPText(this RenderTexture rt, TMP_Text text, in Vector2 pos, float size,
bool clear = true, Color clearColor = default)
{
float aspect = (float)rt.width / rt.height;
Vector3 scale = new Vector3(size, size * aspect, 1);
Matrix4x4 matrix = Matrix4x4.TRS(pos, Quaternion.identity, scale);
BlitTMPText(rt, text, matrix, clear, clearColor);
}
public static void BlitTMPText(this RenderTexture rt, TMP_Text text, Matrix4x4 objectMatrix,
bool clear = true, Color clearColor = default)
{
Material mat = text.fontSharedMaterial;
BlitMesh(rt, objectMatrix, text.mesh, mat, clear, true, clearColor);
}
/// <summary>
/// Draws a mesh to render texture. The camera space is defined in normalized 0-1 coordinates, near and far planes are -100 and 100.
/// </summary>
/// <param name="objectMatrix">The model-matrix of the object</param>
/// <param name="invertCulling">In case the mesh renders inside-out, toggle this</param>
/// <param name="clear">Clears a texture to clearColor before drawing</param>
public static void BlitMesh(this RenderTexture rt, Matrix4x4 objectMatrix, Mesh mesh, Material material,
bool invertCulling = true, bool clear = true, Color clearColor = default)
{
// Create an orthographic matrix (for 2D rendering)
// You can otherwise use Matrix4x4.Perspective()
Matrix4x4 projectionMatrix = Matrix4x4.Ortho(0, 1, 0, 1, -100, 100);
// This fixes flickering (by @guycalledfrank)
// (because there's some switching back and forth between cameras, I don't fully understand)
if (Camera.current != null)
projectionMatrix *= Camera.current.worldToCameraMatrix.inverse;
// Remember the current texture and set our own as "active".
RenderTexture prevRT = RenderTexture.active;
RenderTexture.active = rt;
// Set material as "active". Without this, Unity editor will freeze.
bool canRender = material.SetPass(0);
// Push the projection matrix
GL.PushMatrix();
GL.LoadProjectionMatrix(projectionMatrix);
// It seems that the faces are in a wrong order, so we need to flip them
GL.invertCulling = invertCulling;
// Clear the texture
if (clear)
GL.Clear(true, true, clearColor);
// Draw the mesh!
if (canRender)
Graphics.DrawMeshNow(mesh, objectMatrix);
// Pop the projection matrix to set it back to the previous one
GL.PopMatrix();
// Revert culling
GL.invertCulling = false;
// Re-set the RenderTexture to the last used one
RenderTexture.active = prevRT;
}
#endregion
public static void DrawQuad(this RenderTexture rt, Material material, in Rect rect)
{
Matrix4x4 objectMatrix = Matrix4x4.TRS(
rect.position, Quaternion.identity, rect.size);
rt.DrawMesh(GetQuad(), material, objectMatrix);
//GL.invertCulling = true;
}
public static void DrawSprite(this RenderTexture rt, Texture texture, in Rect rect)
{
Material material = GetBlitMaterial();
material.mainTexture = texture;
DrawQuad(rt, material, rect);
}
#region Utils
public static float Aspect(this Texture rt) => (float)rt.width / rt.height;
public static Texture2D ConvertToTexture2D(this RenderTexture rt,
TextureFormat format = TextureFormat.RGB24,
FilterMode filterMode = FilterMode.Bilinear)
{
Texture2D tex = new Texture2D(rt.width, rt.height, format, false);
tex.filterMode = filterMode;
RenderTexture prevActive = RenderTexture.active;
RenderTexture.active = rt;
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
tex.Apply();
RenderTexture.active = prevActive;
return tex;
}
public static void DrawTextureGUI(Texture texture)
{
GUI.DrawTexture(new Rect(0, 0, texture.width, texture.height), texture);
}
#endregion
}
}