2025-11-24 15:14:10 +00:00

86 lines
3.0 KiB
C#

namespace TheLabs;
using System;
using System.Collections.Generic;
using System.IO;
using Assimp; // The library we just installed
using OpenTK.Mathematics;
public static class ModelLoader
{
public static Mesh LoadMesh(string path)
{
var importer = new AssimpContext();
var scene = importer.ImportFile(path, PostProcessSteps.Triangulate | PostProcessSteps.JoinIdenticalVertices);
if (scene == null || scene.SceneFlags.HasFlag(SceneFlags.Incomplete) || scene.RootNode == null)
{
throw new Exception("Error loading model: " + path);
}
// --- NEW LOGIC: Combine all meshes into one ---
List<float> allVertices = new List<float>();
List<uint> allIndices = new List<uint>();
// We need to track how many vertices we've added so far
// so the indices point to the correct new location
uint indexOffset = 0;
// Loop through EVERY mesh found in the file (Legs, Torso, Head, etc.)
foreach (var mesh in scene.Meshes)
{
// 1. Process Vertices for this specific part
for (int i = 0; i < mesh.VertexCount; i++)
{
// Position (x, y, z)
var pos = mesh.Vertices[i];
allVertices.Add(pos.X);
allVertices.Add(pos.Y);
allVertices.Add(pos.Z);
// 2. Normals (NEW)
if (mesh.HasNormals)
{
var n = mesh.Normals[i];
allVertices.Add(n.X); allVertices.Add(n.Y); allVertices.Add(n.Z);
}
else
{
allVertices.Add(0); allVertices.Add(1); allVertices.Add(0); // Default up
}
// Texture Coordinates (u, v)
if (mesh.HasTextureCoords(0))
{
var uv = mesh.TextureCoordinateChannels[0][i];
allVertices.Add(uv.X);
allVertices.Add(uv.Y);
}
else
{
allVertices.Add(0.0f);
allVertices.Add(0.0f);
}
}
// 2. Process Indices for this specific part
for (int i = 0; i < mesh.FaceCount; i++)
{
var face = mesh.Faces[i];
for (int j = 0; j < face.IndexCount; j++)
{
// CRITICAL: We add the offset to the index!
// If the leg had 100 vertices, the first vertex of the torso
// needs to be index 100, not 0.
allIndices.Add((uint)(face.Indices[j] + indexOffset));
}
}
// Increase the offset by the number of vertices we just added
indexOffset += (uint)mesh.VertexCount;
}
// Return one giant Mesh containing the whole character
return new Mesh(allVertices.ToArray(), allIndices.ToArray(), Mesh.VertexLayout.PosTex);
}
}