源战役客户端
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

865 líneas
35 KiB

  1. /******************************************************************************
  2. * Spine Runtimes Software License v2.5
  3. *
  4. * Copyright (c) 2013-2016, Esoteric Software
  5. * All rights reserved.
  6. *
  7. * You are granted a perpetual, non-exclusive, non-sublicensable, and
  8. * non-transferable license to use, install, execute, and perform the Spine
  9. * Runtimes software and derivative works solely for personal or internal
  10. * use. Without the written permission of Esoteric Software (see Section 2 of
  11. * the Spine Software License Agreement), you may not (a) modify, translate,
  12. * adapt, or develop new applications using the Spine Runtimes or otherwise
  13. * create derivative works or improvements of the Spine Runtimes or (b) remove,
  14. * delete, alter, or obscure any trademarks or any copyright, trademark, patent,
  15. * or other intellectual property or proprietary rights notices on or in the
  16. * Software, including any copy thereof. Redistributions in binary or source
  17. * form must include this license and terms.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
  20. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  21. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  22. * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
  25. * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
  26. * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. * POSSIBILITY OF SUCH DAMAGE.
  29. *****************************************************************************/
  30. #if (UNITY_5 || UNITY_5_3_OR_NEWER || UNITY_WSA || UNITY_WP8 || UNITY_WP8_1)
  31. #define IS_UNITY
  32. #endif
  33. using System;
  34. using System.IO;
  35. using System.Collections.Generic;
  36. #if WINDOWS_STOREAPP
  37. using System.Threading.Tasks;
  38. using Windows.Storage;
  39. #endif
  40. namespace Spine {
  41. public class SkeletonJson {
  42. public float Scale { get; set; }
  43. private AttachmentLoader attachmentLoader;
  44. private List<LinkedMesh> linkedMeshes = new List<LinkedMesh>();
  45. public SkeletonJson (params Atlas[] atlasArray)
  46. : this(new AtlasAttachmentLoader(atlasArray)) {
  47. }
  48. public SkeletonJson (AttachmentLoader attachmentLoader) {
  49. if (attachmentLoader == null) throw new ArgumentNullException("attachmentLoader", "attachmentLoader cannot be null.");
  50. this.attachmentLoader = attachmentLoader;
  51. Scale = 1;
  52. }
  53. #if !IS_UNITY && WINDOWS_STOREAPP
  54. private async Task<SkeletonData> ReadFile(string path) {
  55. var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
  56. var file = await folder.GetFileAsync(path).AsTask().ConfigureAwait(false);
  57. using (var reader = new StreamReader(await file.OpenStreamForReadAsync().ConfigureAwait(false))) {
  58. SkeletonData skeletonData = ReadSkeletonData(reader);
  59. skeletonData.Name = Path.GetFileNameWithoutExtension(path);
  60. return skeletonData;
  61. }
  62. }
  63. public SkeletonData ReadSkeletonData (string path) {
  64. return this.ReadFile(path).Result;
  65. }
  66. #else
  67. public SkeletonData ReadSkeletonData (string path) {
  68. #if WINDOWS_PHONE
  69. using (var reader = new StreamReader(Microsoft.Xna.Framework.TitleContainer.OpenStream(path))) {
  70. #else
  71. using (var reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))) {
  72. #endif
  73. SkeletonData skeletonData = ReadSkeletonData(reader);
  74. skeletonData.name = Path.GetFileNameWithoutExtension(path);
  75. return skeletonData;
  76. }
  77. }
  78. #endif
  79. public SkeletonData ReadSkeletonData (TextReader reader) {
  80. if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null.");
  81. float scale = this.Scale;
  82. var skeletonData = new SkeletonData();
  83. var root = Json.Deserialize(reader) as Dictionary<string, Object>;
  84. if (root == null) throw new Exception("Invalid JSON.");
  85. // Skeleton.
  86. if (root.ContainsKey("skeleton")) {
  87. var skeletonMap = (Dictionary<string, Object>)root["skeleton"];
  88. skeletonData.hash = (string)skeletonMap["hash"];
  89. skeletonData.version = (string)skeletonMap["spine"];
  90. skeletonData.width = GetFloat(skeletonMap, "width", 0);
  91. skeletonData.height = GetFloat(skeletonMap, "height", 0);
  92. skeletonData.fps = GetFloat(skeletonMap, "fps", 0);
  93. skeletonData.imagesPath = GetString(skeletonMap, "images", null);
  94. }
  95. // Bones.
  96. foreach (Dictionary<string, Object> boneMap in (List<Object>)root["bones"]) {
  97. BoneData parent = null;
  98. if (boneMap.ContainsKey("parent")) {
  99. parent = skeletonData.FindBone((string)boneMap["parent"]);
  100. if (parent == null)
  101. throw new Exception("Parent bone not found: " + boneMap["parent"]);
  102. }
  103. var data = new BoneData(skeletonData.Bones.Count, (string)boneMap["name"], parent);
  104. data.length = GetFloat(boneMap, "length", 0) * scale;
  105. data.x = GetFloat(boneMap, "x", 0) * scale;
  106. data.y = GetFloat(boneMap, "y", 0) * scale;
  107. data.rotation = GetFloat(boneMap, "rotation", 0);
  108. data.scaleX = GetFloat(boneMap, "scaleX", 1);
  109. data.scaleY = GetFloat(boneMap, "scaleY", 1);
  110. data.shearX = GetFloat(boneMap, "shearX", 0);
  111. data.shearY = GetFloat(boneMap, "shearY", 0);
  112. string tm = GetString(boneMap, "transform", TransformMode.Normal.ToString());
  113. data.transformMode = (TransformMode)Enum.Parse(typeof(TransformMode), tm, true);
  114. skeletonData.bones.Add(data);
  115. }
  116. // Slots.
  117. if (root.ContainsKey("slots")) {
  118. foreach (Dictionary<string, Object> slotMap in (List<Object>)root["slots"]) {
  119. var slotName = (string)slotMap["name"];
  120. var boneName = (string)slotMap["bone"];
  121. BoneData boneData = skeletonData.FindBone(boneName);
  122. if (boneData == null) throw new Exception("Slot bone not found: " + boneName);
  123. var data = new SlotData(skeletonData.Slots.Count, slotName, boneData);
  124. if (slotMap.ContainsKey("color")) {
  125. string color = (string)slotMap["color"];
  126. data.r = ToColor(color, 0);
  127. data.g = ToColor(color, 1);
  128. data.b = ToColor(color, 2);
  129. data.a = ToColor(color, 3);
  130. }
  131. if (slotMap.ContainsKey("dark")) {
  132. var color2 = (string)slotMap["dark"];
  133. data.r2 = ToColor(color2, 0, 6); // expectedLength = 6. ie. "RRGGBB"
  134. data.g2 = ToColor(color2, 1, 6);
  135. data.b2 = ToColor(color2, 2, 6);
  136. data.hasSecondColor = true;
  137. }
  138. data.attachmentName = GetString(slotMap, "attachment", null);
  139. if (slotMap.ContainsKey("blend"))
  140. data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (string)slotMap["blend"], true);
  141. else
  142. data.blendMode = BlendMode.Normal;
  143. skeletonData.slots.Add(data);
  144. }
  145. }
  146. // IK constraints.
  147. if (root.ContainsKey("ik")) {
  148. foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["ik"]) {
  149. IkConstraintData data = new IkConstraintData((string)constraintMap["name"]);
  150. data.order = GetInt(constraintMap, "order", 0);
  151. foreach (string boneName in (List<Object>)constraintMap["bones"]) {
  152. BoneData bone = skeletonData.FindBone(boneName);
  153. if (bone == null) throw new Exception("IK constraint bone not found: " + boneName);
  154. data.bones.Add(bone);
  155. }
  156. string targetName = (string)constraintMap["target"];
  157. data.target = skeletonData.FindBone(targetName);
  158. if (data.target == null) throw new Exception("Target bone not found: " + targetName);
  159. data.bendDirection = GetBoolean(constraintMap, "bendPositive", true) ? 1 : -1;
  160. data.mix = GetFloat(constraintMap, "mix", 1);
  161. skeletonData.ikConstraints.Add(data);
  162. }
  163. }
  164. // Transform constraints.
  165. if (root.ContainsKey("transform")) {
  166. foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["transform"]) {
  167. TransformConstraintData data = new TransformConstraintData((string)constraintMap["name"]);
  168. data.order = GetInt(constraintMap, "order", 0);
  169. foreach (string boneName in (List<Object>)constraintMap["bones"]) {
  170. BoneData bone = skeletonData.FindBone(boneName);
  171. if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName);
  172. data.bones.Add(bone);
  173. }
  174. string targetName = (string)constraintMap["target"];
  175. data.target = skeletonData.FindBone(targetName);
  176. if (data.target == null) throw new Exception("Target bone not found: " + targetName);
  177. data.local = GetBoolean(constraintMap, "local", false);
  178. data.relative = GetBoolean(constraintMap, "relative", false);
  179. data.offsetRotation = GetFloat(constraintMap, "rotation", 0);
  180. data.offsetX = GetFloat(constraintMap, "x", 0) * scale;
  181. data.offsetY = GetFloat(constraintMap, "y", 0) * scale;
  182. data.offsetScaleX = GetFloat(constraintMap, "scaleX", 0);
  183. data.offsetScaleY = GetFloat(constraintMap, "scaleY", 0);
  184. data.offsetShearY = GetFloat(constraintMap, "shearY", 0);
  185. data.rotateMix = GetFloat(constraintMap, "rotateMix", 1);
  186. data.translateMix = GetFloat(constraintMap, "translateMix", 1);
  187. data.scaleMix = GetFloat(constraintMap, "scaleMix", 1);
  188. data.shearMix = GetFloat(constraintMap, "shearMix", 1);
  189. skeletonData.transformConstraints.Add(data);
  190. }
  191. }
  192. // Path constraints.
  193. if(root.ContainsKey("path")) {
  194. foreach (Dictionary<string, Object> constraintMap in (List<Object>)root["path"]) {
  195. PathConstraintData data = new PathConstraintData((string)constraintMap["name"]);
  196. data.order = GetInt(constraintMap, "order", 0);
  197. foreach (string boneName in (List<Object>)constraintMap["bones"]) {
  198. BoneData bone = skeletonData.FindBone(boneName);
  199. if (bone == null) throw new Exception("Path bone not found: " + boneName);
  200. data.bones.Add(bone);
  201. }
  202. string targetName = (string)constraintMap["target"];
  203. data.target = skeletonData.FindSlot(targetName);
  204. if (data.target == null) throw new Exception("Target slot not found: " + targetName);
  205. data.positionMode = (PositionMode)Enum.Parse(typeof(PositionMode), GetString(constraintMap, "positionMode", "percent"), true);
  206. data.spacingMode = (SpacingMode)Enum.Parse(typeof(SpacingMode), GetString(constraintMap, "spacingMode", "length"), true);
  207. data.rotateMode = (RotateMode)Enum.Parse(typeof(RotateMode), GetString(constraintMap, "rotateMode", "tangent"), true);
  208. data.offsetRotation = GetFloat(constraintMap, "rotation", 0);
  209. data.position = GetFloat(constraintMap, "position", 0);
  210. if (data.positionMode == PositionMode.Fixed) data.position *= scale;
  211. data.spacing = GetFloat(constraintMap, "spacing", 0);
  212. if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) data.spacing *= scale;
  213. data.rotateMix = GetFloat(constraintMap, "rotateMix", 1);
  214. data.translateMix = GetFloat(constraintMap, "translateMix", 1);
  215. skeletonData.pathConstraints.Add(data);
  216. }
  217. }
  218. // Skins.
  219. if (root.ContainsKey("skins")) {
  220. foreach (KeyValuePair<string, Object> skinMap in (Dictionary<string, Object>)root["skins"]) {
  221. var skin = new Skin(skinMap.Key);
  222. foreach (KeyValuePair<string, Object> slotEntry in (Dictionary<string, Object>)skinMap.Value) {
  223. int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
  224. foreach (KeyValuePair<string, Object> entry in ((Dictionary<string, Object>)slotEntry.Value)) {
  225. try {
  226. Attachment attachment = ReadAttachment((Dictionary<string, Object>)entry.Value, skin, slotIndex, entry.Key, skeletonData);
  227. if (attachment != null) skin.AddAttachment(slotIndex, entry.Key, attachment);
  228. } catch (Exception e) {
  229. throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e);
  230. }
  231. }
  232. }
  233. skeletonData.skins.Add(skin);
  234. if (skin.name == "default") skeletonData.defaultSkin = skin;
  235. }
  236. }
  237. // Linked meshes.
  238. for (int i = 0, n = linkedMeshes.Count; i < n; i++) {
  239. LinkedMesh linkedMesh = linkedMeshes[i];
  240. Skin skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.FindSkin(linkedMesh.skin);
  241. if (skin == null) throw new Exception("Slot not found: " + linkedMesh.skin);
  242. Attachment parent = skin.GetAttachment(linkedMesh.slotIndex, linkedMesh.parent);
  243. if (parent == null) throw new Exception("Parent mesh not found: " + linkedMesh.parent);
  244. linkedMesh.mesh.ParentMesh = (MeshAttachment)parent;
  245. linkedMesh.mesh.UpdateUVs();
  246. }
  247. linkedMeshes.Clear();
  248. // Events.
  249. if (root.ContainsKey("events")) {
  250. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)root["events"]) {
  251. var entryMap = (Dictionary<string, Object>)entry.Value;
  252. var data = new EventData(entry.Key);
  253. data.Int = GetInt(entryMap, "int", 0);
  254. data.Float = GetFloat(entryMap, "float", 0);
  255. data.String = GetString(entryMap, "string", string.Empty);
  256. skeletonData.events.Add(data);
  257. }
  258. }
  259. // Animations.
  260. if (root.ContainsKey("animations")) {
  261. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)root["animations"]) {
  262. try {
  263. ReadAnimation((Dictionary<string, Object>)entry.Value, entry.Key, skeletonData);
  264. } catch (Exception e) {
  265. throw new Exception("Error reading animation: " + entry.Key, e);
  266. }
  267. }
  268. }
  269. skeletonData.bones.TrimExcess();
  270. skeletonData.slots.TrimExcess();
  271. skeletonData.skins.TrimExcess();
  272. skeletonData.events.TrimExcess();
  273. skeletonData.animations.TrimExcess();
  274. skeletonData.ikConstraints.TrimExcess();
  275. return skeletonData;
  276. }
  277. private Attachment ReadAttachment (Dictionary<string, Object> map, Skin skin, int slotIndex, string name, SkeletonData skeletonData) {
  278. float scale = this.Scale;
  279. name = GetString(map, "name", name);
  280. var typeName = GetString(map, "type", "region");
  281. if (typeName == "skinnedmesh") typeName = "weightedmesh";
  282. if (typeName == "weightedmesh") typeName = "mesh";
  283. if (typeName == "weightedlinkedmesh") typeName = "linkedmesh";
  284. var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true);
  285. string path = GetString(map, "path", name);
  286. switch (type) {
  287. case AttachmentType.Region:
  288. RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
  289. if (region == null) return null;
  290. region.Path = path;
  291. region.x = GetFloat(map, "x", 0) * scale;
  292. region.y = GetFloat(map, "y", 0) * scale;
  293. region.scaleX = GetFloat(map, "scaleX", 1);
  294. region.scaleY = GetFloat(map, "scaleY", 1);
  295. region.rotation = GetFloat(map, "rotation", 0);
  296. region.width = GetFloat(map, "width", 32) * scale;
  297. region.height = GetFloat(map, "height", 32) * scale;
  298. if (map.ContainsKey("color")) {
  299. var color = (string)map["color"];
  300. region.r = ToColor(color, 0);
  301. region.g = ToColor(color, 1);
  302. region.b = ToColor(color, 2);
  303. region.a = ToColor(color, 3);
  304. }
  305. region.UpdateOffset();
  306. return region;
  307. case AttachmentType.Boundingbox:
  308. BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
  309. if (box == null) return null;
  310. ReadVertices(map, box, GetInt(map, "vertexCount", 0) << 1);
  311. return box;
  312. case AttachmentType.Mesh:
  313. case AttachmentType.Linkedmesh: {
  314. MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
  315. if (mesh == null) return null;
  316. mesh.Path = path;
  317. if (map.ContainsKey("color")) {
  318. var color = (string)map["color"];
  319. mesh.r = ToColor(color, 0);
  320. mesh.g = ToColor(color, 1);
  321. mesh.b = ToColor(color, 2);
  322. mesh.a = ToColor(color, 3);
  323. }
  324. mesh.Width = GetFloat(map, "width", 0) * scale;
  325. mesh.Height = GetFloat(map, "height", 0) * scale;
  326. string parent = GetString(map, "parent", null);
  327. if (parent != null) {
  328. mesh.InheritDeform = GetBoolean(map, "deform", true);
  329. linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent));
  330. return mesh;
  331. }
  332. float[] uvs = GetFloatArray(map, "uvs", 1);
  333. ReadVertices(map, mesh, uvs.Length);
  334. mesh.triangles = GetIntArray(map, "triangles");
  335. mesh.regionUVs = uvs;
  336. mesh.UpdateUVs();
  337. if (map.ContainsKey("hull")) mesh.HullLength = GetInt(map, "hull", 0) * 2;
  338. if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges");
  339. return mesh;
  340. }
  341. case AttachmentType.Path: {
  342. PathAttachment pathAttachment = attachmentLoader.NewPathAttachment(skin, name);
  343. if (pathAttachment == null) return null;
  344. pathAttachment.closed = GetBoolean(map, "closed", false);
  345. pathAttachment.constantSpeed = GetBoolean(map, "constantSpeed", true);
  346. int vertexCount = GetInt(map, "vertexCount", 0);
  347. ReadVertices(map, pathAttachment, vertexCount << 1);
  348. // potential BOZO see Java impl
  349. pathAttachment.lengths = GetFloatArray(map, "lengths", scale);
  350. return pathAttachment;
  351. }
  352. case AttachmentType.Point: {
  353. PointAttachment point = attachmentLoader.NewPointAttachment(skin, name);
  354. if (point == null) return null;
  355. point.x = GetFloat(map, "x", 0) * scale;
  356. point.y = GetFloat(map, "y", 0) * scale;
  357. point.rotation = GetFloat(map, "rotation", 0);
  358. //string color = GetString(map, "color", null);
  359. //if (color != null) point.color = color;
  360. return point;
  361. }
  362. case AttachmentType.Clipping: {
  363. ClippingAttachment clip = attachmentLoader.NewClippingAttachment(skin, name);
  364. if (clip == null) return null;
  365. string end = GetString(map, "end", null);
  366. if (end != null) {
  367. SlotData slot = skeletonData.FindSlot(end);
  368. if (slot == null) throw new Exception("Clipping end slot not found: " + end);
  369. clip.EndSlot = slot;
  370. }
  371. ReadVertices(map, clip, GetInt(map, "vertexCount", 0) << 1);
  372. //string color = GetString(map, "color", null);
  373. // if (color != null) clip.color = color;
  374. return clip;
  375. }
  376. }
  377. return null;
  378. }
  379. private void ReadVertices (Dictionary<string, Object> map, VertexAttachment attachment, int verticesLength) {
  380. attachment.WorldVerticesLength = verticesLength;
  381. float[] vertices = GetFloatArray(map, "vertices", 1);
  382. float scale = Scale;
  383. if (verticesLength == vertices.Length) {
  384. if (scale != 1) {
  385. for (int i = 0; i < vertices.Length; i++) {
  386. vertices[i] *= scale;
  387. }
  388. }
  389. attachment.vertices = vertices;
  390. return;
  391. }
  392. ExposedList<float> weights = new ExposedList<float>(verticesLength * 3 * 3);
  393. ExposedList<int> bones = new ExposedList<int>(verticesLength * 3);
  394. for (int i = 0, n = vertices.Length; i < n;) {
  395. int boneCount = (int)vertices[i++];
  396. bones.Add(boneCount);
  397. for (int nn = i + boneCount * 4; i < nn; i += 4) {
  398. bones.Add((int)vertices[i]);
  399. weights.Add(vertices[i + 1] * this.Scale);
  400. weights.Add(vertices[i + 2] * this.Scale);
  401. weights.Add(vertices[i + 3]);
  402. }
  403. }
  404. attachment.bones = bones.ToArray();
  405. attachment.vertices = weights.ToArray();
  406. }
  407. private void ReadAnimation (Dictionary<string, Object> map, string name, SkeletonData skeletonData) {
  408. var scale = this.Scale;
  409. var timelines = new ExposedList<Timeline>();
  410. float duration = 0;
  411. // Slot timelines.
  412. if (map.ContainsKey("slots")) {
  413. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)map["slots"]) {
  414. string slotName = entry.Key;
  415. int slotIndex = skeletonData.FindSlotIndex(slotName);
  416. var timelineMap = (Dictionary<string, Object>)entry.Value;
  417. foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
  418. var values = (List<Object>)timelineEntry.Value;
  419. var timelineName = (string)timelineEntry.Key;
  420. if (timelineName == "attachment") {
  421. var timeline = new AttachmentTimeline(values.Count);
  422. timeline.slotIndex = slotIndex;
  423. int frameIndex = 0;
  424. foreach (Dictionary<string, Object> valueMap in values) {
  425. float time = (float)valueMap["time"];
  426. timeline.SetFrame(frameIndex++, time, (string)valueMap["name"]);
  427. }
  428. timelines.Add(timeline);
  429. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  430. } else if (timelineName == "color") {
  431. var timeline = new ColorTimeline(values.Count);
  432. timeline.slotIndex = slotIndex;
  433. int frameIndex = 0;
  434. foreach (Dictionary<string, Object> valueMap in values) {
  435. float time = (float)valueMap["time"];
  436. string c = (string)valueMap["color"];
  437. timeline.SetFrame(frameIndex, time, ToColor(c, 0), ToColor(c, 1), ToColor(c, 2), ToColor(c, 3));
  438. ReadCurve(valueMap, timeline, frameIndex);
  439. frameIndex++;
  440. }
  441. timelines.Add(timeline);
  442. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * ColorTimeline.ENTRIES]);
  443. } else if (timelineName == "twoColor") {
  444. var timeline = new TwoColorTimeline(values.Count);
  445. timeline.slotIndex = slotIndex;
  446. int frameIndex = 0;
  447. foreach (Dictionary<string, Object> valueMap in values) {
  448. float time = (float)valueMap["time"];
  449. string light = (string)valueMap["light"];
  450. string dark = (string)valueMap["dark"];
  451. timeline.SetFrame(frameIndex, time, ToColor(light, 0), ToColor(light, 1), ToColor(light, 2), ToColor(light, 3),
  452. ToColor(dark, 0, 6), ToColor(dark, 1, 6), ToColor(dark, 2, 6));
  453. ReadCurve(valueMap, timeline, frameIndex);
  454. frameIndex++;
  455. }
  456. timelines.Add(timeline);
  457. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TwoColorTimeline.ENTRIES]);
  458. } else
  459. throw new Exception("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
  460. }
  461. }
  462. }
  463. // Bone timelines.
  464. if (map.ContainsKey("bones")) {
  465. foreach (KeyValuePair<string, Object> entry in (Dictionary<string, Object>)map["bones"]) {
  466. string boneName = entry.Key;
  467. int boneIndex = skeletonData.FindBoneIndex(boneName);
  468. if (boneIndex == -1) throw new Exception("Bone not found: " + boneName);
  469. var timelineMap = (Dictionary<string, Object>)entry.Value;
  470. foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
  471. var values = (List<Object>)timelineEntry.Value;
  472. var timelineName = (string)timelineEntry.Key;
  473. if (timelineName == "rotate") {
  474. var timeline = new RotateTimeline(values.Count);
  475. timeline.boneIndex = boneIndex;
  476. int frameIndex = 0;
  477. foreach (Dictionary<string, Object> valueMap in values) {
  478. timeline.SetFrame(frameIndex, (float)valueMap["time"], (float)valueMap["angle"]);
  479. ReadCurve(valueMap, timeline, frameIndex);
  480. frameIndex++;
  481. }
  482. timelines.Add(timeline);
  483. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * RotateTimeline.ENTRIES]);
  484. } else if (timelineName == "translate" || timelineName == "scale" || timelineName == "shear") {
  485. TranslateTimeline timeline;
  486. float timelineScale = 1;
  487. if (timelineName == "scale")
  488. timeline = new ScaleTimeline(values.Count);
  489. else if (timelineName == "shear")
  490. timeline = new ShearTimeline(values.Count);
  491. else {
  492. timeline = new TranslateTimeline(values.Count);
  493. timelineScale = scale;
  494. }
  495. timeline.boneIndex = boneIndex;
  496. int frameIndex = 0;
  497. foreach (Dictionary<string, Object> valueMap in values) {
  498. float time = (float)valueMap["time"];
  499. float x = GetFloat(valueMap, "x", 0);
  500. float y = GetFloat(valueMap, "y", 0);
  501. timeline.SetFrame(frameIndex, time, x * timelineScale, y * timelineScale);
  502. ReadCurve(valueMap, timeline, frameIndex);
  503. frameIndex++;
  504. }
  505. timelines.Add(timeline);
  506. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TranslateTimeline.ENTRIES]);
  507. } else
  508. throw new Exception("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
  509. }
  510. }
  511. }
  512. // IK constraint timelines.
  513. if (map.ContainsKey("ik")) {
  514. foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["ik"]) {
  515. IkConstraintData constraint = skeletonData.FindIkConstraint(constraintMap.Key);
  516. var values = (List<Object>)constraintMap.Value;
  517. var timeline = new IkConstraintTimeline(values.Count);
  518. timeline.ikConstraintIndex = skeletonData.ikConstraints.IndexOf(constraint);
  519. int frameIndex = 0;
  520. foreach (Dictionary<string, Object> valueMap in values) {
  521. float time = (float)valueMap["time"];
  522. float mix = GetFloat(valueMap, "mix", 1);
  523. bool bendPositive = GetBoolean(valueMap, "bendPositive", true);
  524. timeline.SetFrame(frameIndex, time, mix, bendPositive ? 1 : -1);
  525. ReadCurve(valueMap, timeline, frameIndex);
  526. frameIndex++;
  527. }
  528. timelines.Add(timeline);
  529. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * IkConstraintTimeline.ENTRIES]);
  530. }
  531. }
  532. // Transform constraint timelines.
  533. if (map.ContainsKey("transform")) {
  534. foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["transform"]) {
  535. TransformConstraintData constraint = skeletonData.FindTransformConstraint(constraintMap.Key);
  536. var values = (List<Object>)constraintMap.Value;
  537. var timeline = new TransformConstraintTimeline(values.Count);
  538. timeline.transformConstraintIndex = skeletonData.transformConstraints.IndexOf(constraint);
  539. int frameIndex = 0;
  540. foreach (Dictionary<string, Object> valueMap in values) {
  541. float time = (float)valueMap["time"];
  542. float rotateMix = GetFloat(valueMap, "rotateMix", 1);
  543. float translateMix = GetFloat(valueMap, "translateMix", 1);
  544. float scaleMix = GetFloat(valueMap, "scaleMix", 1);
  545. float shearMix = GetFloat(valueMap, "shearMix", 1);
  546. timeline.SetFrame(frameIndex, time, rotateMix, translateMix, scaleMix, shearMix);
  547. ReadCurve(valueMap, timeline, frameIndex);
  548. frameIndex++;
  549. }
  550. timelines.Add(timeline);
  551. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * TransformConstraintTimeline.ENTRIES]);
  552. }
  553. }
  554. // Path constraint timelines.
  555. if (map.ContainsKey("paths")) {
  556. foreach (KeyValuePair<string, Object> constraintMap in (Dictionary<string, Object>)map["paths"]) {
  557. int index = skeletonData.FindPathConstraintIndex(constraintMap.Key);
  558. if (index == -1) throw new Exception("Path constraint not found: " + constraintMap.Key);
  559. PathConstraintData data = skeletonData.pathConstraints.Items[index];
  560. var timelineMap = (Dictionary<string, Object>)constraintMap.Value;
  561. foreach (KeyValuePair<string, Object> timelineEntry in timelineMap) {
  562. var values = (List<Object>)timelineEntry.Value;
  563. var timelineName = (string)timelineEntry.Key;
  564. if (timelineName == "position" || timelineName == "spacing") {
  565. PathConstraintPositionTimeline timeline;
  566. float timelineScale = 1;
  567. if (timelineName == "spacing") {
  568. timeline = new PathConstraintSpacingTimeline(values.Count);
  569. if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) timelineScale = scale;
  570. }
  571. else {
  572. timeline = new PathConstraintPositionTimeline(values.Count);
  573. if (data.positionMode == PositionMode.Fixed) timelineScale = scale;
  574. }
  575. timeline.pathConstraintIndex = index;
  576. int frameIndex = 0;
  577. foreach (Dictionary<string, Object> valueMap in values) {
  578. timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, timelineName, 0) * timelineScale);
  579. ReadCurve(valueMap, timeline, frameIndex);
  580. frameIndex++;
  581. }
  582. timelines.Add(timeline);
  583. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * PathConstraintPositionTimeline.ENTRIES]);
  584. }
  585. else if (timelineName == "mix") {
  586. PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(values.Count);
  587. timeline.pathConstraintIndex = index;
  588. int frameIndex = 0;
  589. foreach (Dictionary<string, Object> valueMap in values) {
  590. timeline.SetFrame(frameIndex, (float)valueMap["time"], GetFloat(valueMap, "rotateMix", 1), GetFloat(valueMap, "translateMix", 1));
  591. ReadCurve(valueMap, timeline, frameIndex);
  592. frameIndex++;
  593. }
  594. timelines.Add(timeline);
  595. duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * PathConstraintMixTimeline.ENTRIES]);
  596. }
  597. }
  598. }
  599. }
  600. // Deform timelines.
  601. if (map.ContainsKey("deform")) {
  602. foreach (KeyValuePair<string, Object> deformMap in (Dictionary<string, Object>)map["deform"]) {
  603. Skin skin = skeletonData.FindSkin(deformMap.Key);
  604. foreach (KeyValuePair<string, Object> slotMap in (Dictionary<string, Object>)deformMap.Value) {
  605. int slotIndex = skeletonData.FindSlotIndex(slotMap.Key);
  606. if (slotIndex == -1) throw new Exception("Slot not found: " + slotMap.Key);
  607. foreach (KeyValuePair<string, Object> timelineMap in (Dictionary<string, Object>)slotMap.Value) {
  608. var values = (List<Object>)timelineMap.Value;
  609. VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, timelineMap.Key);
  610. if (attachment == null) throw new Exception("Deform attachment not found: " + timelineMap.Key);
  611. bool weighted = attachment.bones != null;
  612. float[] vertices = attachment.vertices;
  613. int deformLength = weighted ? vertices.Length / 3 * 2 : vertices.Length;
  614. var timeline = new DeformTimeline(values.Count);
  615. timeline.slotIndex = slotIndex;
  616. timeline.attachment = attachment;
  617. int frameIndex = 0;
  618. foreach (Dictionary<string, Object> valueMap in values) {
  619. float[] deform;
  620. if (!valueMap.ContainsKey("vertices")) {
  621. deform = weighted ? new float[deformLength] : vertices;
  622. } else {
  623. deform = new float[deformLength];
  624. int start = GetInt(valueMap, "offset", 0);
  625. float[] verticesValue = GetFloatArray(valueMap, "vertices", 1);
  626. Array.Copy(verticesValue, 0, deform, start, verticesValue.Length);
  627. if (scale != 1) {
  628. for (int i = start, n = i + verticesValue.Length; i < n; i++)
  629. deform[i] *= scale;
  630. }
  631. if (!weighted) {
  632. for (int i = 0; i < deformLength; i++)
  633. deform[i] += vertices[i];
  634. }
  635. }
  636. timeline.SetFrame(frameIndex, (float)valueMap["time"], deform);
  637. ReadCurve(valueMap, timeline, frameIndex);
  638. frameIndex++;
  639. }
  640. timelines.Add(timeline);
  641. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  642. }
  643. }
  644. }
  645. }
  646. // Draw order timeline.
  647. if (map.ContainsKey("drawOrder") || map.ContainsKey("draworder")) {
  648. var values = (List<Object>)map[map.ContainsKey("drawOrder") ? "drawOrder" : "draworder"];
  649. var timeline = new DrawOrderTimeline(values.Count);
  650. int slotCount = skeletonData.slots.Count;
  651. int frameIndex = 0;
  652. foreach (Dictionary<string, Object> drawOrderMap in values) {
  653. int[] drawOrder = null;
  654. if (drawOrderMap.ContainsKey("offsets")) {
  655. drawOrder = new int[slotCount];
  656. for (int i = slotCount - 1; i >= 0; i--)
  657. drawOrder[i] = -1;
  658. var offsets = (List<Object>)drawOrderMap["offsets"];
  659. int[] unchanged = new int[slotCount - offsets.Count];
  660. int originalIndex = 0, unchangedIndex = 0;
  661. foreach (Dictionary<string, Object> offsetMap in offsets) {
  662. int slotIndex = skeletonData.FindSlotIndex((string)offsetMap["slot"]);
  663. if (slotIndex == -1) throw new Exception("Slot not found: " + offsetMap["slot"]);
  664. // Collect unchanged items.
  665. while (originalIndex != slotIndex)
  666. unchanged[unchangedIndex++] = originalIndex++;
  667. // Set changed items.
  668. int index = originalIndex + (int)(float)offsetMap["offset"];
  669. drawOrder[index] = originalIndex++;
  670. }
  671. // Collect remaining unchanged items.
  672. while (originalIndex < slotCount)
  673. unchanged[unchangedIndex++] = originalIndex++;
  674. // Fill in unchanged items.
  675. for (int i = slotCount - 1; i >= 0; i--)
  676. if (drawOrder[i] == -1) drawOrder[i] = unchanged[--unchangedIndex];
  677. }
  678. timeline.SetFrame(frameIndex++, (float)drawOrderMap["time"], drawOrder);
  679. }
  680. timelines.Add(timeline);
  681. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  682. }
  683. // Event timeline.
  684. if (map.ContainsKey("events")) {
  685. var eventsMap = (List<Object>)map["events"];
  686. var timeline = new EventTimeline(eventsMap.Count);
  687. int frameIndex = 0;
  688. foreach (Dictionary<string, Object> eventMap in eventsMap) {
  689. EventData eventData = skeletonData.FindEvent((string)eventMap["name"]);
  690. if (eventData == null) throw new Exception("Event not found: " + eventMap["name"]);
  691. var e = new Event((float)eventMap["time"], eventData);
  692. e.Int = GetInt(eventMap, "int", eventData.Int);
  693. e.Float = GetFloat(eventMap, "float", eventData.Float);
  694. e.String = GetString(eventMap, "string", eventData.String);
  695. timeline.SetFrame(frameIndex++, e);
  696. }
  697. timelines.Add(timeline);
  698. duration = Math.Max(duration, timeline.frames[timeline.FrameCount - 1]);
  699. }
  700. timelines.TrimExcess();
  701. skeletonData.animations.Add(new Animation(name, timelines, duration));
  702. }
  703. static void ReadCurve (Dictionary<string, Object> valueMap, CurveTimeline timeline, int frameIndex) {
  704. if (!valueMap.ContainsKey("curve"))
  705. return;
  706. Object curveObject = valueMap["curve"];
  707. if (curveObject.Equals("stepped"))
  708. timeline.SetStepped(frameIndex);
  709. else {
  710. var curve = curveObject as List<Object>;
  711. if (curve != null)
  712. timeline.SetCurve(frameIndex, (float)curve[0], (float)curve[1], (float)curve[2], (float)curve[3]);
  713. }
  714. }
  715. internal class LinkedMesh {
  716. internal string parent, skin;
  717. internal int slotIndex;
  718. internal MeshAttachment mesh;
  719. public LinkedMesh (MeshAttachment mesh, string skin, int slotIndex, string parent) {
  720. this.mesh = mesh;
  721. this.skin = skin;
  722. this.slotIndex = slotIndex;
  723. this.parent = parent;
  724. }
  725. }
  726. static float[] GetFloatArray(Dictionary<string, Object> map, string name, float scale) {
  727. var list = (List<Object>)map[name];
  728. var values = new float[list.Count];
  729. if (scale == 1) {
  730. for (int i = 0, n = list.Count; i < n; i++)
  731. values[i] = (float)list[i];
  732. } else {
  733. for (int i = 0, n = list.Count; i < n; i++)
  734. values[i] = (float)list[i] * scale;
  735. }
  736. return values;
  737. }
  738. static int[] GetIntArray(Dictionary<string, Object> map, string name) {
  739. var list = (List<Object>)map[name];
  740. var values = new int[list.Count];
  741. for (int i = 0, n = list.Count; i < n; i++)
  742. values[i] = (int)(float)list[i];
  743. return values;
  744. }
  745. static float GetFloat(Dictionary<string, Object> map, string name, float defaultValue) {
  746. if (!map.ContainsKey(name))
  747. return defaultValue;
  748. return (float)map[name];
  749. }
  750. static int GetInt(Dictionary<string, Object> map, string name, int defaultValue) {
  751. if (!map.ContainsKey(name))
  752. return defaultValue;
  753. return (int)(float)map[name];
  754. }
  755. static bool GetBoolean(Dictionary<string, Object> map, string name, bool defaultValue) {
  756. if (!map.ContainsKey(name))
  757. return defaultValue;
  758. return (bool)map[name];
  759. }
  760. static string GetString(Dictionary<string, Object> map, string name, string defaultValue) {
  761. if (!map.ContainsKey(name))
  762. return defaultValue;
  763. return (string)map[name];
  764. }
  765. static float ToColor(string hexString, int colorIndex, int expectedLength = 8) {
  766. if (hexString.Length != expectedLength)
  767. throw new ArgumentException("Color hexidecimal length must be " + expectedLength + ", recieved: " + hexString, "hexString");
  768. return Convert.ToInt32(hexString.Substring(colorIndex * 2, 2), 16) / (float)255;
  769. }
  770. }
  771. }