Beispiel #1
0
    static int SetSkin(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2 && TypeChecker.CheckTypes <Spine.Skin>(L, 2))
            {
                Spine.Skeleton obj  = (Spine.Skeleton)ToLua.CheckObject <Spine.Skeleton>(L, 1);
                Spine.Skin     arg0 = (Spine.Skin)ToLua.ToObject(L, 2);
                obj.SetSkin(arg0);
                return(0);
            }
            else if (count == 2 && TypeChecker.CheckTypes <string>(L, 2))
            {
                Spine.Skeleton obj  = (Spine.Skeleton)ToLua.CheckObject <Spine.Skeleton>(L, 1);
                string         arg0 = ToLua.ToString(L, 2);
                obj.SetSkin(arg0);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: Spine.Skeleton.SetSkin"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Beispiel #2
0
    //
    #region AnimImgChangeVision
    private void Start()
    {
        functionSkin = new Skin("function");
        var templateskin = skeletonAnimation.Skeleton.Data.FindSkin(templateSkinName);

        if (templateskin != null)
        {
            functionSkin.AddAttachments(templateskin);
        }
        skeletonAnimation.Skeleton.Skin = functionSkin;
        RefreshSkeletionAttachments();
    }
 public Attachment NewAttachment(Skin skin, AttachmentType type, String name)
 {
     switch (type) {
     case AttachmentType.region:
         AtlasRegion region = atlas.FindRegion(name);
         if (region == null) throw new Exception("Region not found in atlas: " + name + " (" + type + ")");
         RegionAttachment attachment = new RegionAttachment(name);
         attachment.Region = region;
         return attachment;
     }
     throw new Exception("Unknown attachment type: " + type);
 }
		public RegionAttachment NewRegionAttachment (Skin skin, String name, String path) {
			AtlasRegion region = atlas.FindRegion(path);
			if (region == null) throw new Exception("Region not found in atlas: " + path + " (region attachment: " + name + ")");
			RegionAttachment attachment = new RegionAttachment(name);
			attachment.RendererObject = region;
			attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate);
			attachment.regionOffsetX = region.offsetX;
			attachment.regionOffsetY = region.offsetY;
			attachment.regionWidth = region.width;
			attachment.regionHeight = region.height;
			attachment.regionOriginalWidth = region.originalWidth;
			attachment.regionOriginalHeight = region.originalHeight;
			return attachment;
		}
 static int ToString(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         Spine.Skin obj = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 1);
         string     o   = obj.ToString();
         LuaDLL.lua_pushstring(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int Add(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
         Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
         obj.Add(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int Pop(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
         Spine.Skin o = obj.Pop();
         ToLua.PushObject(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Beispiel #8
0
		void Start () {
			skeletonRenderer = GetComponent<SkeletonRenderer>();
			Skeleton skeleton = skeletonRenderer.skeleton;

			customSkin = new Skin("CustomSkin");

			foreach (var pair in skinItems) {
				var attachment = SpineAttachment.GetAttachment(pair.sourceAttachmentPath, skinSource);
				customSkin.AddAttachment(skeleton.FindSlotIndex(pair.targetSlot), pair.targetAttachment, attachment);
			}

			// The custom skin does not need to be added to the skeleton data for it to work.
			// But it's useful for your script to keep a reference to it.
			skeleton.SetSkin(customSkin);
		}
        void Start()
        {
            equipsSkin = new Skin("Equips");

            // OPTIONAL: Add all the attachments from the template skin.
            var templateSkin = skeletonAnimation.Skeleton.Data.FindSkin(templateSkinName);

            if (templateSkin != null)
            {
                equipsSkin.Append(templateSkin);
            }

            skeletonAnimation.Skeleton.Skin = equipsSkin;
            RefreshSkeletonAttachments();
        }
 static int Remove(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
         Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
         bool       o    = obj.Remove(arg0);
         LuaDLL.lua_pushboolean(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Beispiel #11
0
 static int FindSkin(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         Spine.SkeletonData obj  = (Spine.SkeletonData)ToLua.CheckObject <Spine.SkeletonData>(L, 1);
         string             arg0 = ToLua.CheckString(L, 2);
         Spine.Skin         o    = obj.FindSkin(arg0);
         ToLua.PushObject(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int Insert(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
         int        arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
         Spine.Skin arg1 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 3);
         obj.Insert(arg0, arg1);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int FindLast(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         Spine.ExposedList <Spine.Skin> obj  = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
         System.Predicate <Spine.Skin>  arg0 = (System.Predicate <Spine.Skin>)ToLua.CheckDelegate <System.Predicate <Spine.Skin> >(L, 2);
         Spine.Skin o = obj.FindLast(arg0);
         ToLua.PushObject(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int FindNamesForSlot(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         Spine.Skin obj  = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 1);
         int        arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
         System.Collections.Generic.List <string> arg1 = (System.Collections.Generic.List <string>)ToLua.CheckObject(L, 3, typeof(System.Collections.Generic.List <string>));
         obj.FindNamesForSlot(arg0, arg1);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int AddAttachment(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 4);
         Spine.Skin       obj  = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 1);
         int              arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
         string           arg1 = ToLua.CheckString(L, 3);
         Spine.Attachment arg2 = (Spine.Attachment)ToLua.CheckObject <Spine.Attachment>(L, 4);
         obj.AddAttachment(arg0, arg1, arg2);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static int GetAttachment(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         Spine.Skin       obj  = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 1);
         int              arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
         string           arg1 = ToLua.CheckString(L, 3);
         Spine.Attachment o    = obj.GetAttachment(arg0, arg1);
         ToLua.PushObject(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Beispiel #17
0
    public void OptimizeSkin()
    {
        // 1. Collect all the attachments of all active skins.
        collectedSkin = collectedSkin ?? new Skin("Collected skin");
        collectedSkin.Clear();
        collectedSkin.AddAttachments(skeletonAnimation.Skeleton.Data.DefaultSkin);
        collectedSkin.AddAttachments(functionSkin);

        // 2. Create a repacked skin.
        var repackedSkin = collectedSkin.GetRepackedSkin("Repacked skin", skeletonAnimation.SkeletonDataAsset.atlasAssets[0].PrimaryMaterial, out runtimeMaterial, out runtimeAtlas);

        collectedSkin.Clear();

        // 3. Use the repacked skin.
        skeletonAnimation.Skeleton.Skin = repackedSkin;
        RefreshSkeletionAttachments();
    }
    static int get_Attachments(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            Spine.Skin obj = (Spine.Skin)o;
            System.Collections.Generic.Dictionary <Spine.Skin.AttachmentKeyTuple, Spine.Attachment> ret = obj.Attachments;
            ToLua.PushSealed(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index Attachments on a nil value"));
        }
    }
    static int get_Name(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            Spine.Skin obj = (Spine.Skin)o;
            string     ret = obj.Name;
            LuaDLL.lua_pushstring(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index Name on a nil value"));
        }
    }
Beispiel #20
0
    static int set_Skin(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            Spine.Skeleton obj  = (Spine.Skeleton)o;
            Spine.Skin     arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
            obj.Skin = arg0;
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index Skin on a nil value"));
        }
    }
Beispiel #21
0
    static int get_Skin(IntPtr L)
    {
        object o = null;

        try
        {
            o = ToLua.ToObject(L, 1);
            Spine.Skeleton obj = (Spine.Skeleton)o;
            Spine.Skin     ret = obj.Skin;
            ToLua.PushObject(L, ret);
            return(1);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e, o, "attempt to index Skin on a nil value"));
        }
    }
Beispiel #22
0
    private void SetSkin(int index)
    {
        var numOfSkin = charSke.SkeletonDataAsset.GetSkeletonData(false).Skins;

        if (index >= numOfSkin.Count)
        {
            return;
        }
        // charSke.Skeleton.SetSkin($"{charPrefix}{index + 1}");

        var ske     = charSke.Skeleton;
        var newSkin = new Spine.Skin("new_skin");

        newSkin.AddSkin(ske.Data.FindSkin($"{charPrefix}{index + 1}"));
        ske.SetSkin(newSkin);
        ske.SetToSetupPose();
    }
		public SkinnedMeshAttachment NewSkinnedMeshAttachment (Skin skin, String name, String path) {
			AtlasRegion region = atlas.FindRegion(path);
			if (region == null) throw new Exception("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")");
			SkinnedMeshAttachment attachment = new SkinnedMeshAttachment(name);
			attachment.RendererObject = region;
			attachment.RegionU = region.u;
			attachment.RegionV = region.v;
			attachment.RegionU2 = region.u2;
			attachment.RegionV2 = region.v2;
			attachment.RegionRotate = region.rotate;
			attachment.regionOffsetX = region.offsetX;
			attachment.regionOffsetY = region.offsetY;
			attachment.regionWidth = region.width;
			attachment.regionHeight = region.height;
			attachment.regionOriginalWidth = region.originalWidth;
			attachment.regionOriginalHeight = region.originalHeight;
			return attachment;
		}
    static int BinarySearch(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2)
            {
                Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
                Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
                int        o    = obj.BinarySearch(arg0);
                LuaDLL.lua_pushinteger(L, o);
                return(1);
            }
            else if (count == 3)
            {
                Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
                Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
                System.Collections.Generic.IComparer <Spine.Skin> arg1 = (System.Collections.Generic.IComparer <Spine.Skin>)ToLua.CheckObject <System.Collections.Generic.IComparer <Spine.Skin> >(L, 3);
                int o = obj.BinarySearch(arg0, arg1);
                LuaDLL.lua_pushinteger(L, o);
                return(1);
            }
            else if (count == 5)
            {
                Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
                int        arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
                int        arg1 = (int)LuaDLL.luaL_checknumber(L, 3);
                Spine.Skin arg2 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 4);
                System.Collections.Generic.IComparer <Spine.Skin> arg3 = (System.Collections.Generic.IComparer <Spine.Skin>)ToLua.CheckObject <System.Collections.Generic.IComparer <Spine.Skin> >(L, 5);
                int o = obj.BinarySearch(arg0, arg1, arg2, arg3);
                LuaDLL.lua_pushinteger(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: Spine.ExposedList<Spine.Skin>.BinarySearch"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
        public void OptimizeSkin()
        {
            // 1. Collect all the attachments of all active skins.
            collectedSkin = collectedSkin ?? new Skin("Collected skin");
            collectedSkin.Clear();
            collectedSkin.Append(skeletonAnimation.Skeleton.Data.DefaultSkin);
            collectedSkin.Append(equipsSkin);

            // 2. Create a repacked skin.
            var repackedSkin = collectedSkin.GetRepackedSkin("Repacked skin", skeletonAnimation.SkeletonDataAsset.atlasAssets[0].materials[0], out runtimeMaterial, out runtimeAtlas);

            collectedSkin.Clear();

            // 3. Use the repacked skin.
            skeletonAnimation.Skeleton.Skin = repackedSkin;
            RefreshSkeletonAttachments();

            skeletonAnimation.OverrideTexture = runtimeAtlas;
        }
 public Attachment NewAttachment(Skin skin, AttachmentType type, String name)
 {
     switch (type) {
     case AttachmentType.region:
         AtlasRegion region = atlas.FindRegion(name);
         if (region == null) throw new Exception("Region not found in atlas: " + name + " (" + type + ")");
         RegionAttachment attachment = new RegionAttachment(name);
         attachment.RendererObject = region.page.rendererObject;
         attachment.SetUVs(region.u, region.v, region.u2, region.v2, region.rotate);
         attachment.RegionOffsetX = region.offsetX;
         attachment.RegionOffsetY = region.offsetY;
         attachment.RegionWidth = region.width;
         attachment.RegionHeight = region.height;
         attachment.RegionOriginalWidth = region.originalWidth;
         attachment.RegionOriginalHeight = region.originalHeight;
         return attachment;
     }
     throw new Exception("Unknown attachment type: " + type);
 }
    static int LastIndexOf(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 2)
            {
                Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
                Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
                int        o    = obj.LastIndexOf(arg0);
                LuaDLL.lua_pushinteger(L, o);
                return(1);
            }
            else if (count == 3)
            {
                Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
                Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
                int        arg1 = (int)LuaDLL.luaL_checknumber(L, 3);
                int        o    = obj.LastIndexOf(arg0, arg1);
                LuaDLL.lua_pushinteger(L, o);
                return(1);
            }
            else if (count == 4)
            {
                Spine.ExposedList <Spine.Skin> obj = (Spine.ExposedList <Spine.Skin>)ToLua.CheckObject <Spine.ExposedList <Spine.Skin> >(L, 1);
                Spine.Skin arg0 = (Spine.Skin)ToLua.CheckObject <Spine.Skin>(L, 2);
                int        arg1 = (int)LuaDLL.luaL_checknumber(L, 3);
                int        arg2 = (int)LuaDLL.luaL_checknumber(L, 4);
                int        o    = obj.LastIndexOf(arg0, arg1, arg2);
                LuaDLL.lua_pushinteger(L, o);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: Spine.ExposedList<Spine.Skin>.LastIndexOf"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
    static int _CreateSpine_Skin(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1)
            {
                string     arg0 = ToLua.CheckString(L, 1);
                Spine.Skin obj  = new Spine.Skin(arg0);
                ToLua.PushObject(L, obj);
                return(1);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: Spine.Skin.New"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
		public SkeletonData ReadSkeletonData (TextReader reader) {
			if (reader == null) throw new ArgumentNullException("reader cannot be null.");

			var skeletonData = new SkeletonData();

			var root = Json.Deserialize(reader) as Dictionary<String, Object>;
			if (root == null) throw new Exception("Invalid JSON.");

			// Skeleton.
			if (root.ContainsKey("skeleton")) {
				var skeletonMap = (Dictionary<String, Object>)root["skeleton"];
				skeletonData.hash = (String)skeletonMap["hash"];
				skeletonData.version = (String)skeletonMap["spine"];
				skeletonData.width = GetFloat(skeletonMap, "width", 0);
				skeletonData.height = GetFloat(skeletonMap, "height", 0);
			}

			// Bones.
			foreach (Dictionary<String, Object> boneMap in (List<Object>)root["bones"]) {
				BoneData parent = null;
				if (boneMap.ContainsKey("parent")) {
					parent = skeletonData.FindBone((String)boneMap["parent"]);
					if (parent == null)
						throw new Exception("Parent bone not found: " + boneMap["parent"]);
				}
				var boneData = new BoneData((String)boneMap["name"], parent);
				boneData.length = GetFloat(boneMap, "length", 0) * Scale;
				boneData.x = GetFloat(boneMap, "x", 0) * Scale;
				boneData.y = GetFloat(boneMap, "y", 0) * Scale;
				boneData.rotation = GetFloat(boneMap, "rotation", 0);
				boneData.scaleX = GetFloat(boneMap, "scaleX", 1);
				boneData.scaleY = GetFloat(boneMap, "scaleY", 1);
				boneData.inheritScale = GetBoolean(boneMap, "inheritScale", true);
				boneData.inheritRotation = GetBoolean(boneMap, "inheritRotation", true);
				skeletonData.bones.Add(boneData);
			}

			// IK constraints.
			if (root.ContainsKey("ik")) {
				foreach (Dictionary<String, Object> ikMap in (List<Object>)root["ik"]) {
					IkConstraintData ikConstraintData = new IkConstraintData((String)ikMap["name"]);

					foreach (String boneName in (List<Object>)ikMap["bones"]) {
						BoneData bone = skeletonData.FindBone(boneName);
						if (bone == null) throw new Exception("IK bone not found: " + boneName);
						ikConstraintData.bones.Add(bone);
					}

					String targetName = (String)ikMap["target"];
					ikConstraintData.target = skeletonData.FindBone(targetName);
					if (ikConstraintData.target == null) throw new Exception("Target bone not found: " + targetName);

					ikConstraintData.bendDirection = GetBoolean(ikMap, "bendPositive", true) ? 1 : -1;
					ikConstraintData.mix = GetFloat(ikMap, "mix", 1);

					skeletonData.ikConstraints.Add(ikConstraintData);
				}
			}

			// Transform constraints.
			if (root.ContainsKey("transform")) {
				foreach (Dictionary<String, Object> transformMap in (List<Object>)root["ik"]) {
					TransformConstraintData transformConstraintData = new TransformConstraintData((String)transformMap["name"]);

					String boneName = (String)transformMap["bone"];
					transformConstraintData.target = skeletonData.FindBone(boneName);
					if (transformConstraintData.target == null) throw new Exception("Bone not found: " + boneName);

					String targetName = (String)transformMap["target"];
					transformConstraintData.target = skeletonData.FindBone(targetName);
					if (transformConstraintData.target == null) throw new Exception("Target bone not found: " + targetName);

					transformConstraintData.translateMix = GetFloat(transformMap, "mix", 1);
					transformConstraintData.x = GetFloat(transformMap, "x", 0);
					transformConstraintData.y = GetFloat(transformMap, "y", 0);

					skeletonData.transformConstraints.Add(transformConstraintData);
				}
			}

			// Slots.
			if (root.ContainsKey("slots")) {
				foreach (Dictionary<String, Object> slotMap in (List<Object>)root["slots"]) {
					var slotName = (String)slotMap["name"];
					var boneName = (String)slotMap["bone"];
					BoneData boneData = skeletonData.FindBone(boneName);
					if (boneData == null)
						throw new Exception("Slot bone not found: " + boneName);
					var slotData = new SlotData(slotName, boneData);

					if (slotMap.ContainsKey("color")) {
						var color = (String)slotMap["color"];
						slotData.r = ToColor(color, 0);
						slotData.g = ToColor(color, 1);
						slotData.b = ToColor(color, 2);
						slotData.a = ToColor(color, 3);
					}

					if (slotMap.ContainsKey("attachment"))
						slotData.attachmentName = (String)slotMap["attachment"];

					if (slotMap.ContainsKey("blend"))
						slotData.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (String)slotMap["blend"], false);
					else
						slotData.blendMode = BlendMode.normal;

					skeletonData.slots.Add(slotData);
				}
			}

			// Skins.
			if (root.ContainsKey("skins")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["skins"]) {
					var skin = new Skin(entry.Key);
					foreach (KeyValuePair<String, Object> slotEntry in (Dictionary<String, Object>)entry.Value) {
						int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
						foreach (KeyValuePair<String, Object> attachmentEntry in ((Dictionary<String, Object>)slotEntry.Value)) {
							Attachment attachment = ReadAttachment(skin, attachmentEntry.Key, (Dictionary<String, Object>)attachmentEntry.Value);
							if (attachment != null) skin.AddAttachment(slotIndex, attachmentEntry.Key, attachment);
						}
					}
					skeletonData.skins.Add(skin);
					if (skin.name == "default")
						skeletonData.defaultSkin = skin;
				}
			}

			// Events.
			if (root.ContainsKey("events")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["events"]) {
					var entryMap = (Dictionary<String, Object>)entry.Value;
					var eventData = new EventData(entry.Key);
					eventData.Int = GetInt(entryMap, "int", 0);
					eventData.Float = GetFloat(entryMap, "float", 0);
					eventData.String = GetString(entryMap, "string", null);
					skeletonData.events.Add(eventData);
				}
			}

			// Animations.
			if (root.ContainsKey("animations")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["animations"])
					ReadAnimation(entry.Key, (Dictionary<String, Object>)entry.Value, skeletonData);
			}

			skeletonData.bones.TrimExcess();
			skeletonData.slots.TrimExcess();
			skeletonData.skins.TrimExcess();
			skeletonData.events.TrimExcess();
			skeletonData.animations.TrimExcess();
			skeletonData.ikConstraints.TrimExcess();
			return skeletonData;
		}
Beispiel #30
0
        public SkeletonData ReadSkeletonData(TextReader reader)
        {
            if (reader == null) throw new ArgumentNullException("reader cannot be null.");

            SkeletonData skeletonData = new SkeletonData();

            var root = Json.Deserialize(reader) as Dictionary<String, Object>;
            if (root == null) throw new Exception("Invalid JSON.");

            // Bones.
            foreach (Dictionary<String, Object> boneMap in (List<Object>)root["bones"]) {
                BoneData parent = null;
                if (boneMap.ContainsKey("parent")) {
                    parent = skeletonData.FindBone((String)boneMap["parent"]);
                    if (parent == null)
                        throw new Exception("Parent bone not found: " + boneMap["parent"]);
                }
                BoneData boneData = new BoneData((String)boneMap["name"], parent);
                boneData.Length = getFloat(boneMap, "length", 0) * Scale;
                boneData.X = getFloat(boneMap, "x", 0) * Scale;
                boneData.Y = getFloat(boneMap, "y", 0) * Scale;
                boneData.Rotation = getFloat(boneMap, "rotation", 0);
                boneData.ScaleX = getFloat(boneMap, "scaleX", 1);
                boneData.ScaleY = getFloat(boneMap, "scaleY", 1);
                skeletonData.AddBone(boneData);
            }

            // Slots.
            if (root.ContainsKey("slots")) {
                var slots = (List<Object>)root["slots"];
                foreach (Dictionary<String, Object> slotMap in (List<Object>)slots) {
                    String slotName = (String)slotMap["name"];
                    String boneName = (String)slotMap["bone"];
                    BoneData boneData = skeletonData.FindBone(boneName);
                    if (boneData == null)
                        throw new Exception("Slot bone not found: " + boneName);
                    SlotData slotData = new SlotData(slotName, boneData);

                    if (slotMap.ContainsKey("color")) {
                        String color = (String)slotMap["color"];
                        slotData.R = toColor(color, 0);
                        slotData.G = toColor(color, 1);
                        slotData.B = toColor(color, 2);
                        slotData.A = toColor(color, 3);
                    }

                    if (slotMap.ContainsKey("attachment"))
                        slotData.AttachmentName = (String)slotMap["attachment"];

                    skeletonData.AddSlot(slotData);
                }
            }

            // Skins.
            if (root.ContainsKey("skins")) {
                Dictionary<String, Object> skinMap = (Dictionary<String, Object>)root["skins"];
                foreach (KeyValuePair<String, Object> entry in skinMap) {
                    Skin skin = new Skin(entry.Key);
                    foreach (KeyValuePair<String, Object> slotEntry in (Dictionary<String, Object>)entry.Value) {
                        int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
                        foreach (KeyValuePair<String, Object> attachmentEntry in ((Dictionary<String, Object>)slotEntry.Value)) {
                            Attachment attachment = readAttachment(skin, attachmentEntry.Key, (Dictionary<String, Object>)attachmentEntry.Value);
                            skin.AddAttachment(slotIndex, attachmentEntry.Key, attachment);
                        }
                    }
                    skeletonData.AddSkin(skin);
                    if (skin.Name == "default")
                        skeletonData.DefaultSkin = skin;
                }
            }

            // Animations.
            if (root.ContainsKey("animations")) {
                Dictionary<String, Object> animationMap = (Dictionary<String, Object>)root["animations"];
                foreach (KeyValuePair<String, Object> entry in animationMap)
                    readAnimation(entry.Key, (Dictionary<String, Object>)entry.Value, skeletonData);
            }

            skeletonData.Bones.TrimExcess();
            skeletonData.Slots.TrimExcess();
            skeletonData.Skins.TrimExcess();
            skeletonData.Animations.TrimExcess();
            return skeletonData;
        }
		public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, String name) {
			return new BoundingBoxAttachment(name);
		}
 public PathAttachment NewPathAttachment(Skin skin, String name)
 {
     return(new PathAttachment(name));
 }
		public BoundingBoxAttachment NewBoundingBoxAttachment (Skin skin, string name) {			
			return null;
		}
		/** @return May be null. */
		private Skin ReadSkin (Stream input, String skinName, bool nonessential) {
			int slotCount = ReadInt(input, true);
			if (slotCount == 0) return null;
			Skin skin = new Skin(skinName);
			for (int i = 0; i < slotCount; i++) {
				int slotIndex = ReadInt(input, true);
				for (int ii = 0, nn = ReadInt(input, true); ii < nn; ii++) {
					String name = ReadString(input);
					skin.AddAttachment(slotIndex, name, ReadAttachment(input, skin, name, nonessential));
				}
			}
			return skin;
		}
        /// <return>May be null to not load any attachment.</return>
        public MeshAttachment NewMeshAttachment(Skin skin, string name, string path)
        {
            var attachment = new MeshAttachment(name);

            return(attachment);
        }
        /// <return>May be null to not load any attachment.</return>
        public BoundingBoxAttachment NewBoundingBoxAttachment(Skin skin, string name)
        {
            var attachment = new BoundingBoxAttachment(name);

            return(attachment);
        }
        private Attachment ReadAttachment(Stream input, Skin skin, int slotIndex, String attachmentName, bool nonessential)
        {
            float scale = Scale;

            String name = ReadString(input);

            if (name == null)
            {
                name = attachmentName;
            }

            AttachmentType type = (AttachmentType)input.ReadByte();

            switch (type)
            {
            case AttachmentType.Region: {
                String path     = ReadString(input);
                float  rotation = ReadFloat(input);
                float  x        = ReadFloat(input);
                float  y        = ReadFloat(input);
                float  scaleX   = ReadFloat(input);
                float  scaleY   = ReadFloat(input);
                float  width    = ReadFloat(input);
                float  height   = ReadFloat(input);
                int    color    = ReadInt(input);

                if (path == null)
                {
                    path = name;
                }
                RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
                if (region == null)
                {
                    return(null);
                }
                region.Path     = path;
                region.x        = x * scale;
                region.y        = y * scale;
                region.scaleX   = scaleX;
                region.scaleY   = scaleY;
                region.rotation = rotation;
                region.width    = width * scale;
                region.height   = height * scale;
                region.r        = ((color & 0xff000000) >> 24) / 255f;
                region.g        = ((color & 0x00ff0000) >> 16) / 255f;
                region.b        = ((color & 0x0000ff00) >> 8) / 255f;
                region.a        = ((color & 0x000000ff)) / 255f;
                region.UpdateOffset();
                return(region);
            }

            case AttachmentType.Boundingbox: {
                int      vertexCount = ReadVarint(input, true);
                Vertices vertices    = ReadVertices(input, vertexCount);
                if (nonessential)
                {
                    ReadInt(input);                                       //int color = nonessential ? ReadInt(input) : 0; // Avoid unused local warning.
                }
                BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
                if (box == null)
                {
                    return(null);
                }
                box.worldVerticesLength = vertexCount << 1;
                box.vertices            = vertices.vertices;
                box.bones = vertices.bones;
                return(box);
            }

            case AttachmentType.Mesh: {
                String   path = ReadString(input);
                int      color = ReadInt(input);
                int      vertexCount = ReadVarint(input, true);
                float[]  uvs = ReadFloatArray(input, vertexCount << 1, 1);
                int[]    triangles = ReadShortArray(input);
                Vertices vertices = ReadVertices(input, vertexCount);
                int      hullLength = ReadVarint(input, true);
                int[]    edges = null;
                float    width = 0, height = 0;
                if (nonessential)
                {
                    edges  = ReadShortArray(input);
                    width  = ReadFloat(input);
                    height = ReadFloat(input);
                }

                if (path == null)
                {
                    path = name;
                }
                MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
                if (mesh == null)
                {
                    return(null);
                }
                mesh.Path                = path;
                mesh.r                   = ((color & 0xff000000) >> 24) / 255f;
                mesh.g                   = ((color & 0x00ff0000) >> 16) / 255f;
                mesh.b                   = ((color & 0x0000ff00) >> 8) / 255f;
                mesh.a                   = ((color & 0x000000ff)) / 255f;
                mesh.bones               = vertices.bones;
                mesh.vertices            = vertices.vertices;
                mesh.WorldVerticesLength = vertexCount << 1;
                mesh.triangles           = triangles;
                mesh.regionUVs           = uvs;
                mesh.UpdateUVs();
                mesh.HullLength = hullLength << 1;
                if (nonessential)
                {
                    mesh.Edges  = edges;
                    mesh.Width  = width * scale;
                    mesh.Height = height * scale;
                }
                return(mesh);
            }

            case AttachmentType.Linkedmesh: {
                String path = ReadString(input);
                int    color = ReadInt(input);
                String skinName = ReadString(input);
                String parent = ReadString(input);
                bool   inheritDeform = ReadBoolean(input);
                float  width = 0, height = 0;
                if (nonessential)
                {
                    width  = ReadFloat(input);
                    height = ReadFloat(input);
                }

                if (path == null)
                {
                    path = name;
                }
                MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
                if (mesh == null)
                {
                    return(null);
                }
                mesh.Path          = path;
                mesh.r             = ((color & 0xff000000) >> 24) / 255f;
                mesh.g             = ((color & 0x00ff0000) >> 16) / 255f;
                mesh.b             = ((color & 0x0000ff00) >> 8) / 255f;
                mesh.a             = ((color & 0x000000ff)) / 255f;
                mesh.inheritDeform = inheritDeform;
                if (nonessential)
                {
                    mesh.Width  = width * scale;
                    mesh.Height = height * scale;
                }
                linkedMeshes.Add(new SkeletonJson.LinkedMesh(mesh, skinName, slotIndex, parent));
                return(mesh);
            }

            case AttachmentType.Path: {
                bool     closed        = ReadBoolean(input);
                bool     constantSpeed = ReadBoolean(input);
                int      vertexCount   = ReadVarint(input, true);
                Vertices vertices      = ReadVertices(input, vertexCount);
                float[]  lengths       = new float[vertexCount / 3];
                for (int i = 0, n = lengths.Length; i < n; i++)
                {
                    lengths[i] = ReadFloat(input) * scale;
                }
                if (nonessential)
                {
                    ReadInt(input);                                       //int color = nonessential ? ReadInt(input) : 0; // Avoid unused local warning.
                }
                PathAttachment path = attachmentLoader.NewPathAttachment(skin, name);
                if (path == null)
                {
                    return(null);
                }
                path.closed              = closed;
                path.constantSpeed       = constantSpeed;
                path.worldVerticesLength = vertexCount << 1;
                path.vertices            = vertices.vertices;
                path.bones   = vertices.bones;
                path.lengths = lengths;
                return(path);
            }
            }
            return(null);
        }
		public PathAttachment NewPathAttachment (Skin skin, String name) {
			return new PathAttachment (name);
		}
        /// <returns>May be null to not load any attachment</returns>
        public PathAttachment NewPathAttachment(Skin skin, string name)
        {
            var attachment = new PathAttachment(name);

            return(attachment);
        }
		private Attachment ReadAttachment (Skin skin, String name, Dictionary<String, Object> map) {
			if (map.ContainsKey("name"))
				name = (String)map["name"];

			AttachmentType type = AttachmentType.region;
			if (map.ContainsKey("type"))
				type = (AttachmentType)Enum.Parse(typeof(AttachmentType), (String)map["type"], false);
			Attachment attachment = attachmentLoader.NewAttachment(skin, type, name);

			RegionAttachment regionAttachment = attachment as RegionAttachment;
			if (regionAttachment != null) {
				regionAttachment.x = GetFloat(map, "x", 0) * Scale;
				regionAttachment.y = GetFloat(map, "y", 0) * Scale;
				regionAttachment.scaleX = GetFloat(map, "scaleX", 1);
				regionAttachment.scaleY = GetFloat(map, "scaleY", 1);
				regionAttachment.rotation = GetFloat(map, "rotation", 0);
				regionAttachment.width = GetFloat(map, "width", 32) * Scale;
				regionAttachment.height = GetFloat(map, "height", 32) * Scale;
				regionAttachment.UpdateOffset();
			}

			BoundingBoxAttachment boundingBox = attachment as BoundingBoxAttachment;
			if (boundingBox != null) {
				List<Object> values = (List<Object>)map["vertices"];
				float[] vertices = new float[values.Count];
				for (int i = 0, n = values.Count; i < n; i++)
					vertices[i] = (float)values[i];
				boundingBox.Vertices = vertices;
			}

			return attachment;
		}
		public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
			//MITCH : Left todo: Unity 5 only
			return null;
		}
		private Attachment ReadAttachment (Dictionary<String, Object> map, Skin skin, int slotIndex, String name) {
			var scale = this.Scale;
			name = GetString(map, "name", name);

			var typeName = GetString(map, "type", "region");
			if (typeName == "skinnedmesh") typeName = "weightedmesh";
			if (typeName == "weightedmesh") typeName = "mesh";
			if (typeName == "weightedlinkedmesh") typeName = "linkedmesh";
			var type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName, true);

			String path = GetString(map, "path", name);

			switch (type) {
			case AttachmentType.Region:
				RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
				if (region == null) return null;
				region.Path = path;
				region.x = GetFloat(map, "x", 0) * scale;
				region.y = GetFloat(map, "y", 0) * scale;
				region.scaleX = GetFloat(map, "scaleX", 1);
				region.scaleY = GetFloat(map, "scaleY", 1);
				region.rotation = GetFloat(map, "rotation", 0);
				region.width = GetFloat(map, "width", 32) * scale;
				region.height = GetFloat(map, "height", 32) * scale;
				region.UpdateOffset();

				if (map.ContainsKey("color")) {
					var color = (String)map["color"];
					region.r = ToColor(color, 0);
					region.g = ToColor(color, 1);
					region.b = ToColor(color, 2);
					region.a = ToColor(color, 3);
				}

				region.UpdateOffset();
				return region;
			case AttachmentType.Boundingbox:
				BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
				if (box == null) return null;
				ReadVertices(map, box, GetInt(map, "vertexCount", 0) << 1);
				return box;
			case AttachmentType.Mesh:
			case AttachmentType.Linkedmesh: {
					MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
					if (mesh == null) return null;
					mesh.Path = path;

					if (map.ContainsKey("color")) {
						var color = (String)map["color"];
						mesh.r = ToColor(color, 0);
						mesh.g = ToColor(color, 1);
						mesh.b = ToColor(color, 2);
						mesh.a = ToColor(color, 3);
					}

					mesh.Width = GetFloat(map, "width", 0) * scale;
					mesh.Height = GetFloat(map, "height", 0) * scale;

					String parent = GetString(map, "parent", null);
					if (parent != null) {
						mesh.InheritDeform = GetBoolean(map, "deform", true);
						linkedMeshes.Add(new LinkedMesh(mesh, GetString(map, "skin", null), slotIndex, parent));
						return mesh;
					}

					float[] uvs = GetFloatArray(map, "uvs", 1);
					ReadVertices(map, mesh, uvs.Length);
					mesh.triangles = GetIntArray(map, "triangles");
					mesh.regionUVs = uvs;
					mesh.UpdateUVs();

					if (map.ContainsKey("hull")) mesh.HullLength = GetInt(map, "hull", 0) * 2;
					if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges");
					return mesh;
				}
			case AttachmentType.Path: {
					PathAttachment pathAttachment = attachmentLoader.NewPathAttachment(skin, name);
					if (pathAttachment == null) return null;
					pathAttachment.closed = GetBoolean(map, "closed", false);
					pathAttachment.constantSpeed = GetBoolean(map, "constantSpeed", true);

					int vertexCount = GetInt(map, "vertexCount", 0);
					ReadVertices(map, pathAttachment, vertexCount << 1);

					// potential BOZO see Java impl
					pathAttachment.lengths = GetFloatArray(map, "lengths", scale);
					return pathAttachment;
				}
			}
			return null;
		}
		public PathAttachment NewPathAttachment (Skin skin, string name) {
			return null;
		}
 public BoundingBoxAttachment NewBoundingBoxAttachment(Skin skin, String name)
 {
     return(new BoundingBoxAttachment(name));
 }
		private Attachment ReadAttachment (Stream input, Skin skin, String attachmentName, bool nonessential) {
			float scale = Scale;

			String name = ReadString(input);
			if (name == null) name = attachmentName;

			switch ((AttachmentType)input.ReadByte()) {
			case AttachmentType.region: {
				String path = ReadString(input);
				if (path == null) path = name;
				RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
				if (region == null) return null;
				region.Path = path;
				region.x = ReadFloat(input) * scale;
				region.y = ReadFloat(input) * scale;
				region.scaleX = ReadFloat(input);
				region.scaleY = ReadFloat(input);
				region.rotation = ReadFloat(input);
				region.width = ReadFloat(input) * scale;
				region.height = ReadFloat(input) * scale;
				int color = ReadInt(input);
				region.r = ((color & 0xff000000) >> 24) / 255f;
				region.g = ((color & 0x00ff0000) >> 16) / 255f;
				region.b = ((color & 0x0000ff00) >> 8) / 255f;
				region.a = ((color & 0x000000ff)) / 255f;
				region.UpdateOffset();
				return region;
			}
			case AttachmentType.boundingbox: {
				BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
				if (box == null) return null;
				box.vertices = ReadFloatArray(input, scale);
				return box;
			}
			case AttachmentType.mesh: {
				String path = ReadString(input);
				if (path == null) path = name;
				MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
				if (mesh == null) return null;
				mesh.Path = path;
				mesh.regionUVs = ReadFloatArray(input, 1);
				mesh.triangles = ReadShortArray(input);
				mesh.vertices = ReadFloatArray(input, scale);
				mesh.UpdateUVs();
				int color = ReadInt(input);
				mesh.r = ((color & 0xff000000) >> 24) / 255f;
				mesh.g = ((color & 0x00ff0000) >> 16) / 255f;
				mesh.b = ((color & 0x0000ff00) >> 8) / 255f;
				mesh.a = ((color & 0x000000ff)) / 255f;
				mesh.HullLength = ReadInt(input, true) * 2;
				if (nonessential) {
					mesh.Edges = ReadIntArray(input);
					mesh.Width = ReadFloat(input) * scale;
					mesh.Height = ReadFloat(input) * scale;
				}
				return mesh;
			}
			case AttachmentType.skinnedmesh: {
				String path = ReadString(input);
				if (path == null) path = name;
				SkinnedMeshAttachment mesh = attachmentLoader.NewSkinnedMeshAttachment(skin, name, path);
				if (mesh == null) return null;
				mesh.Path = path;
				float[] uvs = ReadFloatArray(input, 1);
				int[] triangles = ReadShortArray(input);

				int vertexCount = ReadInt(input, true);
				var weights = new List<float>(uvs.Length * 3 * 3);
				var bones = new List<int>(uvs.Length * 3);
				for (int i = 0; i < vertexCount; i++) {
					int boneCount = (int)ReadFloat(input);
					bones.Add(boneCount);
					for (int nn = i + boneCount * 4; i < nn; i += 4) {
						bones.Add((int)ReadFloat(input));
						weights.Add(ReadFloat(input) * scale);
						weights.Add(ReadFloat(input) * scale);
						weights.Add(ReadFloat(input));
					}
				}
				mesh.bones = bones.ToArray();
				mesh.weights = weights.ToArray();
				mesh.triangles = triangles;
				mesh.regionUVs = uvs;
				mesh.UpdateUVs();
				int color = ReadInt(input);
				mesh.r = ((color & 0xff000000) >> 24) / 255f;
				mesh.g = ((color & 0x00ff0000) >> 16) / 255f;
				mesh.b = ((color & 0x0000ff00) >> 8) / 255f;
				mesh.a = ((color & 0x000000ff)) / 255f;
				mesh.HullLength = ReadInt(input, true) * 2;
				if (nonessential) {
					mesh.Edges = ReadIntArray(input);
					mesh.Width = ReadFloat(input) * scale;
					mesh.Height = ReadFloat(input) * scale;
				}
				return mesh;
			}
			}
			return null;
		}
		private Attachment ReadAttachment (Stream input, Skin skin, int slotIndex, String attachmentName, bool nonessential) {
			float scale = Scale;

			String name = ReadString(input);
			if (name == null) name = attachmentName;

			AttachmentType type = (AttachmentType)input.ReadByte();
			switch (type) {
			case AttachmentType.Region: {
					String path = ReadString(input);
					float rotation = ReadFloat(input);		
					float x = ReadFloat(input);
					float y = ReadFloat(input);
					float scaleX = ReadFloat(input);
					float scaleY = ReadFloat(input);
					float width = ReadFloat(input);
					float height = ReadFloat(input);
					int color = ReadInt(input);

					if (path == null) path = name;
					RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
					if (region == null) return null;
					region.Path = path;
					region.x = x * scale;
					region.y = y * scale;
					region.scaleX = scaleX;
					region.scaleY = scaleY;
					region.rotation = rotation;
					region.width = width * scale;
					region.height = height * scale;
					region.r = ((color & 0xff000000) >> 24) / 255f;
					region.g = ((color & 0x00ff0000) >> 16) / 255f;
					region.b = ((color & 0x0000ff00) >> 8) / 255f;
					region.a = ((color & 0x000000ff)) / 255f;
					region.UpdateOffset();
					return region;
				}
			case AttachmentType.Boundingbox: {
					int vertexCount = ReadVarint(input, true);
					Vertices vertices = ReadVertices(input, vertexCount);
					if (nonessential) ReadInt(input); //int color = nonessential ? ReadInt(input) : 0; // Avoid unused local warning.
					
					BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
					if (box == null) return null;
					box.worldVerticesLength = vertexCount << 1;
					box.vertices = vertices.vertices;
					box.bones = vertices.bones;                    
					return box;
				}
			case AttachmentType.Mesh: {
					String path = ReadString(input);
					int color = ReadInt(input);
					int vertexCount = ReadVarint(input, true);					
					float[] uvs = ReadFloatArray(input, vertexCount << 1, 1);
					int[] triangles = ReadShortArray(input);
					Vertices vertices = ReadVertices(input, vertexCount);
					int hullLength = ReadVarint(input, true);
					int[] edges = null;
					float width = 0, height = 0;
					if (nonessential) {
						edges = ReadShortArray(input);
						width = ReadFloat(input);
						height = ReadFloat(input);
					}

					if (path == null) path = name;
					MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
					if (mesh == null) return null;
					mesh.Path = path;
					mesh.r = ((color & 0xff000000) >> 24) / 255f;
					mesh.g = ((color & 0x00ff0000) >> 16) / 255f;
					mesh.b = ((color & 0x0000ff00) >> 8) / 255f;
					mesh.a = ((color & 0x000000ff)) / 255f;
					mesh.bones = vertices.bones;
					mesh.vertices = vertices.vertices;
					mesh.WorldVerticesLength = vertexCount << 1;
					mesh.triangles = triangles;
					mesh.regionUVs = uvs;
					mesh.UpdateUVs();
					mesh.HullLength = hullLength << 1;
					if (nonessential) {
						mesh.Edges = edges;
						mesh.Width = width * scale;
						mesh.Height = height * scale;
					}
					return mesh;
				}
			case AttachmentType.Linkedmesh: {
					String path = ReadString(input);
					int color = ReadInt(input);
					String skinName = ReadString(input);
					String parent = ReadString(input);
					bool inheritDeform = ReadBoolean(input);
					float width = 0, height = 0;
					if (nonessential) {
						width = ReadFloat(input);
						height = ReadFloat(input);
					}

					if (path == null) path = name;
					MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
					if (mesh == null) return null;
					mesh.Path = path;
					mesh.r = ((color & 0xff000000) >> 24) / 255f;
					mesh.g = ((color & 0x00ff0000) >> 16) / 255f;
					mesh.b = ((color & 0x0000ff00) >> 8) / 255f;
					mesh.a = ((color & 0x000000ff)) / 255f;
					mesh.inheritDeform = inheritDeform;
					if (nonessential) {
						mesh.Width = width * scale;
						mesh.Height = height * scale;
					}
					linkedMeshes.Add(new SkeletonJson.LinkedMesh(mesh, skinName, slotIndex, parent));
					return mesh;
				}
			case AttachmentType.Path: {
					bool closed = ReadBoolean(input);
					bool constantSpeed = ReadBoolean(input);
					int vertexCount = ReadVarint(input, true);
					Vertices vertices = ReadVertices(input, vertexCount);
					float[] lengths = new float[vertexCount / 3];
					for (int i = 0, n = lengths.Length; i < n; i++)
						lengths[i] = ReadFloat(input) * scale;
					if (nonessential) ReadInt(input); //int color = nonessential ? ReadInt(input) : 0; // Avoid unused local warning.

					PathAttachment path = attachmentLoader.NewPathAttachment(skin, name);
					if (path == null) return null;
					path.closed = closed;
					path.constantSpeed = constantSpeed;
					path.worldVerticesLength = vertexCount << 1;
					path.vertices = vertices.vertices;
					path.bones = vertices.bones;
					path.lengths = lengths;
					return path;                    
				}			
			}
			return null;
		}
		public SkeletonData ReadSkeletonData (TextReader reader) {
			if (reader == null) throw new ArgumentNullException("reader cannot be null.");

			SkeletonData skeletonData = new SkeletonData();

			var root = Json.Deserialize(reader) as Dictionary<String, Object>;
			if (root == null) throw new Exception("Invalid JSON.");

			// Bones.
			foreach (Dictionary<String, Object> boneMap in (List<Object>)root["bones"]) {
				BoneData parent = null;
				if (boneMap.ContainsKey("parent")) {
					parent = skeletonData.FindBone((String)boneMap["parent"]);
					if (parent == null)
						throw new Exception("Parent bone not found: " + boneMap["parent"]);
				}
				BoneData boneData = new BoneData((String)boneMap["name"], parent);
				boneData.length = GetFloat(boneMap, "length", 0) * Scale;
				boneData.x = GetFloat(boneMap, "x", 0) * Scale;
				boneData.y = GetFloat(boneMap, "y", 0) * Scale;
				boneData.rotation = GetFloat(boneMap, "rotation", 0);
				boneData.scaleX = GetFloat(boneMap, "scaleX", 1);
				boneData.scaleY = GetFloat(boneMap, "scaleY", 1);
				boneData.inheritScale = GetBoolean(boneMap, "inheritScale", true);
				boneData.inheritRotation = GetBoolean(boneMap, "inheritRotation", true);
				skeletonData.AddBone(boneData);
			}

			// Slots.
			if (root.ContainsKey("slots")) {
				foreach (Dictionary<String, Object> slotMap in (List<Object>)root["slots"]) {
					String slotName = (String)slotMap["name"];
					String boneName = (String)slotMap["bone"];
					BoneData boneData = skeletonData.FindBone(boneName);
					if (boneData == null)
						throw new Exception("Slot bone not found: " + boneName);
					SlotData slotData = new SlotData(slotName, boneData);

					if (slotMap.ContainsKey("color")) {
						String color = (String)slotMap["color"];
						slotData.r = ToColor(color, 0);
						slotData.g = ToColor(color, 1);
						slotData.b = ToColor(color, 2);
						slotData.a = ToColor(color, 3);
					}

					if (slotMap.ContainsKey("attachment"))
						slotData.attachmentName = (String)slotMap["attachment"];

					if (slotMap.ContainsKey("additive"))
						slotData.additiveBlending = (bool)slotMap["additive"];

					skeletonData.AddSlot(slotData);
				}
			}

			// Skins.
			if (root.ContainsKey("skins")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["skins"]) {
					Skin skin = new Skin(entry.Key);
					foreach (KeyValuePair<String, Object> slotEntry in (Dictionary<String, Object>)entry.Value) {
						int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
						foreach (KeyValuePair<String, Object> attachmentEntry in ((Dictionary<String, Object>)slotEntry.Value)) {
							Attachment attachment = ReadAttachment(skin, attachmentEntry.Key, (Dictionary<String, Object>)attachmentEntry.Value);
							if (attachment != null) skin.AddAttachment(slotIndex, attachmentEntry.Key, attachment);
						}
					}
					skeletonData.AddSkin(skin);
					if (skin.name == "default")
						skeletonData.defaultSkin = skin;
				}
			}

			// Events.
			if (root.ContainsKey("events")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["events"]) {
					var entryMap = (Dictionary<String, Object>)entry.Value;
					EventData eventData = new EventData(entry.Key);
					eventData.Int = GetInt(entryMap, "int", 0);
					eventData.Float = GetFloat(entryMap, "float", 0);
					eventData.String = GetString(entryMap, "string", null);
					skeletonData.AddEvent(eventData);
				}
			}

			// Animations.
			if (root.ContainsKey("animations")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["animations"])
					ReadAnimation(entry.Key, (Dictionary<String, Object>)entry.Value, skeletonData);
			}

			skeletonData.bones.TrimExcess();
			skeletonData.slots.TrimExcess();
			skeletonData.skins.TrimExcess();
			skeletonData.animations.TrimExcess();
			return skeletonData;
		}
Beispiel #48
0
 /// <summary>Attach all attachments from this skin if the corresponding attachment from the old skin is currently attached.</summary>
 internal void AttachAll(Skeleton skeleton, Skin oldSkin)
 {
     foreach (KeyValuePair<KeyValuePair<int, String>, Attachment> entry in oldSkin.attachments) {
         int slotIndex = entry.Key.Key;
         Slot slot = skeleton.slots[slotIndex];
         if (slot.attachment == entry.Value) {
             Attachment attachment = GetAttachment(slotIndex, entry.Key.Value);
             if (attachment != null) slot.Attachment = attachment;
         }
     }
 }
		public SkeletonData ReadSkeletonData (TextReader reader) {
			if (reader == null) throw new ArgumentNullException("reader", "reader cannot be null.");

			var scale = this.Scale;
			var skeletonData = new SkeletonData();

			var root = Json.Deserialize(reader) as Dictionary<String, Object>;
			if (root == null) throw new Exception("Invalid JSON.");

			// Skeleton.
			if (root.ContainsKey("skeleton")) {
				var skeletonMap = (Dictionary<String, Object>)root["skeleton"];
				skeletonData.hash = (String)skeletonMap["hash"];
				skeletonData.version = (String)skeletonMap["spine"];
				skeletonData.width = GetFloat(skeletonMap, "width", 0);
				skeletonData.height = GetFloat(skeletonMap, "height", 0);
				skeletonData.fps = GetFloat(skeletonMap, "fps", 0);
				skeletonData.imagesPath = GetString(skeletonMap, "images", null);
			}

			// Bones.
			foreach (Dictionary<String, Object> boneMap in (List<Object>)root["bones"]) {
				BoneData parent = null;
				if (boneMap.ContainsKey("parent")) {
					parent = skeletonData.FindBone((String)boneMap["parent"]);
					if (parent == null)
						throw new Exception("Parent bone not found: " + boneMap["parent"]);
				}
				var data = new BoneData(skeletonData.Bones.Count, (String)boneMap["name"], parent);
				data.length = GetFloat(boneMap, "length", 0) * scale;
				data.x = GetFloat(boneMap, "x", 0) * scale;
				data.y = GetFloat(boneMap, "y", 0) * scale;
				data.rotation = GetFloat(boneMap, "rotation", 0);
				data.scaleX = GetFloat(boneMap, "scaleX", 1);
				data.scaleY = GetFloat(boneMap, "scaleY", 1);
				data.shearX = GetFloat(boneMap, "shearX", 0);
				data.shearY = GetFloat(boneMap, "shearY", 0);

				string tm = GetString(boneMap, "transform", TransformMode.Normal.ToString());
				data.transformMode = (TransformMode)Enum.Parse(typeof(TransformMode), tm, true);

				skeletonData.bones.Add(data);
			}

			// Slots.
			if (root.ContainsKey("slots")) {
				foreach (Dictionary<String, Object> slotMap in (List<Object>)root["slots"]) {
					var slotName = (String)slotMap["name"];
					var boneName = (String)slotMap["bone"];
					BoneData boneData = skeletonData.FindBone(boneName);
					if (boneData == null) throw new Exception("Slot bone not found: " + boneName);
					var data = new SlotData(skeletonData.Slots.Count, slotName, boneData);

					if (slotMap.ContainsKey("color")) {
						var color = (String)slotMap["color"];
						data.r = ToColor(color, 0);
						data.g = ToColor(color, 1);
						data.b = ToColor(color, 2);
						data.a = ToColor(color, 3);
					}
						
					data.attachmentName = GetString(slotMap, "attachment", null);
					if (slotMap.ContainsKey("blend"))
						data.blendMode = (BlendMode)Enum.Parse(typeof(BlendMode), (String)slotMap["blend"], false);
					else
						data.blendMode = BlendMode.normal;
					skeletonData.slots.Add(data);
				}
			}

			// IK constraints.
			if (root.ContainsKey("ik")) {
				foreach (Dictionary<String, Object> constraintMap in (List<Object>)root["ik"]) {
					IkConstraintData data = new IkConstraintData((String)constraintMap["name"]);
					data.order = GetInt(constraintMap, "order", 0);

					foreach (String boneName in (List<Object>)constraintMap["bones"]) {
						BoneData bone = skeletonData.FindBone(boneName);
						if (bone == null) throw new Exception("IK constraint bone not found: " + boneName);
						data.bones.Add(bone);
					}
					
					String targetName = (String)constraintMap["target"];
					data.target = skeletonData.FindBone(targetName);
					if (data.target == null) throw new Exception("Target bone not found: " + targetName);

					data.bendDirection = GetBoolean(constraintMap, "bendPositive", true) ? 1 : -1;
					data.mix = GetFloat(constraintMap, "mix", 1);

					skeletonData.ikConstraints.Add(data);
				}
			}

			// Transform constraints.
			if (root.ContainsKey("transform")) {
				foreach (Dictionary<String, Object> constraintMap in (List<Object>)root["transform"]) {
					TransformConstraintData data = new TransformConstraintData((String)constraintMap["name"]);
					data.order = GetInt(constraintMap, "order", 0);

					foreach (String boneName in (List<Object>)constraintMap["bones"]) {
						BoneData bone = skeletonData.FindBone(boneName);
						if (bone == null) throw new Exception("Transform constraint bone not found: " + boneName);
						data.bones.Add(bone);
					}

					String targetName = (String)constraintMap["target"];
					data.target = skeletonData.FindBone(targetName);
					if (data.target == null) throw new Exception("Target bone not found: " + targetName);

					data.offsetRotation = GetFloat(constraintMap, "rotation", 0);
					data.offsetX = GetFloat(constraintMap, "x", 0) * scale;
					data.offsetY = GetFloat(constraintMap, "y", 0) * scale;
					data.offsetScaleX = GetFloat(constraintMap, "scaleX", 0);
					data.offsetScaleY = GetFloat(constraintMap, "scaleY", 0);
					data.offsetShearY = GetFloat(constraintMap, "shearY", 0);

					data.rotateMix = GetFloat(constraintMap, "rotateMix", 1);
					data.translateMix = GetFloat(constraintMap, "translateMix", 1);
					data.scaleMix = GetFloat(constraintMap, "scaleMix", 1);
					data.shearMix = GetFloat(constraintMap, "shearMix", 1);

					skeletonData.transformConstraints.Add(data);
				}
			}

			// Path constraints.
			if(root.ContainsKey("path")) {
				foreach (Dictionary<String, Object> constraintMap in (List<Object>)root["path"]) {
					PathConstraintData data = new PathConstraintData((String)constraintMap["name"]);
					data.order = GetInt(constraintMap, "order", 0);

					foreach (String boneName in (List<Object>)constraintMap["bones"]) {
						BoneData bone = skeletonData.FindBone(boneName);
						if (bone == null) throw new Exception("Path bone not found: " + boneName);
						data.bones.Add(bone);
					}

					String targetName = (String)constraintMap["target"];
					data.target = skeletonData.FindSlot(targetName);
					if (data.target == null) throw new Exception("Target slot not found: " + targetName);

					data.positionMode = (PositionMode)Enum.Parse(typeof(PositionMode), GetString(constraintMap, "positionMode", "percent"), true);
					data.spacingMode = (SpacingMode)Enum.Parse(typeof(SpacingMode), GetString(constraintMap, "spacingMode", "length"), true);
					data.rotateMode = (RotateMode)Enum.Parse(typeof(RotateMode), GetString(constraintMap, "rotateMode", "tangent"), true);
					data.offsetRotation = GetFloat(constraintMap, "rotation", 0);
					data.position = GetFloat(constraintMap, "position", 0);
					if (data.positionMode == PositionMode.Fixed) data.position *= scale;
					data.spacing = GetFloat(constraintMap, "spacing", 0);
					if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed) data.spacing *= scale;
					data.rotateMix = GetFloat(constraintMap, "rotateMix", 1);
					data.translateMix = GetFloat(constraintMap, "translateMix", 1);

					skeletonData.pathConstraints.Add(data);
				}
			}

			// Skins.
			if (root.ContainsKey("skins")) {
					foreach (KeyValuePair<String, Object> skinMap in (Dictionary<String, Object>)root["skins"]) {
					var skin = new Skin(skinMap.Key);
					foreach (KeyValuePair<String, Object> slotEntry in (Dictionary<String, Object>)skinMap.Value) {
						int slotIndex = skeletonData.FindSlotIndex(slotEntry.Key);
						foreach (KeyValuePair<String, Object> entry in ((Dictionary<String, Object>)slotEntry.Value)) {
							try {
								Attachment attachment = ReadAttachment((Dictionary<String, Object>)entry.Value, skin, slotIndex, entry.Key);
								if (attachment != null) skin.AddAttachment(slotIndex, entry.Key, attachment);
							} catch (Exception e) {
								throw new Exception("Error reading attachment: " + entry.Key + ", skin: " + skin, e);
							}
						} 
					}
					skeletonData.skins.Add(skin);
					if (skin.name == "default") skeletonData.defaultSkin = skin;
				}
			}

			// Linked meshes.
			for (int i = 0, n = linkedMeshes.Count; i < n; i++) {
				LinkedMesh linkedMesh = linkedMeshes[i];
				Skin skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.FindSkin(linkedMesh.skin);
				if (skin == null) throw new Exception("Slot not found: " + linkedMesh.skin);
				Attachment parent = skin.GetAttachment(linkedMesh.slotIndex, linkedMesh.parent);
				if (parent == null) throw new Exception("Parent mesh not found: " + linkedMesh.parent);
				linkedMesh.mesh.ParentMesh = (MeshAttachment)parent;
				linkedMesh.mesh.UpdateUVs();
			}
			linkedMeshes.Clear();

			// Events.
			if (root.ContainsKey("events")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["events"]) {
					var entryMap = (Dictionary<String, Object>)entry.Value;
					var data = new EventData(entry.Key);
					data.Int = GetInt(entryMap, "int", 0);
					data.Float = GetFloat(entryMap, "float", 0);
					data.String = GetString(entryMap, "string", string.Empty);
					skeletonData.events.Add(data);
				}
			}

			// Animations.
			if (root.ContainsKey("animations")) {
				foreach (KeyValuePair<String, Object> entry in (Dictionary<String, Object>)root["animations"]) {
					try {
						ReadAnimation((Dictionary<String, Object>)entry.Value, entry.Key, skeletonData);
					} catch (Exception e) {
						throw new Exception("Error reading animation: " + entry.Key, e);
					}
				}   
			}

			skeletonData.bones.TrimExcess();
			skeletonData.slots.TrimExcess();
			skeletonData.skins.TrimExcess();
			skeletonData.events.TrimExcess();
			skeletonData.animations.TrimExcess();
			skeletonData.ikConstraints.TrimExcess();
			return skeletonData;
		}
		public static SkeletonAnimation InstantiateSkeletonAnimation (SkeletonDataAsset skeletonDataAsset, Skin skin = null, bool destroyInvalid = true) {
			SkeletonData data = skeletonDataAsset.GetSkeletonData(true);

			if (data == null) {
				for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
					string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
					skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
				}
				data = skeletonDataAsset.GetSkeletonData(false);
			}

			if (data == null) {
				Debug.LogWarning("InstantiateSkeletonAnimation tried to instantiate a skeleton from an invalid SkeletonDataAsset.");
				return null;
			}

			if (skin == null) skin = data.DefaultSkin;
			if (skin == null) skin = data.Skins.Items[0];

			string spineGameObjectName = string.Format("Spine GameObject ({0})", skeletonDataAsset.name.Replace("_SkeletonData", ""));
			GameObject go = new GameObject(spineGameObjectName, typeof(MeshFilter), typeof(MeshRenderer), typeof(SkeletonAnimation));
			SkeletonAnimation newSkeletonAnimation = go.GetComponent<SkeletonAnimation>();
			newSkeletonAnimation.skeletonDataAsset = skeletonDataAsset;

			{
				bool requiresNormals = false;
				foreach (AtlasAsset atlasAsset in skeletonDataAsset.atlasAssets) {
					foreach (Material m in atlasAsset.materials) {
						if (m.shader.name.Contains("Lit")) {
							requiresNormals = true;
							break;
						}
					}
				}
				newSkeletonAnimation.calculateNormals = requiresNormals;
			}

			try {
				newSkeletonAnimation.Initialize(false);
			} catch (System.Exception e) {
				if (destroyInvalid) {
					Debug.LogWarning("Editor-instantiated SkeletonAnimation threw an Exception. Destroying GameObject to prevent orphaned GameObject.");
					GameObject.DestroyImmediate(go);
				}
				throw e;
			}

			newSkeletonAnimation.skeleton.SetSkin(skin);
			newSkeletonAnimation.initialSkinName = skin.Name;

			newSkeletonAnimation.skeleton.Update(1);
			newSkeletonAnimation.state.Update(1);
			newSkeletonAnimation.state.Apply(newSkeletonAnimation.skeleton);
			newSkeletonAnimation.skeleton.UpdateWorldTransform();

			return newSkeletonAnimation;
		}
