TemplateFactory.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.Xna.Framework.Graphics;
  7. using SharpGLTF.Runtime.Template;
  8. namespace SharpGLTF.Runtime.Pipeline
  9. {
  10. /// <summary>
  11. /// This is the entry point class used to load glTF models and its resources into MonoGame.
  12. /// </summary>
  13. public static class TemplateFactory
  14. {
  15. public static MonoGameDeviceContent<MonoGameModelTemplate> LoadDeviceModel(GraphicsDevice device, string filePath, MeshesFactory context = null)
  16. {
  17. var model = Schema2.ModelRoot.Load(filePath, Validation.ValidationMode.TryFix);
  18. return CreateDeviceModel(device, model, context);
  19. }
  20. public static MonoGameDeviceContent<MonoGameModelTemplate> CreateDeviceModel(GraphicsDevice device, Schema2.ModelRoot srcModel, MeshesFactory context = null)
  21. {
  22. context ??= MeshesFactory.Create(device);
  23. context.Reset();
  24. var options = new RuntimeOptions { IsolateMemory = true };
  25. var templates = srcModel.LogicalScenes
  26. .Select(item => SceneTemplate.Create(item, options))
  27. .ToArray();
  28. var srcMeshes = templates
  29. .SelectMany(item => item.LogicalMeshIds)
  30. .Distinct()
  31. .Select(idx => srcModel.LogicalMeshes[idx]);
  32. var dstMeshes = context.CreateRuntimeMeshes(srcMeshes);
  33. var mdl = new MonoGameModelTemplate(templates, srcModel.DefaultScene.LogicalIndex, dstMeshes);
  34. return new MonoGameDeviceContent<MonoGameModelTemplate>(mdl, context.Disposables.ToArray());
  35. }
  36. }
  37. }