-
Notifications
You must be signed in to change notification settings - Fork 9
/
MeshDataBuilder.cs
87 lines (74 loc) · 2.28 KB
/
MeshDataBuilder.cs
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
// Based on: https://catlikecoding.com/unity/tutorials/advanced-rendering/flat-and-wireframe-shading/
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class MeshDataBuilder : MonoBehaviour
{
private void Reset()
{
GenerateMeshData();
}
/// <summary>
/// We will assign a color to each Vertex in a Triangle on the object's mesh
/// </summary>
void GenerateMeshData()
{
Mesh mesh = GetComponent<MeshFilter>().sharedMesh;
SplitMesh(mesh);
SetVertexColors(mesh);
}
/// <summary>
/// For this approach, we need to make sure there are not shared vertices
/// on the mesh, that's why we use this method to split the mesh.
/// This will increase the number of vertices, so less optimized.
/// </summary>
/// <param name="mesh"></param>
void SplitMesh(Mesh mesh)
{
int[] triangles = mesh.triangles;
Vector3[] verts = mesh.vertices;
Vector3[] normals = mesh.normals;
Vector2[] uvs = mesh.uv;
Vector3[] newVerts;
Vector3[] newNormals;
Vector2[] newUvs;
int n = triangles.Length;
newVerts = new Vector3[n];
newNormals = new Vector3[n];
newUvs = new Vector2[n];
for (int i = 0; i < n; i++)
{
newVerts[i] = verts[triangles[i]];
newNormals[i] = normals[triangles[i]];
if (uvs.Length > 0)
{
newUvs[i] = uvs[triangles[i]];
}
triangles[i] = i;
}
mesh.vertices = newVerts;
mesh.normals = newNormals;
mesh.uv = newUvs;
mesh.triangles = triangles;
}
/// <summary>
/// We paint the vertex color
/// </summary>
/// <param name="mesh"></param>
void SetVertexColors(Mesh mesh)
{
Color[] colorCoords = new[]
{
new Color(1, 0, 0),
new Color(0, 1, 0),
new Color(0, 0, 1),
};
Color32[] vertexColors = new Color32[mesh.vertices.Length];
for (int i = 0; i < vertexColors.Length; i += 3)
{
vertexColors[i] = colorCoords[0];
vertexColors[i + 1] = colorCoords[1];
vertexColors[i + 2] = colorCoords[2];
}
mesh.colors32 = vertexColors;
}
}