SpriteSkinUtility.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using System;
  2. using System.Collections.Generic;
  3. using Unity.Collections;
  4. using Unity.Mathematics;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using UnityEngine.U2D;
  7. using UnityEngine.U2D.Common;
  8. namespace UnityEngine.U2D.Animation
  9. {
  10. internal enum SpriteSkinValidationResult
  11. {
  12. SpriteNotFound,
  13. SpriteHasNoSkinningInformation,
  14. SpriteHasNoWeights,
  15. RootTransformNotFound,
  16. InvalidTransformArray,
  17. InvalidTransformArrayLength,
  18. TransformArrayContainsNull,
  19. RootNotFoundInTransformArray,
  20. Ready
  21. }
  22. internal class NativeByteArray
  23. {
  24. public int Length => array.Length;
  25. public bool IsCreated => array.IsCreated;
  26. public byte this[int index] => array[index];
  27. public NativeArray<byte> array
  28. { get; }
  29. public NativeByteArray(NativeArray<byte> array)
  30. {
  31. this.array = array;
  32. }
  33. public void Dispose() => array.Dispose();
  34. }
  35. internal static class SpriteSkinUtility
  36. {
  37. internal static SpriteSkinValidationResult Validate(this SpriteSkin spriteSkin)
  38. {
  39. if (spriteSkin.spriteRenderer.sprite == null)
  40. return SpriteSkinValidationResult.SpriteNotFound;
  41. var bindPoses = spriteSkin.spriteRenderer.sprite.GetBindPoses();
  42. if (bindPoses.Length == 0)
  43. return SpriteSkinValidationResult.SpriteHasNoSkinningInformation;
  44. if (spriteSkin.rootBone == null)
  45. return SpriteSkinValidationResult.RootTransformNotFound;
  46. if (spriteSkin.boneTransforms == null)
  47. return SpriteSkinValidationResult.InvalidTransformArray;
  48. if (bindPoses.Length != spriteSkin.boneTransforms.Length)
  49. return SpriteSkinValidationResult.InvalidTransformArrayLength;
  50. var rootFound = false;
  51. foreach (var boneTransform in spriteSkin.boneTransforms)
  52. {
  53. if (boneTransform == null)
  54. return SpriteSkinValidationResult.TransformArrayContainsNull;
  55. if (boneTransform == spriteSkin.rootBone)
  56. rootFound = true;
  57. }
  58. if (!rootFound)
  59. return SpriteSkinValidationResult.RootNotFoundInTransformArray;
  60. return SpriteSkinValidationResult.Ready;
  61. }
  62. internal static void CreateBoneHierarchy(this SpriteSkin spriteSkin)
  63. {
  64. if (spriteSkin.spriteRenderer.sprite == null)
  65. throw new InvalidOperationException("SpriteRenderer has no Sprite set");
  66. var spriteBones = spriteSkin.spriteRenderer.sprite.GetBones();
  67. var transforms = new Transform[spriteBones.Length];
  68. Transform root = null;
  69. for (int i = 0; i < spriteBones.Length; ++i)
  70. {
  71. CreateGameObject(i, spriteBones, transforms, spriteSkin.transform);
  72. if (spriteBones[i].parentId < 0 && root == null)
  73. root = transforms[i];
  74. }
  75. spriteSkin.rootBone = root;
  76. spriteSkin.boneTransforms = transforms;
  77. }
  78. internal static int GetVertexStreamSize(this Sprite sprite)
  79. {
  80. int vertexStreamSize = 12;
  81. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Normal))
  82. vertexStreamSize = vertexStreamSize + 12;
  83. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent))
  84. vertexStreamSize = vertexStreamSize + 16;
  85. return vertexStreamSize;
  86. }
  87. internal static int GetVertexStreamOffset(this Sprite sprite, Rendering.VertexAttribute channel )
  88. {
  89. bool hasPosition = sprite.HasVertexAttribute(Rendering.VertexAttribute.Position);
  90. bool hasNormals = sprite.HasVertexAttribute(Rendering.VertexAttribute.Normal);
  91. bool hasTangents = sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent);
  92. switch(channel)
  93. {
  94. case Rendering.VertexAttribute.Position:
  95. return hasPosition ? 0 : -1;
  96. case Rendering.VertexAttribute.Normal:
  97. return hasNormals ? 12 : -1;
  98. case Rendering.VertexAttribute.Tangent:
  99. return hasTangents ? (hasNormals ? 24 : 12) : -1;
  100. }
  101. return -1;
  102. }
  103. private static void CreateGameObject(int index, SpriteBone[] spriteBones, Transform[] transforms, Transform root)
  104. {
  105. if (transforms[index] == null)
  106. {
  107. var spriteBone = spriteBones[index];
  108. if (spriteBone.parentId >= 0)
  109. CreateGameObject(spriteBone.parentId, spriteBones, transforms, root);
  110. var go = new GameObject(spriteBone.name);
  111. var transform = go.transform;
  112. if (spriteBone.parentId >= 0)
  113. transform.SetParent(transforms[spriteBone.parentId]);
  114. else
  115. transform.SetParent(root);
  116. transform.localPosition = spriteBone.position;
  117. transform.localRotation = spriteBone.rotation;
  118. transform.localScale = Vector3.one;
  119. transforms[index] = transform;
  120. }
  121. }
  122. internal static void ResetBindPose(this SpriteSkin spriteSkin)
  123. {
  124. if (!spriteSkin.isValid)
  125. throw new InvalidOperationException("SpriteSkin is not valid");
  126. var spriteBones = spriteSkin.spriteRenderer.sprite.GetBones();
  127. var boneTransforms = spriteSkin.boneTransforms;
  128. for (int i = 0; i < boneTransforms.Length; ++i)
  129. {
  130. var boneTransform = boneTransforms[i];
  131. var spriteBone = spriteBones[i];
  132. if (spriteBone.parentId != -1)
  133. {
  134. boneTransform.localPosition = spriteBone.position;
  135. boneTransform.localRotation = spriteBone.rotation;
  136. boneTransform.localScale = Vector3.one;
  137. }
  138. }
  139. }
  140. //TODO: Add other ways to find the transforms in case the named path fails
  141. internal static void Rebind(this SpriteSkin spriteSkin)
  142. {
  143. if (spriteSkin.spriteRenderer.sprite == null)
  144. throw new ArgumentException("SpriteRenderer has no Sprite set");
  145. if (spriteSkin.rootBone == null)
  146. throw new ArgumentException("SpriteSkin has no rootBone");
  147. var spriteBones = spriteSkin.spriteRenderer.sprite.GetBones();
  148. var boneTransforms = new List<Transform>();
  149. for (int i = 0; i < spriteBones.Length; ++i)
  150. {
  151. var boneTransformPath = CalculateBoneTransformPath(i, spriteBones);
  152. var boneTransform = spriteSkin.rootBone.Find(boneTransformPath);
  153. boneTransforms.Add(boneTransform);
  154. }
  155. spriteSkin.boneTransforms = boneTransforms.ToArray();
  156. }
  157. private static string CalculateBoneTransformPath(int index, SpriteBone[] spriteBones)
  158. {
  159. var path = "";
  160. while (index != -1)
  161. {
  162. var spriteBone = spriteBones[index];
  163. var spriteBoneName = spriteBone.name;
  164. if (spriteBone.parentId != -1)
  165. {
  166. if (string.IsNullOrEmpty(path))
  167. path = spriteBoneName;
  168. else
  169. path = spriteBoneName + "/" + path;
  170. }
  171. index = spriteBone.parentId;
  172. }
  173. return path;
  174. }
  175. private static int GetHash(Matrix4x4 matrix)
  176. {
  177. unsafe
  178. {
  179. uint* b = (uint*)&matrix;
  180. {
  181. var c = (char*)b;
  182. return (int)math.hash(c, 16 * sizeof(float));
  183. }
  184. }
  185. }
  186. internal static int CalculateTransformHash(this SpriteSkin spriteSkin)
  187. {
  188. int bits = 0;
  189. int boneTransformHash = GetHash(spriteSkin.transform.localToWorldMatrix) >> bits;
  190. bits++;
  191. foreach (var transform in spriteSkin.boneTransforms)
  192. {
  193. boneTransformHash ^= GetHash(transform.localToWorldMatrix) >> bits;
  194. bits = (bits + 1) % 8;
  195. }
  196. return boneTransformHash;
  197. }
  198. internal unsafe static void Deform(Sprite sprite, Matrix4x4 rootInv, NativeSlice<Vector3> vertices, NativeSlice<Vector4> tangents, NativeSlice<BoneWeight> boneWeights, NativeArray<Matrix4x4> boneTransforms, NativeSlice<Matrix4x4> bindPoses, NativeArray<byte> deformableVertices)
  199. {
  200. var verticesFloat3 = vertices.SliceWithStride<float3>();
  201. var tangentsFloat4 = tangents.SliceWithStride<float4>();
  202. var bindPosesFloat4x4 = bindPoses.SliceWithStride<float4x4>();
  203. var spriteVertexCount = sprite.GetVertexCount();
  204. var spriteVertexStreamSize = sprite.GetVertexStreamSize();
  205. var boneTransformsFloat4x4 = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float4x4>(boneTransforms.GetUnsafePtr(), boneTransforms.Length, Allocator.None);
  206. byte* deformedPosOffset = (byte*)NativeArrayUnsafeUtility.GetUnsafePtr(deformableVertices);
  207. NativeSlice<float3> deformableVerticesFloat3 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float3>(deformedPosOffset, spriteVertexStreamSize, spriteVertexCount);
  208. NativeSlice<float4> deformableTangentsFloat4 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float4>(deformedPosOffset, spriteVertexStreamSize, 1); // Just Dummy.
  209. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent))
  210. {
  211. byte* deformedTanOffset = deformedPosOffset + sprite.GetVertexStreamOffset(Rendering.VertexAttribute.Tangent);
  212. deformableTangentsFloat4 = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float4>(deformedTanOffset, spriteVertexStreamSize, spriteVertexCount);
  213. }
  214. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  215. var handle1 = CreateSafetyChecks<float4x4>(ref boneTransformsFloat4x4);
  216. var handle2 = CreateSafetyChecks<float3>(ref deformableVerticesFloat3);
  217. var handle3 = CreateSafetyChecks<float4>(ref deformableTangentsFloat4);
  218. #endif
  219. if (sprite.HasVertexAttribute(Rendering.VertexAttribute.Tangent))
  220. Deform(rootInv, verticesFloat3, tangentsFloat4, boneWeights, boneTransformsFloat4x4, bindPosesFloat4x4, deformableVerticesFloat3, deformableTangentsFloat4);
  221. else
  222. Deform(rootInv, verticesFloat3, boneWeights, boneTransformsFloat4x4, bindPosesFloat4x4, deformableVerticesFloat3);
  223. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  224. DisposeSafetyChecks(handle1);
  225. DisposeSafetyChecks(handle2);
  226. DisposeSafetyChecks(handle3);
  227. #endif
  228. }
  229. internal static void Deform(float4x4 rootInv, NativeSlice<float3> vertices, NativeSlice<BoneWeight> boneWeights, NativeArray<float4x4> boneTransforms, NativeSlice<float4x4> bindPoses, NativeSlice<float3> deformed)
  230. {
  231. if (boneTransforms.Length == 0)
  232. return;
  233. for (var i = 0; i < boneTransforms.Length; i++)
  234. {
  235. var bindPoseMat = bindPoses[i];
  236. var boneTransformMat = boneTransforms[i];
  237. boneTransforms[i] = math.mul(rootInv, math.mul(boneTransformMat, bindPoseMat));
  238. }
  239. for (var i = 0; i < vertices.Length; i++)
  240. {
  241. var bone0 = boneWeights[i].boneIndex0;
  242. var bone1 = boneWeights[i].boneIndex1;
  243. var bone2 = boneWeights[i].boneIndex2;
  244. var bone3 = boneWeights[i].boneIndex3;
  245. var vertex = vertices[i];
  246. deformed[i] =
  247. math.transform(boneTransforms[bone0], vertex) * boneWeights[i].weight0 +
  248. math.transform(boneTransforms[bone1], vertex) * boneWeights[i].weight1 +
  249. math.transform(boneTransforms[bone2], vertex) * boneWeights[i].weight2 +
  250. math.transform(boneTransforms[bone3], vertex) * boneWeights[i].weight3;
  251. }
  252. }
  253. internal static void Deform(float4x4 rootInv, NativeSlice<float3> vertices, NativeSlice<float4> tangents, NativeSlice<BoneWeight> boneWeights, NativeArray<float4x4> boneTransforms, NativeSlice<float4x4> bindPoses, NativeSlice<float3> deformed, NativeSlice<float4> deformedTangents)
  254. {
  255. if(boneTransforms.Length == 0)
  256. return;
  257. for (var i = 0; i < boneTransforms.Length; i++)
  258. {
  259. var bindPoseMat = bindPoses[i];
  260. var boneTransformMat = boneTransforms[i];
  261. boneTransforms[i] = math.mul(rootInv, math.mul(boneTransformMat, bindPoseMat));
  262. }
  263. for (var i = 0; i < vertices.Length; i++)
  264. {
  265. var bone0 = boneWeights[i].boneIndex0;
  266. var bone1 = boneWeights[i].boneIndex1;
  267. var bone2 = boneWeights[i].boneIndex2;
  268. var bone3 = boneWeights[i].boneIndex3;
  269. var vertex = vertices[i];
  270. deformed[i] =
  271. math.transform(boneTransforms[bone0], vertex) * boneWeights[i].weight0 +
  272. math.transform(boneTransforms[bone1], vertex) * boneWeights[i].weight1 +
  273. math.transform(boneTransforms[bone2], vertex) * boneWeights[i].weight2 +
  274. math.transform(boneTransforms[bone3], vertex) * boneWeights[i].weight3;
  275. var tangent = new float4(tangents[i].xyz, 0.0f);
  276. tangent =
  277. math.mul(boneTransforms[bone0], tangent) * boneWeights[i].weight0 +
  278. math.mul(boneTransforms[bone1], tangent) * boneWeights[i].weight1 +
  279. math.mul(boneTransforms[bone2], tangent) * boneWeights[i].weight2 +
  280. math.mul(boneTransforms[bone3], tangent) * boneWeights[i].weight3;
  281. deformedTangents[i] = new float4(math.normalize(tangent.xyz), tangents[i].w);
  282. }
  283. }
  284. internal unsafe static void Deform(Sprite sprite, Matrix4x4 invRoot, Transform[] boneTransformsArray, NativeArray<byte> deformVertexData)
  285. {
  286. Debug.Assert(sprite != null);
  287. Debug.Assert(sprite.GetVertexCount() == (deformVertexData.Length / sprite.GetVertexStreamSize()));
  288. var vertices = sprite.GetVertexAttribute<Vector3>(UnityEngine.Rendering.VertexAttribute.Position);
  289. var tangents = sprite.GetVertexAttribute<Vector4>(UnityEngine.Rendering.VertexAttribute.Tangent);
  290. var boneWeights = sprite.GetVertexAttribute<BoneWeight>(UnityEngine.Rendering.VertexAttribute.BlendWeight);
  291. var bindPoses = sprite.GetBindPoses();
  292. Debug.Assert(bindPoses.Length == boneTransformsArray.Length);
  293. Debug.Assert(boneWeights.Length == sprite.GetVertexCount());
  294. var boneTransforms = new NativeArray<Matrix4x4>(boneTransformsArray.Length, Allocator.Temp, NativeArrayOptions.UninitializedMemory);
  295. for (var i = 0; i < boneTransformsArray.Length; ++i)
  296. boneTransforms[i] = boneTransformsArray[i].localToWorldMatrix;
  297. Deform(sprite, invRoot, vertices, tangents, boneWeights, boneTransforms, bindPoses, deformVertexData);
  298. boneTransforms.Dispose();
  299. }
  300. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  301. private static AtomicSafetyHandle CreateSafetyChecks<T>(ref NativeArray<T> array) where T : struct
  302. {
  303. var handle = AtomicSafetyHandle.Create();
  304. AtomicSafetyHandle.SetAllowSecondaryVersionWriting(handle, true);
  305. AtomicSafetyHandle.UseSecondaryVersion(ref handle);
  306. NativeArrayUnsafeUtility.SetAtomicSafetyHandle<T>(ref array, handle);
  307. return handle;
  308. }
  309. private static AtomicSafetyHandle CreateSafetyChecks<T>(ref NativeSlice<T> array) where T : struct
  310. {
  311. var handle = AtomicSafetyHandle.Create();
  312. AtomicSafetyHandle.SetAllowSecondaryVersionWriting(handle, true);
  313. AtomicSafetyHandle.UseSecondaryVersion(ref handle);
  314. NativeSliceUnsafeUtility.SetAtomicSafetyHandle<T>(ref array, handle);
  315. return handle;
  316. }
  317. private static void DisposeSafetyChecks(AtomicSafetyHandle handle)
  318. {
  319. AtomicSafetyHandle.Release(handle);
  320. }
  321. #endif
  322. internal static void Bake(this SpriteSkin spriteSkin, NativeArray<byte> deformVertexData)
  323. {
  324. if (!spriteSkin.isValid)
  325. throw new Exception("Bake error: invalid SpriteSkin");
  326. var sprite = spriteSkin.spriteRenderer.sprite;
  327. var boneTransformsArray = spriteSkin.boneTransforms;
  328. Deform(sprite, Matrix4x4.identity, boneTransformsArray, deformVertexData);
  329. }
  330. internal unsafe static void CalculateBounds(this SpriteSkin spriteSkin)
  331. {
  332. Debug.Assert(spriteSkin.isValid);
  333. var sprite = spriteSkin.sprite;
  334. var deformVertexData = new NativeArray<byte>(sprite.GetVertexStreamSize() * sprite.GetVertexCount(), Allocator.Temp, NativeArrayOptions.UninitializedMemory);
  335. void* dataPtr = NativeArrayUnsafeUtility.GetUnsafePtr(deformVertexData);
  336. var deformedPosSlice = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<Vector3>(dataPtr, sprite.GetVertexStreamSize(), sprite.GetVertexCount());
  337. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  338. NativeSliceUnsafeUtility.SetAtomicSafetyHandle(ref deformedPosSlice, NativeArrayUnsafeUtility.GetAtomicSafetyHandle(deformVertexData));
  339. #endif
  340. spriteSkin.Bake(deformVertexData);
  341. UpdateBounds(spriteSkin, deformVertexData);
  342. deformVertexData.Dispose();
  343. }
  344. internal static Bounds CalculateSpriteSkinBounds(NativeSlice<float3> deformablePositions)
  345. {
  346. float3 min = deformablePositions[0];
  347. float3 max = deformablePositions[0];
  348. for (int j = 1; j < deformablePositions.Length; ++j)
  349. {
  350. min = math.min(min, deformablePositions[j]);
  351. max = math.max(max, deformablePositions[j]);
  352. }
  353. float3 ext = (max - min) * 0.5F;
  354. float3 ctr = min + ext;
  355. Bounds bounds = new Bounds();
  356. bounds.center = ctr;
  357. bounds.extents = ext;
  358. return bounds;
  359. }
  360. internal static unsafe void UpdateBounds(this SpriteSkin spriteSkin, NativeArray<byte> deformedVertices)
  361. {
  362. byte* deformedPosOffset = (byte*)NativeArrayUnsafeUtility.GetUnsafePtr(deformedVertices);
  363. var spriteVertexCount = spriteSkin.sprite.GetVertexCount();
  364. var spriteVertexStreamSize = spriteSkin.sprite.GetVertexStreamSize();
  365. NativeSlice<float3> deformedPositions = NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice<float3>(deformedPosOffset, spriteVertexStreamSize, spriteVertexCount);
  366. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  367. var handle = CreateSafetyChecks<float3>(ref deformedPositions);
  368. #endif
  369. spriteSkin.bounds = CalculateSpriteSkinBounds(deformedPositions);
  370. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  371. DisposeSafetyChecks(handle);
  372. #endif
  373. InternalEngineBridge.SetLocalAABB(spriteSkin.spriteRenderer, spriteSkin.bounds);
  374. }
  375. }
  376. }