CharacterPartCacheExtensions.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace UnityEditor.U2D.Animation
  5. {
  6. internal static class CharacterPartCacheExtensions
  7. {
  8. public static void SyncSpriteSheetSkeleton(this CharacterPartCache characterPart)
  9. {
  10. var skinningCache = characterPart.skinningCache;
  11. var character = skinningCache.character;
  12. var characterSkeleton = character.skeleton;
  13. var spriteSkeleton = characterPart.sprite.GetSkeleton();
  14. var spriteSkeletonBones = spriteSkeleton.bones;
  15. var characterPartBones = characterPart.bones;
  16. if (spriteSkeletonBones.Length != characterPartBones.Length)
  17. return;
  18. for (var i = 0; i < characterPartBones.Length; ++i)
  19. {
  20. var spriteBone = spriteSkeletonBones[i];
  21. var characterBone = characterPartBones[i];
  22. var childWorldPose = spriteBone.GetChildrenWoldPose();
  23. spriteBone.position = spriteSkeleton.localToWorldMatrix.MultiplyPoint3x4(
  24. characterPart.worldToLocalMatrix.MultiplyPoint3x4(characterBone.position));
  25. spriteBone.rotation = characterBone.rotation;
  26. spriteBone.length = characterBone.length;
  27. spriteBone.name = characterBone.name;
  28. spriteBone.depth = characterBone.depth;
  29. spriteBone.bindPoseColor = characterBone.bindPoseColor;
  30. spriteBone.SetChildrenWorldPose(childWorldPose);
  31. }
  32. if (characterSkeleton.isPosePreview)
  33. spriteSkeleton.SetPosePreview();
  34. else
  35. spriteSkeleton.SetDefaultPose();
  36. }
  37. public static void DeassociateUnusedBones(this CharacterPartCache characterPart)
  38. {
  39. var skinningCache = characterPart.skinningCache;
  40. var bones = characterPart.bones;
  41. if (bones.Length == 0)
  42. return;
  43. Debug.Assert(characterPart.sprite != null);
  44. var mesh = characterPart.sprite.GetMesh();
  45. Debug.Assert(mesh != null);
  46. var vertices = mesh.vertices;
  47. var newBonesSet = new HashSet<BoneCache>();
  48. foreach (var vertex in vertices)
  49. {
  50. var boneWeight = vertex.editableBoneWeight;
  51. foreach (BoneWeightChannel channel in boneWeight)
  52. if (channel.enabled)
  53. newBonesSet.Add(bones[channel.boneIndex]);
  54. }
  55. bones = new List<BoneCache>(newBonesSet).ToArray();
  56. characterPart.bones = bones;
  57. characterPart.sprite.UpdateMesh(bones);
  58. skinningCache.events.characterPartChanged.Invoke(characterPart);
  59. }
  60. }
  61. }