This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
3 changed files with 784842 additions and 0 deletions

381
Brutal.Render.Mesh/Mesh.cs Normal file
View file

@ -0,0 +1,381 @@
using System.Diagnostics.CodeAnalysis;
using Brutal.Attributes;
using Brutal.Collections;
using Brutal.Memory;
namespace Brutal.Render.Mesh;
/// <summary>
/// Interface for an object that maps vertex buffers by a key
/// </summary>
/// <typeparam name="TKey">Key used to map vertex buffers</typeparam>
public interface IVertexBufferMap<TKey>
{
/// Get vertex list by key
public NativeStrideList GetVertexList(TKey key);
/// Set vertex list by key
public void SetVertexList(TKey key, NativeStrideList vertexList);
/// Remove a vertex channel at key
public bool RemoveVertexList(TKey key);
/// True if key is present in map
public bool ContainsKey(TKey key);
/// Try-get list by key
public bool TryGetVertexList(TKey key, [MaybeNullWhen(false)] out NativeStrideList value);
/// <summary>
/// Enumerate through all keys
/// </summary>
/// <returns>IEnumerable of keys</returns>
public IEnumerable<TKey> GetVertexKeys();
/// Official number of vertices
int VertexCount { get; }
}
/// <summary>
/// Interface for a mesh object that may store an index buffer
/// </summary>
public interface IIndexBufferStorage
{
/// Index buffer
public NativeStrideList? IndexBuffer { get; }
/// Set index buffer
public void SetIndexBuffer(NativeStrideList indexList);
/// Remove index buffer
public void RemoveIndexBuffer();
/// Number of indices in index buffer, if any
int IndexCount { get; }
}
/// <summary>
/// Combined vertex/index mesh buffer interface
/// </summary>
/// <typeparam name="TKey">Vertex channel key</typeparam>
public interface IMeshStorage<TKey> : IVertexBufferMap<TKey>, IIndexBufferStorage { }
/// <summary>
/// Simple, generic mesh class that maps vertex channel buffers by a key for easy serialisation, modification and uploading to GPU
/// </summary>
/// <typeparam name="TKey">Key used to track vertex channels, can be an int, or a game specific enum</typeparam>
public class Mesh<TKey> : IDisposable, IMeshStorage<TKey>
where TKey : unmanaged
{
/// <summary>
/// Index buffer (optional)
/// </summary>
public NativeStrideList? IndexBuffer { get; protected set; }
/// <summary>
/// Vertex buffers, mapped by a key, usually corresponding to a channel (eg: position, normals)
/// </summary>
public Dictionary<TKey, NativeStrideList> VertexBufferMap { get; protected set; } = new();
/// <summary>
/// Official number of vertices
/// </summary>
public int VertexCount { get; set; }
/// <summary>
/// Number of indices in index buffer, if any
/// </summary>
public int IndexCount => IndexBuffer?.Count ?? 0;
/// <summary>
/// Dictionary style Try-Get function
/// </summary>
/// <param name="key">Vertex channel key</param>
/// <param name="value">NativeStrideList of vertices</param>
/// <returns>True if found</returns>
public bool TryGetVertexList(TKey key, [MaybeNullWhen(false)] out NativeStrideList value) =>
VertexBufferMap.TryGetValue(key, out value);
/// <summary>
/// Returns true if vertex map contains the key
/// </summary>
/// <param name="key">Vertex channel key</param>
/// <returns>True if key is present</returns>
public bool ContainsKey(TKey key) => VertexBufferMap.ContainsKey(key);
/// <summary>
/// Get all the keys for vertex channels present
/// </summary>
/// <returns>IEnumerable of keys</returns>
public IEnumerable<TKey> GetVertexKeys()
{
return VertexBufferMap.Keys;
}
/// <summary>
/// Set or safely replace IndexBuffer
/// </summary>
/// <param name="indexList">List of index data</param>
public void SetIndexBuffer(NativeStrideList indexList)
{
IndexBuffer?.Dispose();
IndexBuffer = indexList;
}
/// <summary>
/// Safely remove IndexBuffer
/// </summary>
public void RemoveIndexBuffer()
{
IndexBuffer?.Dispose();
IndexBuffer = null;
}
/// <summary>
/// Returns a vertex channel via span
/// </summary>
/// <param name="key">Key that maps to vertex channels</param>
/// <typeparam name="T">Type we want to use for span</typeparam>
/// <returns>Vertex buffer cast as span</returns>
public Span<T> GetVertexSpan<T>(TKey key)
where T : unmanaged
{
if (!VertexBufferMap.TryGetValue(key, out var nativeList))
return default;
return nativeList.ToSpan<T>();
}
/// <summary>
/// Returns a NativeStrideList corresponding to a vertex channel
/// </summary>
/// <param name="key">Vertex channel key</param>
/// <returns>Vertex buffer as a NativeStrideList</returns>
/// <exception cref="Exception"></exception>
public NativeStrideList GetVertexList(TKey key)
{
if (!VertexBufferMap.TryGetValue(key, out var nativeList))
throw new Exception($"Vertex list for key {key} not found");
return nativeList;
}
/// <summary>
/// Remove and safely dispose a channel from Mesh
/// </summary>
/// <param name="key">Vertex channel key</param>
/// <returns>True if successfully removed</returns>
public bool RemoveVertexList(TKey key)
{
if (VertexBufferMap.TryGetValue(key, out var nativeList))
{
nativeList.Dispose();
VertexBufferMap.Remove(key);
return true;
}
return false;
}
/// <summary>
/// Map a vertex channel key to an existing NativeStrideList
/// </summary>
/// <param name="key">Vertex channel key</param>
/// <param name="vertexList">Vertex buffer as a NativeStrideList</param>
public void SetVertexList(TKey key, NativeStrideList vertexList)
{
VertexBufferMap[key] = vertexList;
}
/// <summary>
/// Clear all buffers present
/// </summary>
public void Clear()
{
VertexCount = 0;
IndexBuffer?.Clear();
foreach (var data in VertexBufferMap)
data.Value.Clear();
}
/// <summary>
/// Release all buffers present
/// </summary>
public void Release()
{
VertexCount = 0;
IndexBuffer?.Dispose();
IndexBuffer = null;
foreach (var data in VertexBufferMap)
data.Value.Dispose();
VertexBufferMap.Clear();
}
/// <summary>
/// Dispose pattern
/// </summary>
public void Dispose()
{
Release();
}
}
/// <summary>
/// Extension methods for meshes
/// </summary>
public static partial class MeshExtensions
{
/// Creates empty vertex buffer if needed, or resizes existing buffer. Either way ensures a buffer of specified size exists and returns it
public static NativeStrideList EnsureVertexBuffer<TKey>(
this IVertexBufferMap<TKey> mesh,
TKey key,
ElementCount size,
ByteSize stride
)
{
if (mesh.TryGetVertexList(key, out NativeStrideList? nativeList))
{
if (stride != nativeList.Stride)
{
nativeList = new NativeStrideList(stride, nativeList.Capacity);
mesh.SetVertexList(key, nativeList);
}
}
else
{
nativeList = new NativeStrideList(stride, size);
mesh.SetVertexList(key, nativeList);
}
nativeList.Count = size;
return nativeList;
}
/// Creates empty index buffer if needed, or resizes existing buffer. Either way ensures a buffer of specified size exists and returns it
public static NativeStrideList EnsureIndexBuffer(this IIndexBufferStorage mesh, ElementCount size, ByteSize stride)
{
if (mesh.IndexBuffer != null)
{
if (stride != mesh.IndexBuffer.Stride)
mesh.SetIndexBuffer(new NativeStrideList(stride, mesh.IndexBuffer.Capacity));
mesh.IndexBuffer.Count = size;
return mesh.IndexBuffer;
}
var buffer = new NativeStrideList(stride, size);
buffer.Count = size;
mesh.SetIndexBuffer(buffer);
return buffer;
}
/// Convenience function to set/replace vertices via NativeStrideSpan
public static void SetIndicesFromData(this IIndexBufferStorage mesh, NativeStrideSpan data)
{
mesh.SetIndexBuffer(NativeStrideList.FromSpan(data));
}
/// Convenience function to set/replace vertices via Span
public static void SetIndicesFromData<T>(this IIndexBufferStorage mesh, [Fixed] Span<T> data)
where T : unmanaged
{
mesh.SetIndicesFromData(NativeStrideSpan.FromSpan(data));
}
/// Convenience function to set/replace vertices via NativeStrideSpan
public static void SetVerticesFromData<TKey>(this IVertexBufferMap<TKey> mesh, TKey key, NativeStrideSpan data)
{
mesh.SetVertexList(key, NativeStrideList.FromSpan(data));
}
/// Convenience function to set/replace vertices via Span
public static void SetVerticesFromData<TKey, T>(this IVertexBufferMap<TKey> mesh, TKey key, [Fixed] Span<T> data)
where T : unmanaged
{
mesh.SetVerticesFromData(key, NativeStrideSpan.FromSpan(data));
}
/// Convenience function to add vertices via NativeStrideSpan
public static void AddVerticesFromData<TKey>(this IVertexBufferMap<TKey> mesh, TKey key, NativeStrideSpan data)
{
if (mesh.TryGetVertexList(key, out var nativeList))
{
nativeList.AddData(data);
}
else
{
mesh.SetVertexList(key, NativeStrideList.FromSpan(data));
}
}
/// Convenience function to add vertices via Span
public static void AddVerticesFromData<TKey, T>(this IVertexBufferMap<TKey> mesh, TKey key, [Fixed] Span<T> data)
where T : unmanaged
{
mesh.AddVerticesFromData(key, NativeStrideSpan.FromSpan(data));
}
/// Convenience function to add indices via NativeStrideSpan
public static void AddIndicesFromData(this IIndexBufferStorage mesh, NativeStrideSpan data)
{
if (mesh.IndexBuffer != null)
mesh.IndexBuffer.AddData(data);
else
mesh.SetIndexBuffer(NativeStrideList.FromSpan(data));
}
/// Convenience function to add vertices via Span
public static void AddIndicesFromData<T>(this IIndexBufferStorage mesh, [Fixed] Span<T> data)
where T : unmanaged
{
mesh.AddIndicesFromData(NativeStrideSpan.FromSpan(data));
}
/// Convenience function for quickly accessing vertex data as span
public static bool TryGetVertexSpan<TKey, T>(this IVertexBufferMap<TKey> mesh, TKey key, out Span<T> data)
where T : unmanaged
{
if (mesh.TryGetVertexList(key, out var nativeList))
{
data = nativeList.ToSpan<T>();
return true;
}
data = default;
return false;
}
/// Convenience function for quickly accessing vertex data as span
public static bool TryGetIndexSpan<T>(this IIndexBufferStorage mesh, out Span<T> data)
where T : unmanaged
{
if (mesh.IndexBuffer != null)
{
data = mesh.IndexBuffer.ToSpan<T>();
return true;
}
data = default;
return false;
}
}
/// <summary>
/// Functions added to assist with updating Brutal.Core to 0.2.2 (and dependent packages)
/// </summary>
public static class NativeStrideListExtensions
{
public static void AddData(this NativeStrideList list, NativeStrideSpan data)
{
ValidateSameStrides(data.Stride, list.Stride);
list.AddRange(data.AsSpan<byte>().ToArray());
}
public static Span<T> ToSpan<T>(this NativeStrideList list)
where T : unmanaged
{
if (list.Stride != ByteSize.Of<T>())
throw new Exception(
$"Invalid conversion: buffer stored with stride {list.Stride} but converting to type with stride {ByteSize.Of<T>()}"
);
return list.AsSpan<T>();
}
public static void ValidateSameStrides(ByteSize first, ByteSize second)
{
if (first != second)
throw new ArgumentException($"Strides not equal");
}
}

