using System.Collections.Generic; using System.IO; using Godot; using Godot.Collections; using KeepersCompound.LGS; using KeepersCompound.TMV.UI; namespace KeepersCompound.TMV; public partial class Model : Node3D { public override void _Ready() { var modelSelector = GetNode("%ModelSelector") as ModelSelector; modelSelector.LoadModel += BuildModel; } private void BuildModel(string rootPath, string modelPath) { foreach (var node in GetChildren()) { node.QueueFree(); } var modelFile = new ModelFile(modelPath); if (modelFile == null) { GD.Print($"Failed to load model file: {modelPath}"); return; } // TODO: Remove this disgusting hack var baseDir = ProjectSettings.GlobalizePath($"user://objects/tmp"); var options = new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, RecurseSubdirectories = true, }; foreach (var material in modelFile.Materials) { var paths = Directory.GetFiles(baseDir, material.Name, options); if (paths.IsEmpty()) continue; var texture = TextureLoader.LoadTexture(paths[0]); var saveName = material.Name.GetBaseName() + ".png"; texture.GetImage().SavePng(ProjectSettings.GlobalizePath($"user://debug/{saveName}")); } var vertices = new List(); var indices = new List(); foreach (var v in modelFile.Vertices) { vertices.Add(v.ToGodotVec3()); } foreach (var poly in modelFile.Polygons) { for (var i = 1; i < poly.VertexCount - 1; i++) { indices.Add(poly.VertexIndices[0]); indices.Add(poly.VertexIndices[i]); indices.Add(poly.VertexIndices[i + 1]); } } var array = new Array(); array.Resize((int)Mesh.ArrayType.Max); array[(int)Mesh.ArrayType.Vertex] = vertices.ToArray(); array[(int)Mesh.ArrayType.Index] = indices.ToArray(); var mesh = new ArrayMesh(); mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, array); var meshInstance = new MeshInstance3D { Mesh = mesh }; AddChild(meshInstance); } }