ShowSkeleton.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Collections.Generic;
  2. using TriLibCore.Extensions;
  3. using UnityEngine;
  4. namespace TriLibCore.Samples
  5. {
  6. public class ShowSkeleton : MonoBehaviour
  7. {
  8. private List<Transform> _bones;
  9. private Material _material;
  10. public void Setup(AssetLoaderContext assetLoaderContext, AssetViewer assetViewer)
  11. {
  12. _material = new Material(Shader.Find("Hidden/ShowSkeleton"));
  13. _bones = new List<Transform>();
  14. assetLoaderContext.RootModel.GetBones(assetLoaderContext, _bones);
  15. if (_bones.Count > 0)
  16. {
  17. SetCustomBounds(assetLoaderContext, assetViewer);
  18. }
  19. }
  20. private void SetCustomBounds(AssetLoaderContext assetLoaderContext, AssetViewer assetViewer)
  21. {
  22. var totalBounds = new Bounds();
  23. var totalBoundsInitialized = false;
  24. if (assetViewer.RootGameObject.TryGetComponent<Animation>(out var animation))
  25. {
  26. var animationClips = animation.GetAllAnimationClips();
  27. foreach (var clip in animationClips)
  28. {
  29. animation.clip = clip;
  30. var frameInterval = 1f / clip.frameRate;
  31. for (var t = 0f; t < clip.length; t += frameInterval)
  32. {
  33. animation[clip.name].time = t;
  34. animation.Sample();
  35. var bounds = new Bounds();
  36. var initialized = false;
  37. foreach (var bone in _bones)
  38. {
  39. if (!initialized)
  40. {
  41. bounds.center = bone.position;
  42. if (!totalBoundsInitialized)
  43. {
  44. totalBounds.center = bone.position;
  45. totalBoundsInitialized = true;
  46. }
  47. initialized = true;
  48. }
  49. else
  50. {
  51. bounds.Encapsulate(bone.position);
  52. }
  53. }
  54. totalBounds.Encapsulate(bounds);
  55. }
  56. }
  57. }
  58. if (totalBounds.size.magnitude > 0f)
  59. {
  60. assetViewer.SetCustomBounds(totalBounds);
  61. }
  62. }
  63. private void OnRenderObject()
  64. {
  65. _material.SetPass(0);
  66. GL.PushMatrix();
  67. GL.Begin(GL.LINES);
  68. foreach (var transform in _bones)
  69. {
  70. foreach (Transform child in transform)
  71. {
  72. GL.Color(Color.green);
  73. GL.Vertex(transform.position);
  74. GL.Vertex(child.position);
  75. }
  76. }
  77. GL.End();
  78. GL.PopMatrix();
  79. }
  80. }
  81. }