View file

@ -0,0 +1,564 @@
using System.Runtime.CompilerServices;
using Brutal.Numerics;
namespace Brutal.Render.Mesh;
/// <summary>
/// Contains functions for generating procedural geometry for standard primitive shapes
/// </summary>
public static partial class ProcGenMeshLibrary
{
/// <summary>
/// Get right and up directions for a plane
/// </summary>
/// <param name="normal">Normal of plane</param>
/// <param name="right">Outputs right direction</param>
/// <param name="up">Outputs up direction</param>
private static void GetRightUp(float3 normal, out float3 right, out float3 up)
{
right = float3.Cross(normal, GlobalUp);
var dot = float3.Dot(normal, GlobalUp);
if (MathF.Abs(dot) > 0.9999f)
right = GlobalRight * MathF.Sign(dot);
up = float3.Cross(right, normal);
}
/// <summary>
/// Generate a plane mesh with the given origin, right, up, size and grid resolution
/// </summary>
/// <param name="output">Output mesh</param>
/// <param name="origin">Plane origin</param>
/// <param name="right">Plane right direction</param>
/// <param name="up">Plane up direction</param>
/// <param name="size">Size of plane</param>
/// <param name="resolution">Resolution of grid on plane</param>
public static unsafe void GeneratePlane(
in ProcGenMesh output,
float3 origin,
float3 right,
float3 up,
float size,
int resolution
)
{
var vertices = output.OutPositions;
var vStart = vertices.Count;
GenerateGridTopology(output, resolution, resolution);
var vPtr = vertices.Ptr.Cast<float3>().Offset(vStart);
var vCount = vertices.Count - vStart;
origin -= right * size / 2 + up * size / 2;
for (var i = 0; i < vCount; ++i)
{
var uv = vPtr[i];
vPtr[i] = origin + right * uv.X * size + up * uv.Y * size;
}
if (output.OutNormals != null)
{
var forward = float3.Normalize(float3.Cross(up, right));
AppendFlatValue(output.OutNormals, forward, vCount);
}
}
/// <summary>
/// Generate a plane mesh with the given origin, normal, size and grid resolution
/// </summary>
/// <param name="output"></param>
/// <param name="origin"></param>
/// <param name="normal"></param>
/// <param name="size"></param>
/// <param name="resolution"></param>
public static void GeneratePlane(in ProcGenMesh output, float3 origin, float3 normal, float size, int resolution)
{
GetRightUp(normal, out var right, out var up);
GeneratePlane(in output, origin, right, up, size, resolution);
}
/// <summary>
/// Generate a cube mesh with the given origin, size and grid resolution
/// </summary>
/// <param name="output"></param>
/// <param name="origin"></param>
/// <param name="size"></param>
/// <param name="resolution"></param>
public static void GenerateCube(in ProcGenMesh output, float3 origin, float size, int resolution)
{
//Use GeneratePlane to generate the 6 faces of the cube
GeneratePlane(in output, origin + new float3(0, 0, size / 2), float3.UnitZ, size, resolution);
GeneratePlane(in output, origin + new float3(0, 0, -size / 2), -float3.UnitZ, size, resolution);
GeneratePlane(in output, origin + new float3(size / 2, 0, 0), float3.UnitX, size, resolution);
GeneratePlane(in output, origin + new float3(-size / 2, 0, 0), -float3.UnitX, size, resolution);
GeneratePlane(in output, origin + new float3(0, size / 2, 0), float3.UnitY, size, resolution);
GeneratePlane(in output, origin + new float3(0, -size / 2, 0), -float3.UnitY, size, resolution);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static float2 CartesianToSphere(in float3 cartesian)
{
var latitude = MathF.Asin(cartesian.Y);
var longitude = MathF.Atan2(cartesian.X, cartesian.Z);
return new float2(latitude, longitude);
}
/// <summary>
/// Normalised spherical coordinates to cartesian coordinates
/// </summary>
/// <param name="latitude"></param>
/// <param name="longitude"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static float3 SphereToCartesian(in float latitude, in float longitude)
{
var a = float.Cos(longitude);
var x = a * float.Cos(latitude);
var y = float.Sin(longitude);
var z = a * float.Sin(latitude);
return new float3(x, y, z);
}
/// <summary>
/// Cartesian coordinates from toroidal coordinates
/// </summary>
/// <param name="latitude"></param>
/// <param name="longitude"></param>
/// <param name="radiusA"></param>
/// <param name="radiusB"></param>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static float3 ToroidialToCartesian(
in float latitude,
in float longitude,
float radiusA = 1.0f,
float radiusB = 0.5f
)
{
var a = radiusA + radiusB * MathF.Cos(latitude);
var x = a * MathF.Cos(longitude);
var y = radiusB * MathF.Sin(latitude);
var z = a * MathF.Sin(longitude);
return new float3(x, y, z);
}
/// <summary>
/// Generates grid topology for a mesh, which can be transformed into a conic shape or plane
/// </summary>
/// <param name="output"></param>
/// <param name="resolutionX">Number of vertices on X axis</param>
/// <param name="resolutionY">Number of vertices on Y axis</param>
public static unsafe void GenerateGridTopology(in ProcGenMesh output, int resolutionX, int resolutionY)
{
var vStart = output.VertexCount;
if (output.OutIndices == null)
{
var stepX = 1.0f / resolutionX;
var stepY = 1.0f / resolutionY;
int vCount = resolutionX * resolutionY * 6;
var vertices = output.OutPositions;
var vPtr = AllocateAtEnd<float3>(vertices, vCount);
var vIndex = 0;
for (var y = 0; y < resolutionY; ++y)
{
for (var x = 0; x < resolutionX; ++x)
{
var x0 = x * stepX;
var y0 = y * stepY;
var x1 = (x + 1) * stepX;
var y1 = (y + 1) * stepY;
var p0 = new float3(x0, y0, 0);
var p1 = new float3(x1, y0, 0);
var p2 = new float3(x1, y1, 0);
var p3 = new float3(x0, y1, 0);
vPtr[vIndex++] = p0;
vPtr[vIndex++] = p1;
vPtr[vIndex++] = p2;
vPtr[vIndex++] = p0;
vPtr[vIndex++] = p2;
vPtr[vIndex++] = p3;
}
}
//UVs can be generated from this topology directly
if (output.OutUVs != null)
{
var uvs = output.OutUVs;
var uvPtr = AllocateAtEnd<float2>(uvs, vCount);
vIndex = 0;
for (var i = 0; i < vCount; ++i)
{
uvPtr[vIndex++] = vPtr[i].XY;
}
}
}
else
{
var stepX = 1.0f / resolutionX;
var stepY = 1.0f / resolutionY;
// Vertex resolution is one more than the grid resolution
var total = (resolutionX + 1) * (resolutionY + 1);
var vertices = output.OutPositions;
var vPtr = AllocateAtEnd<float3>(vertices, total);
var vIndex = 0;
for (var y = 0; y <= resolutionY; ++y)
{
for (var x = 0; x <= resolutionX; ++x)
{
var x0 = x * stepX;
var y0 = y * stepY;
vPtr[vIndex++] = new float3(x0, y0, 0);
}
}
//UVs can be generated from this topology directly
if (output.OutUVs != null)
{
var uvs = output.OutUVs;
var uvPtr = AllocateAtEnd<float2>(uvs, total);
vIndex = 0;
for (var i = 0; i < total; ++i)
{
uvPtr[vIndex++] = vPtr[i].XY;
}
}
AddGridIndices(output.OutIndices, vStart, resolutionX, resolutionY);
}
}
/// <summary>
/// Generate a sphere mesh with the given origin, radius and resolution
/// </summary>
/// <param name="output">Mesh to output to</param>
/// <param name="origin">Sphere origin</param>
/// <param name="radius">Sphere radius</param>
/// <param name="resolutionA">Resolution of sphere (longitude)</param>
/// <param name="resolutionB">Resolution of sphere (latitude)</param>
public static unsafe void GenerateSphere(
in ProcGenMesh output,
float3 origin,
float radius,
int resolutionA,
int resolutionB
)
{
var vertices = output.OutPositions;
var vStart = vertices.Count;
var resOffset = new float2(0, -float.Pi / 2);
// Normalize the scale to match spherical coordinates
var resScale = new float2(float.Tau, float.Pi);
GenerateGridTopology(in output, resolutionA, resolutionB);
var vPtr = vertices.Ptr.Cast<float3>().Offset(vStart);
;
var vCount = vertices.Count - vStart;
for (var i = 0; i < vCount; ++i)
{
var uv = vPtr[i];
vPtr[i] =
SphereToCartesian(uv.X * resScale.X + resOffset.X, uv.Y * resScale.Y + resOffset.Y) * radius + origin;
}
if (output.OutNormals != null)
{
var normals = output.OutNormals;
var nPtr = AllocateAtEnd<float3>(normals, vCount);
var vIndex = 0;
for (var i = 0; i < vCount; ++i)
{
nPtr[vIndex++] = float3.Normalize(vPtr[i] - origin);
}
}
}
public static void GenerateSphere(in ProcGenMesh output, float3 origin, float radius, int resolution)
{
GenerateSphere(output, origin, radius, resolution, resolution / 2);
}
/// <summary>
/// Generate a torus mesh with the given origin, radius and resolution
/// </summary>
/// <param name="output">Mesh to output to</param>
/// <param name="origin">Torus origin</param>
/// <param name="radiusA">Torus main radius</param>
/// <param name="radiusB">Torus secondary radius</param>
/// <param name="resolutionA">Resolution of torus (primary)</param>
/// <param name="resolutionB">Resolution of torus (secondary)</param>
public static unsafe void GenerateTorus(
in ProcGenMesh output,
float3 origin,
float radiusA,
float radiusB,
int resolutionA,
int resolutionB
)
{
var vertices = output.OutPositions;
var vStart = vertices.Count;
var resOffset = new float2(0, 0);
// Normalize the scale to match spherical coordinates
var resScale = new float2(float.Tau, -float.Tau);
GenerateGridTopology(in output, resolutionA, resolutionB);
var vPtr = vertices.Ptr.Cast<float3>().Offset(vStart);
var vCount = vertices.Count - vStart;
for (var i = 0; i < vCount; ++i)
{
var uv = vPtr[i];
vPtr[i] =
ToroidialToCartesian(uv.X * resScale.X + resOffset.X, uv.Y * resScale.Y + resOffset.Y, radiusA, radiusB)
+ origin;
}
if (output.OutNormals != null)
{
var normals = output.OutNormals;
var nPtr = AllocateAtEnd<float3>(normals, vCount);
var vIndex = 0;
for (var i = 0; i < vCount; ++i)
{
var uv = vPtr[i];
var normal = float3.Normalize(uv - origin);
nPtr[vIndex++] = normal;
}
}
}
/// <summary>
/// Generate a circle/disk mesh with the given origin, axis, radius and resolution
/// </summary>
/// <param name="output">Output mesh object</param>
/// <param name="origin">Origin of disk</param>
/// <param name="axis">Axis/normal of disk</param>
/// <param name="radius">Radius of disk</param>
/// <param name="resolution">Resolution of disk</param>
/// <param name="flip">If true, reverse disk direction</param>
public static unsafe void GenerateDisk(
in ProcGenMesh output,
float3 origin,
float3 axis,
float radius,
int resolution,
bool flip = false
)
{
var vertices = output.OutPositions;
var vStart = vertices.Count;
GetRightUp(axis, out var right, out var up);
var step = MathF.Tau / resolution;
var vPtr = AllocateAtEnd<float3>(vertices, resolution * 3);
var vIndex = 0;
for (var i = 0; i < resolution; ++i)
{
var angle0 = i * step;
var angle1 = (i + 1) * step;
var p0 = origin + right * MathF.Cos(angle0) * radius + up * MathF.Sin(angle0) * radius;
var p1 = origin + right * MathF.Cos(angle1) * radius + up * MathF.Sin(angle1) * radius;
var p2 = origin;
if (flip)
{
vPtr[vIndex++] = p0;
vPtr[vIndex++] = p2;
vPtr[vIndex++] = p1;
}
else
{
vPtr[vIndex++] = p0;
vPtr[vIndex++] = p1;
vPtr[vIndex++] = p2;
}
}
if (output.OutUVs != null)
{
var uvs = output.OutUVs;
uvs.EnsureCapacity(uvs.Count + resolution * 3);
var uvPtr = AllocateAtEnd<float2>(uvs, resolution * 3);
vIndex = 0;
var uvOrigin = new float2(0.5f, 0.5f);
for (var i = 0; i < resolution; ++i)
{
var angle0 = i * step;
var angle1 = (i + 1) * step;
uvPtr[vIndex++] = uvOrigin + new float2(MathF.Cos(angle0), MathF.Sin(angle0)) * 0.5f;
uvPtr[vIndex++] = uvOrigin + new float2(MathF.Cos(angle1), MathF.Sin(angle1)) * 0.5f;
uvPtr[vIndex++] = uvOrigin;
}
}
if (output.OutNormals != null)
AppendFlatValue(output.OutNormals, axis, resolution * 3);
AddOrderedIndices(output.OutIndices, vStart, resolution * 3);
}
/// <summary>
/// Generate a cone mesh with the given origin, axis, radius, height and resolution
/// </summary>
/// <param name="output">Output mesh</param>
/// <param name="origin">Cone origin</param>
/// <param name="axis">Cone axis</param>
/// <param name="radius">Cone radius</param>
/// <param name="height">Cone height</param>
/// <param name="resolution">Resolution of output mesh</param>
/// <param name="addCap">If true, will add a disk to cap cone</param>
public static unsafe void GenerateCone(
in ProcGenMesh output,
float3 origin,
float3 axis,
float radius,
float height,
int resolution,
bool addCap = true
)
{
var vertices = output.OutPositions;
var vStart = vertices.Count;
var vPtr = AllocateAtEnd<float3>(vertices, resolution * 3);
var vIndex = 0;
GetRightUp(axis, out var right, out var up);
var step = MathF.Tau / resolution;
for (var i = 0; i < resolution; ++i)
{
var angle0 = i * step;
var angle1 = (i + 1) * step;
var p0 = origin + right * MathF.Cos(angle0) * radius + up * MathF.Sin(angle0) * radius;
var p1 = origin + right * MathF.Cos(angle1) * radius + up * MathF.Sin(angle1) * radius;
var p2 = origin + axis * height;
vPtr[vIndex++] = p0;
vPtr[vIndex++] = p1;
vPtr[vIndex++] = p2;
}
if (output.OutUVs != null)
{
var uvs = output.OutUVs;
var uvPtr = AllocateAtEnd<float2>(uvs, resolution * 3);
vIndex = 0;
var invRes = 1.0f / resolution;
for (var i = 0; i < resolution; ++i)
{
var u0 = i * invRes;
var u1 = (i + 1) * invRes;
uvPtr[vIndex++] = new float2(u0, 0);
uvPtr[vIndex++] = new float2(u1, 0);
uvPtr[vIndex++] = new float2(0.5f, 1);
}
}
if (output.OutNormals != null)
{
var normals = output.OutNormals;
var nPtr = AllocateAtEnd<float3>(normals, resolution * 3);
vIndex = 0;
var dir = float2.Normalize(new float2(radius, height));
var scaleXY = dir.Y;
var scaledAxis = axis * dir.X;
var prevNormal = (right * MathF.Cos(0) + up * MathF.Sin(0)) * scaleXY + scaledAxis;
for (var i = 1; i <= resolution; ++i)
{
var angle = i * step;
var normal = (right * MathF.Cos(angle) + up * MathF.Sin(angle)) * scaleXY + scaledAxis;
nPtr[vIndex++] = prevNormal;
nPtr[vIndex++] = normal;
nPtr[vIndex++] = (prevNormal + normal) * 0.5f;
prevNormal = normal;
}
}
AddOrderedIndices(output.OutIndices, vStart, resolution * 3);
if (addCap)
{
GenerateDisk(in output, origin, -axis, radius, resolution, false);
}
}
/// <summary>
/// Generate a cylinder mesh with the given origin, axis, radius, height and resolution
/// </summary>
/// <param name="output">Output mesh object</param>
/// <param name="origin">Origin to place mesh</param>
/// <param name="axis">Axis of shape</param>
/// <param name="radius">Radius of shape</param>
/// <param name="height">Height of shape</param>
/// <param name="resolution">Resolution of output mesh</param>
/// <param name="addCaps">If true, will add disks on both ends of cylinder</param>
public static unsafe void GenerateCylinder(
in ProcGenMesh output,
float3 origin,
float3 axis,
float radius,
float height,
int resolution,
bool addCaps = true
)
{
var vertices = output.OutPositions;
var vStart = vertices.Count;
GenerateGridTopology(in output, resolution, 2);
const float scale = float.Tau;
GetRightUp(axis, out var right, out var up);
var vPtr = vertices.Ptr.Cast<float3>().Offset(vStart);
var vCount = vertices.Count - vStart;
if (output.OutNormals != null)
{
// Generate normals and warp grid to cylinder
var normals = output.OutNormals;
var nPtr = AllocateAtEnd<float3>(normals, vCount);
for (var i = 0; i < vCount; ++i)
{
var uv = vPtr[i];
var angle = uv.X * scale;
var heightOffset = uv.Y * height;
var normal = right * MathF.Cos(angle) * radius + up * MathF.Sin(angle);
nPtr[i] = normal;
vPtr[i] = origin + normal * radius + axis * heightOffset;
}
}
else
{
// Warp grid to cylinder
for (var i = 0; i < vCount; ++i)
{
var uv = vPtr[i];
var angle = uv.X * scale;
var heightOffset = uv.Y * height;
vPtr[i] =
origin + right * MathF.Cos(angle) * radius + up * MathF.Sin(angle) * radius + axis * heightOffset;
}
}
if (addCaps)
{
GenerateDisk(in output, origin, -axis, radius, resolution, false);
GenerateDisk(in output, origin + axis * height, axis, radius, resolution, false);
}
}
}