Beispiel #51
0
 /// <summary>Sets the skin used to look up attachments not found in the {@link SkeletonData#getDefaultSkin() default skin}. Attachments
 /// from the new skin are attached if the corresponding attachment from the old skin was attached.</summary>
 /// <param name="newSkin">May be null.</param>
 public void SetSkin(Skin newSkin)
 {
     if (skin != null && newSkin != null) newSkin.AttachAll(this, skin);
     skin = newSkin;
 }
		public static SkeletonAnimator InstantiateSkeletonAnimator (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
			string spineGameObjectName = string.Format("Spine Mecanim GameObject ({0})", skeletonDataAsset.name.Replace("_SkeletonData", ""));
			GameObject go = new GameObject(spineGameObjectName, typeof(MeshFilter), typeof(MeshRenderer), typeof(Animator), typeof(SkeletonAnimator));

			if (skeletonDataAsset.controller == null) {
				SkeletonBaker.GenerateMecanimAnimationClips(skeletonDataAsset);
			}

			go.GetComponent<Animator>().runtimeAnimatorController = skeletonDataAsset.controller;

			SkeletonAnimator anim = go.GetComponent<SkeletonAnimator>();
			anim.skeletonDataAsset = skeletonDataAsset;

			bool requiresNormals = false;

			foreach (AtlasAsset atlasAsset in anim.skeletonDataAsset.atlasAssets) {
				foreach (Material m in atlasAsset.materials) {
					if (m.shader.name.Contains("Lit")) {
						requiresNormals = true;
						break;
					}
				}
			}

			anim.calculateNormals = requiresNormals;

			SkeletonData data = skeletonDataAsset.GetSkeletonData(true);

			if (data == null) {
				for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
					string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
					skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
				}

				data = skeletonDataAsset.GetSkeletonData(true);
			}

			if (skin == null)
				skin = data.DefaultSkin;

			if (skin == null)
				skin = data.Skins.Items[0];

			anim.Initialize(false);

			anim.skeleton.SetSkin(skin);
			anim.initialSkinName = skin.Name;

			anim.skeleton.Update(1);
			anim.skeleton.UpdateWorldTransform();
			anim.LateUpdate();

			return anim;
		}
			public MeshAttachment NewMeshAttachment (Skin skin, string name, string path) {
				requirementList.Add(path);
				return new MeshAttachment(name);
			}
		public static SkeletonGraphic InstantiateSkeletonGraphic (SkeletonDataAsset skeletonDataAsset, Skin skin = null) {
			string spineGameObjectName = string.Format("SkeletonGraphic ({0})", skeletonDataAsset.name.Replace("_SkeletonData", ""));
			var go = NewSkeletonGraphicGameObject(spineGameObjectName);
			var graphic = go.GetComponent<SkeletonGraphic>();
			graphic.skeletonDataAsset = skeletonDataAsset;

			SkeletonData data = skeletonDataAsset.GetSkeletonData(true);

			if (data == null) {
				for (int i = 0; i < skeletonDataAsset.atlasAssets.Length; i++) {
					string reloadAtlasPath = AssetDatabase.GetAssetPath(skeletonDataAsset.atlasAssets[i]);
					skeletonDataAsset.atlasAssets[i] = (AtlasAsset)AssetDatabase.LoadAssetAtPath(reloadAtlasPath, typeof(AtlasAsset));
				}

				data = skeletonDataAsset.GetSkeletonData(true);
			}

			if (skin == null)
				skin = data.DefaultSkin;

			if (skin == null)
				skin = data.Skins.Items[0];

			graphic.Initialize(false);
			graphic.Skeleton.SetSkin(skin);
			graphic.initialSkinName = skin.Name;
			graphic.Skeleton.UpdateWorldTransform();
			graphic.UpdateMesh();

			return graphic;
		}
