Unity GL 实时绘制

GL立即绘图

  • 挂载到GameObject上即可
    • OnRenderObject // 都可以显示
    • OnGUI // Game模式可以显示,Editor不显示

矩阵

  • GL.PushMatrix(); // 保存摄像机变换矩阵
    • GL.LoadPixelMatrix() // 设置用屏幕坐标绘图
    • GL.MultMatrix()
  • GL.PopMatrix(); // 还原

绘制模式

  • GL.Begin()
    • Primitive
      • GL.QUADS
      • GL.LINES
      • GL.LINE_STRIP
      • GL.TRIANGLES
      • GL.TRIANGLE_STRIP
    • GL.Vertex3()
  • GL.End()

代码结构

1
2
3
4
5
6
7
8
9
void OnRenderObject()
{
GL.PushMatrix();
Color clr = Color.green;
clr.a = 0.1f;
GL.MultMatrix(transform.localToWorldMatrix);

GL.PopMatrix();
}

参考

代码

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
using UnityEngine;

public static class DrawGL
{
public enum DrawMode : int
{
Line = GL.LINES,
LineStrip = GL.LINE_STRIP,
Triangle = GL.TRIANGLES,
TriangleStrip = GL.TRIANGLE_STRIP,
Quad = GL.QUADS
}

static Material drawMaterial;

static void InitMaterial()
{
if (!drawMaterial)
{
Shader shader = Shader.Find("Hidden/Internal-Colored");
drawMaterial = new Material(shader);
drawMaterial.hideFlags = HideFlags.HideAndDontSave;
}
}

public static void WireframeMode(float zBias = 0, bool bAlpha = false, bool bZTest = true, int cullMode = 0)
{
InitMaterial();
if (bAlpha)
{
drawMaterial.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
drawMaterial.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
}
else
{
drawMaterial.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
drawMaterial.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
}

drawMaterial.SetInt("_Cull", cullMode); // Off=0 Front=1 Back=2
drawMaterial.SetInt("_ZWrite", 0); // Turn off depth writes

var zTest = bZTest
? UnityEngine.Rendering.CompareFunction.LessEqual
: UnityEngine.Rendering.CompareFunction.Always;
drawMaterial.SetInt("_ZTest", (int) zTest);
drawMaterial.SetFloat("_ZBias", zBias);

drawMaterial.SetPass(0);
}

public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Color color, float zBias = 0)
{
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;

WireframeMode(zBias);
GL.PushMatrix();
GL.MultMatrix(matrix);

GL.Begin(GL.LINES);
GL.Color(color);
for (int cnt = 0; cnt < triangles.Length; cnt += 3)
{
GL.Vertex(vertices[triangles[cnt]]);
GL.Vertex(vertices[triangles[cnt + 1]]);
GL.Vertex(vertices[triangles[cnt + 1]]);
GL.Vertex(vertices[triangles[cnt + 2]]);
GL.Vertex(vertices[triangles[cnt + 2]]);
GL.Vertex(vertices[triangles[cnt]]);
}

GL.End();
GL.PopMatrix();
}
}

Unity GL 实时绘制
https://automask.github.io/wild/2022/06/28/lab/S_Unity_GL/
作者
Kyle Zhou
发布于
2022年6月28日
许可协议