View file

@ -0,0 +1,570 @@
using System.Linq.Expressions;
using Brutal.Collections;
using Brutal.Memory;
using Brutal.Numerics;
using Brutal.Pointers.Extensions;
namespace Brutal.Render.Mesh;
/// <summary>
/// Output mesh structure that can optionally output to required vertex attributes
/// </summary>
public readonly struct ProcGenMesh
{
/// <summary>
/// Vertex positions as Vec3 (always required)
/// </summary>
public readonly NativeStrideList OutPositions;
/// <summary>
/// Vertex normals as Vec3 (optional)
/// </summary>
public readonly NativeStrideList? OutNormals;
/// <summary>
/// Vertex UVs as Vec2 (optional)
/// </summary>
public readonly NativeStrideList? OutUVs;
/// <summary>
/// Indices (optional)
/// </summary>
public readonly NativeStrideList? OutIndices;
/// Construct a new ProcGenMesh structure from the given output lists
public ProcGenMesh(
NativeStrideList outPositions,
NativeStrideList? outIndices = null,
NativeStrideList? outNormals = null,
NativeStrideList? outUVs = null
)
{
OutPositions = outPositions;
OutNormals = outNormals;
OutUVs = outUVs;
OutIndices = outIndices;
}
/// <summary>
/// Vertex count
/// </summary>
public int VertexCount => OutPositions.Count;
/// <summary>
/// Index count
/// </summary>
public int IndexCount => OutIndices?.Count ?? 0;
/// <summary>
/// If true, indices are 16-bit shorts
/// </summary>
public bool Indices16Bit => OutIndices?.Stride == ByteSize.Of<ushort>();
/// <summary>
/// If true, indices are 32-bit ints
/// </summary>
public bool Indices32Bit => OutIndices?.Stride == ByteSize.Of<uint>();
}
/// <summary>
/// Procedural generation mesh library
/// Functions in this library support generating meshes with a variety vertex and index attributes
/// </summary>
public static partial class ProcGenMeshLibrary
{
/// Global right direction assumed in generation. Change this if you are using a different coordinate system
public static float3 GlobalRight = float3.UnitX;
/// Global up direction assumed in generation. Change this if you are using a different coordinate system
public static float3 GlobalUp = float3.UnitY;
/// <summary>
/// Ensures space for the given number of vertices in the output buffer,
/// increases count and returns a pointer to the start of the new vertices.
/// Pointer is only valid until the next modification of the buffer.
/// </summary>
/// <param name="list">NativeStrideList</param>
/// <param name="count">Number of new elements to allocate</param>
/// <typeparam name="T">Vertex struct type</typeparam>
/// <returns>Pointer to first element in updated buffer</returns>
public static unsafe T* AllocateAtEnd<T>(INativeList<T> list, int count)
where T : unmanaged
{
if (list.Stride != ByteSize.Of<T>())
throw new System.Exception($"Stride mismatch: {list.Stride} != {ByteSize.Of<T>()}");
var oldSize = ByteSize.Of(list);
list.Count += count;
return (T*)((byte*)list.Ptr + oldSize);
}
public static unsafe T* AllocateAtEnd<T>(NativeStrideList list, int count)
where T : unmanaged
{
if (list.Stride != ByteSize.Of<T>())
throw new System.Exception($"Stride mismatch: {list.Stride} != {ByteSize.Of<T>()}");
var oldSize = ByteSize.Of(list);
list.Count += count;
return (T*)(((byte*)list.Ptr) + oldSize);
}
/// <summary>
/// General function for swizzling around vertex data
/// Example offsets to swizzle: XZY: [0,2,1], XXX: [0,0,0], YX: [1,0], WXYZ: [3,0,1,2]
/// </summary>
/// <param name="inList">Input list of vertex elements to swizzle.</param>
/// <param name="outList">Output list of vertex elements to swizzle (can be same as input)</param>
/// <param name="offsets">List of offsets to target index. MUST be same length as expected vector</param>
/// <typeparam name="T">Vector element type (usually float). NOT things like Vec3, you must cast these lists to their element type</typeparam>
public static unsafe void SwizzleVertices<T>(Span<T> inList, Span<T> outList, Span<int> offsets)
where T : unmanaged
{
if (inList.Length != outList.Length)
throw new System.Exception($"Length mismatch: {inList.Length} != {outList.Length}");
var vectorLength = offsets.Length;
var buffer = stackalloc T[vectorLength];
var vCount = inList.Length / vectorLength;
var ptr = inList.AsPointer();
for (var i = 0; i < vCount; i++)
{
var vI = i * vectorLength;
for (var ii = 0; ii < vectorLength; ii++)
buffer[ii] = ptr[vI + offsets[ii]];
for (var ii = 0; ii < vectorLength; ii++)
ptr[vI + ii] = buffer[ii];
}
}
/// <summary>
/// Add indices assuming triangles are generated in a clockwise order
/// Supports both 16 and 32bit indices as output
/// </summary>
/// <param name="indices">Output indices, if null, ignore</param>
/// <param name="start">First vertex</param>
/// <param name="count">Number of indices to generate</param>
public static unsafe void AddOrderedIndices(NativeStrideList? indices, int start, int count)
{
if (indices == null)
return;
var oldSize = ByteSize.Of(indices);
indices.Count += count;
var bytePtr = indices.Ptr.Offset(oldSize);
var startU = (uint)start;
// Support 16 and 32 bit indices
if (indices.Stride == ByteSize.Of<ushort>())
{
var ptr = (ushort*)bytePtr;
for (uint i = 0; i < count; ++i)
ptr[i] = (ushort)(startU + i);
}
else if (indices.Stride == ByteSize.Of<uint>())
{
var ptr = (uint*)bytePtr;
for (uint i = 0; i < count; ++i)
ptr[i] = startU + i;
}
else
{
throw new Exception($"Unsupported index stride: {indices.Stride}");
}
}
public static unsafe void AddGridIndices(
NativeStrideList indices,
int start,
int resolutionX,
int resolutionY,
bool flip = false
)
{
var oldSize = ByteSize.Of(indices);
indices.Count += (resolutionX * resolutionY * 6);
// Vertex resolution is one more than the grid resolution
var realResX = resolutionX + 1;
var bytePtr = indices.Ptr.Offset(oldSize);
var flipOffset = flip ? 1 : 0;
var p0 = flipOffset;
var p1 = 1 - flipOffset;
var p2 = (realResX + flipOffset);
var p3 = (realResX + 1 - flipOffset);
// Support 16 and 32 bit indices
if (indices.Stride == ByteSize.Of<ushort>())
{
var ptr = (ushort*)bytePtr;
var index = 0;
for (var i = 0; i < resolutionY; i++)
{
for (var j = 0; j < resolutionX; j++)
{
var i0 = start + i * realResX + j;
ptr[index++] = (ushort)(i0 + p0);
ptr[index++] = (ushort)(i0 + p1);
ptr[index++] = (ushort)(i0 + p3);
ptr[index++] = (ushort)(i0 + p0);
ptr[index++] = (ushort)(i0 + p3);
ptr[index++] = (ushort)(i0 + p2);
}
}
}
else if (indices.Stride == ByteSize.Of<uint>())
{
var ptr = (uint*)bytePtr;
var index = 0;
for (var i = 0; i < resolutionY; i++)
{
for (var j = 0; j < resolutionX; j++)
{
var i0 = start + i * realResX + j;
ptr[index++] = (uint)(i0 + p0);
ptr[index++] = (uint)(i0 + p1);
ptr[index++] = (uint)(i0 + p3);
ptr[index++] = (uint)(i0 + p0);
ptr[index++] = (uint)(i0 + p3);
ptr[index++] = (uint)(i0 + p2);
}
}
}
else
{
throw new Exception($"Unsupported index stride: {indices.Stride}");
}
}
/// <summary>
/// Add a flat repeated value to the end of the list
/// </summary>
/// <param name="list">target NativeStrideList</param>
/// <param name="value">Value to use</param>
/// <param name="count">Number of repeats</param>
/// <typeparam name="T">Value type, must be correct stride</typeparam>
private static unsafe void AppendFlatValue<T>(NativeStrideList list, T value, int count)
where T : unmanaged
{
var ptr = AllocateAtEnd<T>(list, count);
for (var i = 0; i < count; ++i)
ptr[i] = value;
}
/// <summary>
/// Add a triangle to a vertex buffer
/// </summary>
/// <param name="positions">Position buffer</param>
/// <param name="p0">Point in triangle</param>
/// <param name="p1">Point in triangle</param>
/// <param name="p2">Point in triangle</param>
/// <typeparam name="T">Vertex type</typeparam>
public static unsafe void AddTriangle<T>(NativeStrideList positions, T p0, T p1, T p2)
where T : unmanaged
{
var ptr = AllocateAtEnd<T>(positions, 3);
ptr[0] = p0;
ptr[1] = p1;
ptr[2] = p2;
}
/// <summary>
/// Adds a quad as two triangles to the output mesh.
/// Assumes points are organised in clockwise or anticlockwise order (p0 and p2 should be opposite corners, as with p1 and p3)
/// </summary>
/// <param name="positions">Output buffer</param>
/// <param name="p0">Point in quad</param>
/// <param name="p1">Point in quad</param>
/// <param name="p2">Point in quad</param>
/// <param name="p3">Point in quad</param>
/// <typeparam name="T">Vertex type</typeparam>
public static unsafe void AddQuad<T>(NativeStrideList positions, T p0, T p1, T p2, T p3)
where T : unmanaged
{
var ptr = AllocateAtEnd<T>(positions, 6);
ptr[0] = p0;
ptr[1] = p1;
ptr[2] = p2;
ptr[3] = p0;
ptr[4] = p2;
ptr[5] = p3;
}
/// <summary>
/// Adds a quad as two triangles to the output mesh, with efficient index generation.
/// Assumes points are organised in clockwise or anticlockwise order (p0 and p2 should be opposite corners, as with p1 and p3)
/// </summary>
/// <param name="positions">Output position buffer</param>
/// <param name="indices">Output indices</param>
/// <param name="p0">Point in quad</param>
/// <param name="p1">Point in quad</param>
/// <param name="p2">Point in quad</param>
/// <param name="p3">Point in quad</param>
/// <typeparam name="T">Vertex type</typeparam>
public static unsafe void AddQuad<T>(NativeStrideList positions, NativeStrideList indices, T p0, T p1, T p2, T p3)
where T : unmanaged
{
var vCount = positions.Count;
var ptr = AllocateAtEnd<T>(positions, 4);
ptr[0] = p0;
ptr[1] = p1;
ptr[2] = p2;
ptr[3] = p3;
AddGridIndices(indices, vCount, 2, 2);
}
/// <summary>
/// Add a triangle to an output mesh
/// </summary>
/// <param name="output">Output mesh object</param>
/// <param name="p0">Point in triangle</param>
/// <param name="p1">Point in triangle</param>
/// <param name="p2">Point in triangle</param>
public static void AddTriangle(in ProcGenMesh output, float3 p0, float3 p1, float3 p2)
{
var vCount = output.VertexCount;
AddTriangle(output.OutPositions, p0, p1, p2);
if (output.OutUVs != null)
AppendFlatValue(output.OutUVs, float2.Zero, 3);
if (output.OutNormals != null)
{
var normal = float3.Normalize(float3.Cross(p1 - p0, p2 - p0));
AppendFlatValue(output.OutNormals, normal, 3);
}
AddOrderedIndices(output.OutIndices, vCount, 3);
}
/// <summary>
/// Add a quad to an output mesh. Assumes quad is planar for normals, and UVs are normalised
/// Assumes points are organised in clockwise or anticlockwise order (p0 and p2 should be opposite corners, as with p1 and p3)
/// </summary>
/// <param name="output">Output mesh target</param>
/// <param name="p0">Point in quad</param>
/// <param name="p1">Point in quad</param>
/// <param name="p2">Point in quad</param>
/// <param name="p3">Point in quad</param>
public static void AddQuad(in ProcGenMesh output, float3 p0, float3 p1, float3 p2, float3 p3)
{
if (output.OutIndices != null)
{
// AddQuad with indices: Use efficient index generation
AddQuad(output.OutPositions, output.OutIndices, p0, p1, p2, p3);
if (output.OutUVs != null)
{
output.OutUVs.AddRange([new float2(0, 0), new float2(0, 1), new float2(1, 1), new float2(1, 0)]);
}
}
else
{
// AddQuad without indices: Add vertices directly
AddQuad(output.OutPositions, p0, p1, p2, p3);
if (output.OutUVs != null)
{
output.OutUVs.AddRange(
[
new float2(0, 0),
new float2(0, 1),
new float2(1, 1),
new float2(0, 0),
new float2(1, 1),
new float2(1, 0),
]
);
}
}
// Normals are the same for all vertices in a quad
if (output.OutNormals != null)
{
var normal = float3.Normalize(float3.Cross(p1 - p0, p2 - p0));
AppendFlatValue(output.OutNormals, normal, output.OutIndices != null ? 4 : 6);
}
}
/// Calculate tangents for a mesh from UV data
public static unsafe void CalculateTangents(
NativeStrideList outTangents,
Span<float3> positions,
Span<int> indices,
Span<float3> normals,
Span<float2> uvs
)
{
var vCount = positions.Length;
var tangents = AllocateAtEnd<float4>(outTangents, vCount);
// Temporary tangent lists
using var tan1 = new NativeList<float3>();
tan1.Count = vCount;
using var tan2 = new NativeList<float3>();
tan2.Count = vCount;
var iCount = indices.Length;
for (var a = 0; a < iCount; a += 3)
{
var i1 = indices[a];
var i2 = indices[a + 1];
var i3 = indices[a + 2];
var v1 = positions[i1];
var v2 = positions[i2];
var v3 = positions[i3];
var w1 = uvs[i1];
var w2 = uvs[i2];
var w3 = uvs[i3];
var x1 = v2.X - v1.X;
var x2 = v3.X - v1.X;
var y1 = v2.Y - v1.Y;
var y2 = v3.Y - v1.Y;
var z1 = v2.Z - v1.Z;
var z2 = v3.Z - v1.Z;
var s1 = w2.X - w1.X;
var s2 = w3.X - w1.X;
var t1 = w2.Y - w1.Y;
var t2 = w3.Y - w1.Y;
var div = s1 * t2 - s2 * t1;
var r = div == 0.0f ? 0.0f : 1.0f / div;
var sDir = new float3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r);
var tDir = new float3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r);
tan1[i1] += sDir;
tan1[i2] += sDir;
tan1[i3] += sDir;
tan2[i1] += tDir;
tan2[i2] += tDir;
tan2[i3] += tDir;
}
// Calculate final tangents from normals and temporary tangents
for (var a = 0; a < vCount; a++)
{
var n = normals[a];
var t = tan1[a];
// Gram-Schmidt orthogonalize
var tmp = (t - n * float3.Dot(n, t));
tmp = float3.Normalize(tmp);
// Calculate handedness
var w = float3.Dot(float3.Cross(n, t), tan2[a]) < 0.0f ? -1.0f : 1.0f;
tangents[a] = new float4(tmp, w);
}
}
/// Calculate tangents for a mesh purely from normals
public static unsafe void CalculateTangents(NativeStrideList outTangents, Span<float3> normals)
{
//No UVs, calculate tangents from world up direction
var tangents = AllocateAtEnd<float4>(outTangents, normals.Length);
var count = normals.Length;
for (var i = 0; i < count; i++)
{
var normal = normals[i];
if (normal.Y >= 1.0f)
{
tangents[i] = new float4(1.0f, 0.0f, 0.0f, 1.0f);
}
else
{
var biTangent = float3.Cross(normal, GlobalUp);
tangents[i] = new float4(float3.Normalize(float3.Cross(normal, biTangent)), 1.0f);
}
}
}
/// <summary>
/// Calculate the tangents of a mesh
/// </summary>
/// <param name="mesh">Source mesh to calculate tangents from</param>
/// <param name="outTangents">Tangent buffer to output to</param>
/// <exception cref="Exception">Thrown if insufficient mesh data present</exception>
public static void CalculateTangents(in ProcGenMesh mesh, NativeStrideList outTangents)
{
if (mesh is { OutIndices: not null, OutUVs: not null, OutNormals: not null })
CalculateTangents(
outTangents,
mesh.OutPositions.ToSpan<float3>(),
mesh.OutIndices.ToSpan<int>(),
mesh.OutNormals.ToSpan<float3>(),
mesh.OutUVs.ToSpan<float2>()
);
else if (mesh.OutNormals != null)
CalculateTangents(outTangents, mesh.OutNormals.ToSpan<float3>());
else
throw new Exception("Insufficient data to calculate tangents");
}
/// <summary>
/// Swizzle XYZ coords of a generated mesh. Helpful if you are using different coordinate systems
/// </summary>
/// <param name="mesh">Target mesh data</param>
/// <param name="offsets">Offset of swizzle data for XYZ</param>
/// <exception cref="Exception"></exception>
public static void SwizzleWorldCoords(in ProcGenMesh mesh, Span<int> offsets)
{
if (offsets.Length != 3)
throw new Exception("Insufficient data to calculate world coords");
var positions = mesh.OutPositions.AsSpan<float>();
SwizzleVertices(positions, positions, offsets);
if (mesh.OutNormals != null)
{
var normals = mesh.OutNormals.AsSpan<float>();
SwizzleVertices(normals, normals, offsets);
}
}
/// <summary>
/// Offset all position values by a translation value
/// </summary>
/// <param name="mesh">Target mesh</param>
/// <param name="translation">Translation offset</param>
public static unsafe void OffsetWorldCoords(in ProcGenMesh mesh, float3 translation)
{
var positions = mesh.OutPositions.ToSpan<float3>();
var vCount = positions.Length;
var ptr = positions.AsPointer();
for (var i = 0; i < vCount; i++)
ptr[i] += translation;
}
/// <summary>
/// Scale all position/normal values by a value
/// </summary>
/// <param name="mesh">Target mesh</param>
/// <param name="scale">Scaler</param>
public static unsafe void ScaleWorldCoords(in ProcGenMesh mesh, float3 scale)
{
var positions = mesh.OutPositions.ToSpan<float3>();
var vCount = positions.Length;
var ptr = positions.AsPointer();
for (var i = 0; i < vCount; i++)
ptr[i] *= scale;
if (mesh.OutNormals != null)
{
var normals = mesh.OutNormals.ToSpan<float3>();
vCount = normals.Length;
ptr = normals.AsPointer();
for (var i = 0; i < vCount; i++)
ptr[i] *= scale;
}
}
/// <summary>
/// Transform all position/normal values by a value
/// </summary>
/// <param name="mesh">Target mesh</param>
/// <param name="matrix">Transform matrix</param>
public static unsafe void TransformWorldCoords(in ProcGenMesh mesh, float4x4 matrix)
{
var positions = mesh.OutPositions.ToSpan<float3>();
var vCount = positions.Length;
var ptr = positions.AsPointer();
for (var i = 0; i < vCount; i++)
ptr[i] = float3.Transform(ptr[i], matrix);
if (mesh.OutNormals != null)
{
var normals = mesh.OutNormals.ToSpan<float3>();
vCount = normals.Length;
ptr = normals.AsPointer();
for (var i = 0; i < vCount; i++)
ptr[i] = float3.TransformNormal(ptr[i], matrix);
}
}
}