Beispiel #55
0
        private Attachment readAttachment(Skin skin, String name, Dictionary<String, Object> map)
        {
            if (map.ContainsKey("name"))
                name = (String)map["name"];

            AttachmentType type = AttachmentType.region;
            if (map.ContainsKey("type"))
                type = (AttachmentType)Enum.Parse(typeof(AttachmentType), (String)map["type"], false);
            Attachment attachment = attachmentLoader.NewAttachment(skin, type, name);

            if (attachment is RegionAttachment) {
                RegionAttachment regionAttachment = (RegionAttachment)attachment;
                regionAttachment.X = getFloat(map, "x", 0) * Scale;
                regionAttachment.Y = getFloat(map, "y", 0) * Scale;
                regionAttachment.ScaleX = getFloat(map, "scaleX", 1);
                regionAttachment.ScaleY = getFloat(map, "scaleY", 1);
                regionAttachment.Rotation = getFloat(map, "rotation", 0);
                regionAttachment.Width = getFloat(map, "width", 32) * Scale;
                regionAttachment.Height = getFloat(map, "height", 32) * Scale;
                regionAttachment.UpdateOffset();
            }

            return attachment;
        }
		private void SortPathConstraintAttachment (Skin skin, int slotIndex, Bone slotBone) {
			foreach (var entry in skin.Attachments)
				if (entry.Key.slotIndex == slotIndex) SortPathConstraintAttachment(entry.Value, slotBone);
		}
		private Attachment ReadAttachment (Skin skin, String name, Dictionary<String, Object> map) {
			if (map.ContainsKey("name"))
				name = (String)map["name"];

			var type = AttachmentType.region;
			if (map.ContainsKey("type")) {
				var typeName = (String)map["type"];
				if (typeName == "skinnedmesh") typeName = "weightedmesh";
				type = (AttachmentType)Enum.Parse(typeof(AttachmentType), typeName , false);
			}

			String path = name;
			if (map.ContainsKey("path"))
				path = (String)map["path"];

			switch (type) {
			case AttachmentType.region:
				RegionAttachment region = attachmentLoader.NewRegionAttachment(skin, name, path);
				if (region == null) return null;
				region.Path = path;
				region.x = GetFloat(map, "x", 0) * Scale;
				region.y = GetFloat(map, "y", 0) * Scale;
				region.scaleX = GetFloat(map, "scaleX", 1);
				region.scaleY = GetFloat(map, "scaleY", 1);
				region.rotation = GetFloat(map, "rotation", 0);
				region.width = GetFloat(map, "width", 32) * Scale;
				region.height = GetFloat(map, "height", 32) * Scale;
				region.UpdateOffset();

				if (map.ContainsKey("color")) {
					var color = (String)map["color"];
					region.r = ToColor(color, 0);
					region.g = ToColor(color, 1);
					region.b = ToColor(color, 2);
					region.a = ToColor(color, 3);
				}

				return region;
			case AttachmentType.mesh: {
					MeshAttachment mesh = attachmentLoader.NewMeshAttachment(skin, name, path);
					if (mesh == null) return null;

					mesh.Path = path;
					mesh.vertices = GetFloatArray(map, "vertices", Scale);
					mesh.triangles = GetIntArray(map, "triangles");
					mesh.regionUVs = GetFloatArray(map, "uvs", 1);
					mesh.UpdateUVs();

					if (map.ContainsKey("color")) {
						var color = (String)map["color"];
						mesh.r = ToColor(color, 0);
						mesh.g = ToColor(color, 1);
						mesh.b = ToColor(color, 2);
						mesh.a = ToColor(color, 3);
					}

					mesh.HullLength = GetInt(map, "hull", 0) * 2;
					if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges");
					mesh.Width = GetInt(map, "width", 0) * Scale;
					mesh.Height = GetInt(map, "height", 0) * Scale;

					return mesh;
				}
			case AttachmentType.weightedmesh: {
					WeightedMeshAttachment mesh = attachmentLoader.NewWeightedMeshAttachment(skin, name, path);
					if (mesh == null) return null;

					mesh.Path = path;
					float[] uvs = GetFloatArray(map, "uvs", 1);
					float[] vertices = GetFloatArray(map, "vertices", 1);
					var weights = new List<float>(uvs.Length * 3 * 3);
					var bones = new List<int>(uvs.Length * 3);
					float scale = Scale;
					for (int i = 0, n = vertices.Length; i < n; ) {
						int boneCount = (int)vertices[i++];
						bones.Add(boneCount);
						for (int nn = i + boneCount * 4; i < nn; ) {
							bones.Add((int)vertices[i]);
							weights.Add(vertices[i + 1] * scale);
							weights.Add(vertices[i + 2] * scale);
							weights.Add(vertices[i + 3]);
							i += 4;
						}
					}
					mesh.bones = bones.ToArray();
					mesh.weights = weights.ToArray();
					mesh.triangles = GetIntArray(map, "triangles");
					mesh.regionUVs = uvs;
					mesh.UpdateUVs();

					if (map.ContainsKey("color")) {
						var color = (String)map["color"];
						mesh.r = ToColor(color, 0);
						mesh.g = ToColor(color, 1);
						mesh.b = ToColor(color, 2);
						mesh.a = ToColor(color, 3);
					}

					mesh.HullLength = GetInt(map, "hull", 0) * 2;
					if (map.ContainsKey("edges")) mesh.Edges = GetIntArray(map, "edges");
					mesh.Width = GetInt(map, "width", 0) * Scale;
					mesh.Height = GetInt(map, "height", 0) * Scale;

					return mesh;
				}
			case AttachmentType.boundingbox:
				BoundingBoxAttachment box = attachmentLoader.NewBoundingBoxAttachment(skin, name);
				if (box == null) return null;
				box.vertices = GetFloatArray(map, "vertices", Scale);
				return box;
			}
			return null;
		}
		public RegionAttachment NewRegionAttachment (Skin skin, string name, string path) {
			RegionAttachment attachment = new RegionAttachment(name);

			Texture2D tex = sprite.texture;
			int instanceId = tex.GetInstanceID();
			AtlasRegion atlasRegion;

			// Check cache first
			if (atlasTable.ContainsKey(instanceId)) {
				atlasRegion = atlasTable[instanceId];
			} else {
				// Setup new material.
				var material = new Material(shader);
				if (sprite.packed)
					material.name = "Unity Packed Sprite Material";
				else
					material.name = sprite.name + " Sprite Material";
				material.mainTexture = tex;

				// Create faux-region to play nice with SkeletonRenderer.
				atlasRegion = new AtlasRegion();
				AtlasPage page = new AtlasPage();
				page.rendererObject = material;
				atlasRegion.page = page;

				// Cache it.
				atlasTable[instanceId] = atlasRegion;
			}

			Rect texRect = sprite.textureRect;

			//normalize rect to UV space of packed atlas
			texRect.x = Mathf.InverseLerp(0, tex.width, texRect.x);
			texRect.y = Mathf.InverseLerp(0, tex.height, texRect.y);
			texRect.width = Mathf.InverseLerp(0, tex.width, texRect.width);
			texRect.height = Mathf.InverseLerp(0, tex.height, texRect.height);

			Bounds bounds = sprite.bounds;
			Vector3 size = bounds.size;

			//MITCH: left todo: make sure this rotation thing actually works
			bool rotated = false;
			if (sprite.packed)
				rotated = sprite.packingRotation == SpritePackingRotation.Any;

			attachment.SetUVs(texRect.xMin, texRect.yMax, texRect.xMax, texRect.yMin, rotated);
			attachment.RendererObject = atlasRegion;
			attachment.SetColor(Color.white);
			attachment.ScaleX = 1;
			attachment.ScaleY = 1;
			attachment.RegionOffsetX = sprite.rect.width * (0.5f - InverseLerp(bounds.min.x, bounds.max.x, 0)) / sprite.pixelsPerUnit;
			attachment.RegionOffsetY = sprite.rect.height * (0.5f - InverseLerp(bounds.min.y, bounds.max.y, 0)) / sprite.pixelsPerUnit;
			attachment.Width = size.x;
			attachment.Height = size.y;
			attachment.RegionWidth = size.x;
			attachment.RegionHeight = size.y;
			attachment.RegionOriginalWidth = size.x;
			attachment.RegionOriginalHeight = size.y;
			attachment.UpdateOffset();

			return attachment;
		}
