Init
This commit is contained in:
76
Assets/Script/MeshGeneration.cs
Normal file
76
Assets/Script/MeshGeneration.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using Unity.VisualScripting;
|
||||
using UnityEngine;
|
||||
|
||||
|
||||
public class MeshGeneration : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private Noise noise;
|
||||
[SerializeField] private ComputeShader marchShader;
|
||||
|
||||
public Mesh March(int numPointsPerAxis, Vector3 offset, float isoLevel)
|
||||
{
|
||||
Buffers.Create(numPointsPerAxis);
|
||||
int numVoxelsPerAxis = numPointsPerAxis - 1;
|
||||
int numThreadsPerAxis = Mathf.CeilToInt (numVoxelsPerAxis / (float) 8);
|
||||
noise.Generate(numPointsPerAxis, numThreadsPerAxis, offset);
|
||||
|
||||
marchShader.SetBuffer(0, "points", Buffers.pointsBuffer);
|
||||
marchShader.SetBuffer(0, "triangles", Buffers.triangleBuffer);
|
||||
marchShader.SetInt("numPointsPerAxis", numPointsPerAxis);
|
||||
marchShader.SetFloat("isoLevel", isoLevel);
|
||||
|
||||
marchShader.Dispatch(0, numThreadsPerAxis,numThreadsPerAxis,numThreadsPerAxis);
|
||||
|
||||
ComputeBuffer.CopyCount(Buffers.triangleBuffer, Buffers.triCountBuffer, 0);
|
||||
int[] triCountArray = { 0 };
|
||||
Buffers.triCountBuffer.GetData(triCountArray);
|
||||
int numTris = triCountArray[0];
|
||||
|
||||
Triangle[] tris = new Triangle[numTris];
|
||||
Buffers.triangleBuffer.GetData(tris, 0,0, numTris);
|
||||
|
||||
Mesh mesh = new Mesh();
|
||||
mesh.Clear();
|
||||
|
||||
var vertices = new Vector3[numTris * 3];
|
||||
var meshTriangles = new int[numTris * 3];
|
||||
|
||||
for (int i = 0; i < numTris; i++) {
|
||||
for (int j = 0; j < 3; j++) {
|
||||
meshTriangles[i * 3 + j] = i * 3 + j;
|
||||
vertices[i * 3 + j] = tris[i][j];
|
||||
}
|
||||
}
|
||||
mesh.vertices = vertices;
|
||||
mesh.triangles = meshTriangles;
|
||||
|
||||
mesh.RecalculateNormals();
|
||||
return mesh;
|
||||
}
|
||||
|
||||
private void OnDestroy()
|
||||
{
|
||||
Buffers.Release();
|
||||
}
|
||||
|
||||
struct Triangle
|
||||
{
|
||||
public Vector3 a;
|
||||
public Vector3 b;
|
||||
public Vector3 c;
|
||||
|
||||
public Vector3 this [int i] {
|
||||
get {
|
||||
switch (i) {
|
||||
case 0:
|
||||
return a;
|
||||
case 1:
|
||||
return b;
|
||||
default:
|
||||
return c;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user