Skip to content

Commit 9d4c59b

Browse files
committed
- Improve from stackalloc to Unsafe to use pointers
1 parent 4279cad commit 9d4c59b

File tree

1 file changed

+23
-22
lines changed

1 file changed

+23
-22
lines changed

MeshOptimizerGen/HelloMeshlets/Program.cs

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Collections.Generic;
77
using System.IO;
88
using System.Reflection;
9+
using System.Runtime.CompilerServices;
910
using System.Runtime.InteropServices;
1011

1112
namespace HelloMeshlets
@@ -57,31 +58,31 @@ public unsafe static void Main(string[] args)
5758
byte[] meshletTriangles = new byte[maxMeshlets * kMaxTriangles * 3];
5859
Vector3[] positions = attrib.Vertices.ToArray();
5960

60-
fixed (meshopt_Meshlet* pMeshlets = &meshlets[0])
61-
fixed (uint* pMeshletVertices = &meshletVertices[0])
62-
fixed (byte* pMeshletTriangles = &meshletTriangles[0])
63-
fixed (uint* pIndices = &indices[0])
64-
fixed (Vector3* pPositions = &positions[0])
65-
{
66-
float* pVertsAsFloats = (float*)pPositions;
67-
68-
uint meshletCount = MeshOptNative.meshopt_buildMeshlets(
69-
pMeshlets,
70-
pMeshletVertices,
71-
pMeshletTriangles,
72-
pIndices,
73-
meshNumIndices,
74-
pVertsAsFloats,
75-
meshNumVertices,
76-
(uint)sizeof(Vector3),
77-
kMaxVertices,
78-
kMaxTriangles,
79-
kConeWeight);
61+
meshopt_Meshlet* pMeshlets = (meshopt_Meshlet*)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(meshlets));
62+
uint* pMeshletVertices = (uint*)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(meshletVertices));
63+
byte* pMeshletTriangles = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(meshletTriangles));
64+
uint* pIndices = (uint*)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(indices));
65+
float* pVertsAsFloats = (float*)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(positions));
8066

81-
Console.WriteLine($"{meshletCount} meshlets generated");
82-
}
67+
uint meshletCount = MeshOptNative.meshopt_buildMeshlets(
68+
pMeshlets,
69+
pMeshletVertices,
70+
pMeshletTriangles,
71+
pIndices,
72+
meshNumIndices,
73+
pVertsAsFloats,
74+
meshNumVertices,
75+
(uint)sizeof(Vector3),
76+
kMaxVertices,
77+
kMaxTriangles,
78+
kConeWeight);
8379

80+
var last = meshlets[meshletCount - 1];
81+
Array.Resize(ref meshletVertices, (int)(last.vertex_offset + last.vertex_count));
82+
Array.Resize(ref meshletTriangles, (int)(last.triangle_offset + ((last.triangle_count * 3 + 3) & ~3)));
83+
Array.Resize(ref meshlets, (int)meshletCount);
8484

85+
Console.WriteLine($"{meshletCount} meshlets generated");
8586
}
8687

8788
private static IntPtr ResolveRuntimes(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)

0 commit comments

Comments
 (0)