Beispiel #59
0
		/// <summary>Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default 
		/// skin}. Attachmentsfrom the new skin are attached if the corresponding attachment from the old skin was attached. If 
		/// there was no old skin, each slot's setup mode attachment is attached from the new skin.</summary>
		/// <param name="newSkin">May be null.</param>
		public void SetSkin (Skin newSkin) {
			if (newSkin != null) {
				if (skin != null)
					newSkin.AttachAll(this, skin);
				else {
					ExposedList<Slot> slots = this.slots;
					for (int i = 0, n = slots.Count; i < n; i++) {
						Slot slot = slots.Items[i];
						String name = slot.data.attachmentName;
						if (name != null) {
							Attachment attachment = newSkin.GetAttachment(i, name);
							if (attachment != null) slot.Attachment = attachment;
						}
					}
				}
			}
			skin = newSkin;
		}
        private void ReadAnimation(String name, Stream input, SkeletonData skeletonData)
        {
            var   timelines = new ExposedList <Timeline>();
            float scale     = Scale;
            float duration  = 0;

            // Slot timelines.
            for (int i = 0, n = ReadVarint(input, true); i < n; i++)
            {
                int slotIndex = ReadVarint(input, true);
                for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++)
                {
                    int timelineType = input.ReadByte();
                    int frameCount   = ReadVarint(input, true);
                    switch (timelineType)
                    {
                    case SLOT_COLOR: {
                        ColorTimeline timeline = new ColorTimeline(frameCount);
                        timeline.slotIndex = slotIndex;
                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            float time  = ReadFloat(input);
                            int   color = ReadInt(input);
                            float r     = ((color & 0xff000000) >> 24) / 255f;
                            float g     = ((color & 0x00ff0000) >> 16) / 255f;
                            float b     = ((color & 0x0000ff00) >> 8) / 255f;
                            float a     = ((color & 0x000000ff)) / 255f;
                            timeline.SetFrame(frameIndex, time, r, g, b, a);
                            if (frameIndex < frameCount - 1)
                            {
                                ReadCurve(input, frameIndex, timeline);
                            }
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[(timeline.FrameCount - 1) * ColorTimeline.ENTRIES]);
                        break;
                    }

                    case SLOT_ATTACHMENT: {
                        AttachmentTimeline timeline = new AttachmentTimeline(frameCount);
                        timeline.slotIndex = slotIndex;
                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            timeline.SetFrame(frameIndex, ReadFloat(input), ReadString(input));
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[frameCount - 1]);
                        break;
                    }
                    }
                }
            }

            // Bone timelines.
            for (int i = 0, n = ReadVarint(input, true); i < n; i++)
            {
                int boneIndex = ReadVarint(input, true);
                for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++)
                {
                    int timelineType = input.ReadByte();
                    int frameCount   = ReadVarint(input, true);
                    switch (timelineType)
                    {
                    case BONE_ROTATE: {
                        RotateTimeline timeline = new RotateTimeline(frameCount);
                        timeline.boneIndex = boneIndex;
                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input));
                            if (frameIndex < frameCount - 1)
                            {
                                ReadCurve(input, frameIndex, timeline);
                            }
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[(frameCount - 1) * RotateTimeline.ENTRIES]);
                        break;
                    }

                    case BONE_TRANSLATE:
                    case BONE_SCALE:
                    case BONE_SHEAR: {
                        TranslateTimeline timeline;
                        float             timelineScale = 1;
                        if (timelineType == BONE_SCALE)
                        {
                            timeline = new ScaleTimeline(frameCount);
                        }
                        else if (timelineType == BONE_SHEAR)
                        {
                            timeline = new ShearTimeline(frameCount);
                        }
                        else
                        {
                            timeline      = new TranslateTimeline(frameCount);
                            timelineScale = scale;
                        }
                        timeline.boneIndex = boneIndex;
                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input) * timelineScale, ReadFloat(input)
                                              * timelineScale);
                            if (frameIndex < frameCount - 1)
                            {
                                ReadCurve(input, frameIndex, timeline);
                            }
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TranslateTimeline.ENTRIES]);
                        break;
                    }
                    }
                }
            }

            // IK timelines.
            for (int i = 0, n = ReadVarint(input, true); i < n; i++)
            {
                int index      = ReadVarint(input, true);
                int frameCount = ReadVarint(input, true);
                IkConstraintTimeline timeline = new IkConstraintTimeline(frameCount);
                timeline.ikConstraintIndex = index;
                for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                {
                    timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadSByte(input));
                    if (frameIndex < frameCount - 1)
                    {
                        ReadCurve(input, frameIndex, timeline);
                    }
                }
                timelines.Add(timeline);
                duration = Math.Max(duration, timeline.frames[(frameCount - 1) * IkConstraintTimeline.ENTRIES]);
            }

            // Transform constraint timelines.
            for (int i = 0, n = ReadVarint(input, true); i < n; i++)
            {
                int index      = ReadVarint(input, true);
                int frameCount = ReadVarint(input, true);
                TransformConstraintTimeline timeline = new TransformConstraintTimeline(frameCount);
                timeline.transformConstraintIndex = index;
                for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                {
                    timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadFloat(input), ReadFloat(input), ReadFloat(input));
                    if (frameIndex < frameCount - 1)
                    {
                        ReadCurve(input, frameIndex, timeline);
                    }
                }
                timelines.Add(timeline);
                duration = Math.Max(duration, timeline.frames[(frameCount - 1) * TransformConstraintTimeline.ENTRIES]);
            }

            // Path constraint timelines.
            for (int i = 0, n = ReadVarint(input, true); i < n; i++)
            {
                int index = ReadVarint(input, true);
                PathConstraintData data = skeletonData.pathConstraints.Items[index];
                for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++)
                {
                    int timelineType = ReadSByte(input);
                    int frameCount   = ReadVarint(input, true);
                    switch (timelineType)
                    {
                    case PATH_POSITION:
                    case PATH_SPACING: {
                        PathConstraintPositionTimeline timeline;
                        float timelineScale = 1;
                        if (timelineType == PATH_SPACING)
                        {
                            timeline = new PathConstraintSpacingTimeline(frameCount);
                            if (data.spacingMode == SpacingMode.Length || data.spacingMode == SpacingMode.Fixed)
                            {
                                timelineScale = scale;
                            }
                        }
                        else
                        {
                            timeline = new PathConstraintPositionTimeline(frameCount);
                            if (data.positionMode == PositionMode.Fixed)
                            {
                                timelineScale = scale;
                            }
                        }
                        timeline.pathConstraintIndex = index;
                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input) * timelineScale);
                            if (frameIndex < frameCount - 1)
                            {
                                ReadCurve(input, frameIndex, timeline);
                            }
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[(frameCount - 1) * PathConstraintPositionTimeline.ENTRIES]);
                        break;
                    }

                    case PATH_MIX: {
                        PathConstraintMixTimeline timeline = new PathConstraintMixTimeline(frameCount);
                        timeline.pathConstraintIndex = index;
                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            timeline.SetFrame(frameIndex, ReadFloat(input), ReadFloat(input), ReadFloat(input));
                            if (frameIndex < frameCount - 1)
                            {
                                ReadCurve(input, frameIndex, timeline);
                            }
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[(frameCount - 1) * PathConstraintMixTimeline.ENTRIES]);
                        break;
                    }
                    }
                }
            }

            // Deform timelines.
            for (int i = 0, n = ReadVarint(input, true); i < n; i++)
            {
                Skin skin = skeletonData.skins.Items[ReadVarint(input, true)];
                for (int ii = 0, nn = ReadVarint(input, true); ii < nn; ii++)
                {
                    int slotIndex = ReadVarint(input, true);
                    for (int iii = 0, nnn = ReadVarint(input, true); iii < nnn; iii++)
                    {
                        VertexAttachment attachment = (VertexAttachment)skin.GetAttachment(slotIndex, ReadString(input));
                        bool             weighted   = attachment.bones != null;
                        float[]          vertices   = attachment.vertices;
                        int deformLength            = weighted ? vertices.Length / 3 * 2 : vertices.Length;

                        int            frameCount = ReadVarint(input, true);
                        DeformTimeline timeline   = new DeformTimeline(frameCount);
                        timeline.slotIndex  = slotIndex;
                        timeline.attachment = attachment;

                        for (int frameIndex = 0; frameIndex < frameCount; frameIndex++)
                        {
                            float   time = ReadFloat(input);
                            float[] deform;
                            int     end = ReadVarint(input, true);
                            if (end == 0)
                            {
                                deform = weighted ? new float[deformLength] : vertices;
                            }
                            else
                            {
                                deform = new float[deformLength];
                                int start = ReadVarint(input, true);
                                end += start;
                                if (scale == 1)
                                {
                                    for (int v = start; v < end; v++)
                                    {
                                        deform[v] = ReadFloat(input);
                                    }
                                }
                                else
                                {
                                    for (int v = start; v < end; v++)
                                    {
                                        deform[v] = ReadFloat(input) * scale;
                                    }
                                }
                                if (!weighted)
                                {
                                    for (int v = 0, vn = deform.Length; v < vn; v++)
                                    {
                                        deform[v] += vertices[v];
                                    }
                                }
                            }

                            timeline.SetFrame(frameIndex, time, deform);
                            if (frameIndex < frameCount - 1)
                            {
                                ReadCurve(input, frameIndex, timeline);
                            }
                        }
                        timelines.Add(timeline);
                        duration = Math.Max(duration, timeline.frames[frameCount - 1]);
                    }
                }
            }

            // Draw order timeline.
            int drawOrderCount = ReadVarint(input, true);

            if (drawOrderCount > 0)
            {
                DrawOrderTimeline timeline = new DrawOrderTimeline(drawOrderCount);
                int slotCount = skeletonData.slots.Count;
                for (int i = 0; i < drawOrderCount; i++)
                {
                    float time        = ReadFloat(input);
                    int   offsetCount = ReadVarint(input, true);
                    int[] drawOrder   = new int[slotCount];
                    for (int ii = slotCount - 1; ii >= 0; ii--)
                    {
                        drawOrder[ii] = -1;
                    }
                    int[] unchanged = new int[slotCount - offsetCount];
                    int   originalIndex = 0, unchangedIndex = 0;
                    for (int ii = 0; ii < offsetCount; ii++)
                    {
                        int slotIndex = ReadVarint(input, true);
                        // Collect unchanged items.
                        while (originalIndex != slotIndex)
                        {
                            unchanged[unchangedIndex++] = originalIndex++;
                        }
                        // Set changed items.
                        drawOrder[originalIndex + ReadVarint(input, true)] = originalIndex++;
                    }
                    // Collect remaining unchanged items.
                    while (originalIndex < slotCount)
                    {
                        unchanged[unchangedIndex++] = originalIndex++;
                    }
                    // Fill in unchanged items.
                    for (int ii = slotCount - 1; ii >= 0; ii--)
                    {
                        if (drawOrder[ii] == -1)
                        {
                            drawOrder[ii] = unchanged[--unchangedIndex];
                        }
                    }
                    timeline.SetFrame(i, time, drawOrder);
                }
                timelines.Add(timeline);
                duration = Math.Max(duration, timeline.frames[drawOrderCount - 1]);
            }

            // Event timeline.
            int eventCount = ReadVarint(input, true);

            if (eventCount > 0)
            {
                EventTimeline timeline = new EventTimeline(eventCount);
                for (int i = 0; i < eventCount; i++)
                {
                    float     time      = ReadFloat(input);
                    EventData eventData = skeletonData.events.Items[ReadVarint(input, true)];
                    Event     e         = new Event(time, eventData);
                    e.Int    = ReadVarint(input, false);
                    e.Float  = ReadFloat(input);
                    e.String = ReadBoolean(input) ? ReadString(input) : eventData.String;
                    timeline.SetFrame(i, e);
                }
                timelines.Add(timeline);
                duration = Math.Max(duration, timeline.frames[eventCount - 1]);
            }

            timelines.TrimExcess();
            skeletonData.animations.Add(new Animation(name, timelines, duration));
        }