Sprite Collection Data.
Inheritance: MonoBehaviour
Ejemplo n.º 1
0
 public static void DoPickSprite(tk2dSpriteCollectionData spriteCollection, int spriteId, string title, tk2dSpriteGuiUtility.SpriteChangedCallback callback, object callbackData)
 {
     tk2dSpritePickerPopup popup = EditorWindow.GetWindow(typeof(tk2dSpritePickerPopup), true, title, true) as tk2dSpritePickerPopup;
     popup.InitForSpriteInCollection(spriteCollection, spriteId);
     popup.callback = callback;
     popup.callbackData = callbackData;
 }
 public void Create(tk2dSpriteCollectionSize spriteCollectionSize, Texture texture, tk2dBaseSprite.Anchor anchor)
 {
     this.DestroyInternal();
     if (texture != null)
     {
         this.spriteCollectionSize.CopyFrom(spriteCollectionSize);
         this.texture = texture;
         this.anchor = anchor;
         GameObject parentObject = new GameObject("tk2dSpriteFromTexture - " + texture.name);
         parentObject.transform.localPosition = Vector3.zero;
         parentObject.transform.localRotation = Quaternion.identity;
         parentObject.transform.localScale = Vector3.one;
         parentObject.hideFlags = HideFlags.DontSave;
         Vector2 vector = tk2dSpriteGeomGen.GetAnchorOffset(anchor, (float) texture.width, (float) texture.height);
         string[] names = new string[] { "unnamed" };
         Rect[] regions = new Rect[] { new Rect(0f, 0f, (float) texture.width, (float) texture.height) };
         Vector2[] anchors = new Vector2[] { vector };
         this.spriteCollection = SpriteCollectionGenerator.CreateFromTexture(parentObject, texture, spriteCollectionSize, new Vector2((float) texture.width, (float) texture.height), names, regions, null, anchors, new bool[1]);
         string str = "SpriteFromTexture " + texture.name;
         this.spriteCollection.spriteCollectionName = str;
         this.spriteCollection.spriteDefinitions[0].material.name = str;
         this.spriteCollection.spriteDefinitions[0].material.hideFlags = HideFlags.DontSave | HideFlags.HideInInspector;
         this.Sprite.SetSprite(this.spriteCollection, 0);
     }
 }
	void DoDemoTexturePacker(tk2dSpriteCollectionSize spriteCollectionSize) {
		if (GUILayout.Button("Import")) {
			DestroyData();

			// Create atlas
			spriteCollectionInstance = tk2dSpriteCollectionData.CreateFromTexturePacker(spriteCollectionSize, texturePackerExportFile.text, texturePackerTexture );

			GameObject go = new GameObject("sprite");
			go.transform.localPosition = new Vector3(-1, 0, 0);
			spriteInstance = go.AddComponent<tk2dSprite>();
			spriteInstance.SetSprite(spriteCollectionInstance, "sun");

			go = new GameObject("sprite2");
			go.transform.parent = spriteInstance.transform;
			go.transform.localPosition = new Vector3(2, 0, 0);
			tk2dSprite sprite = go.AddComponent<tk2dSprite>();
			sprite.SetSprite(spriteCollectionInstance, "2dtoolkit_logo");

			go = new GameObject("sprite3");
			go.transform.parent = spriteInstance.transform;
			go.transform.localPosition = new Vector3(1, 1, 0);
			sprite = go.AddComponent<tk2dSprite>();
			sprite.SetSprite(spriteCollectionInstance, "button_up");

			go = new GameObject("sprite4");
			go.transform.parent = spriteInstance.transform;
			go.transform.localPosition = new Vector3(1, -1, 0);
			sprite = go.AddComponent<tk2dSprite>();
			sprite.SetSprite(spriteCollectionInstance, "Rock");
		}
	}
 private void DoDemoRuntimeSpriteCollection(tk2dSpriteCollectionSize spriteCollectionSize)
 {
     if (GUILayout.Button("Use Full Texture", new GUILayoutOption[0]))
     {
         this.DestroyData();
         Rect region = new Rect(0f, 0f, (float) this.runtimeTexture.width, (float) this.runtimeTexture.height);
         Vector2 anchor = new Vector2(region.width / 2f, region.height / 2f);
         this.spriteInstance = tk2dSprite.CreateFromTexture(this.runtimeTexture, spriteCollectionSize, region, anchor, string.Empty).GetComponent<tk2dSprite>();
         this.spriteCollectionInstance = this.spriteInstance.Collection;
     }
     if (GUILayout.Button("Extract Region)", new GUILayoutOption[0]))
     {
         this.DestroyData();
         Rect rect2 = new Rect(79f, 243f, 215f, 200f);
         Vector2 vector2 = new Vector2(rect2.width / 2f, rect2.height / 2f);
         this.spriteInstance = tk2dSprite.CreateFromTexture(this.runtimeTexture, spriteCollectionSize, rect2, vector2, string.Empty).GetComponent<tk2dSprite>();
         this.spriteCollectionInstance = this.spriteInstance.Collection;
     }
     if (GUILayout.Button("Extract multiple Sprites", new GUILayoutOption[0]))
     {
         this.DestroyData();
         string[] names = new string[] { "Extracted region", "Another region", "Full sprite" };
         Rect[] regions = new Rect[] { new Rect(79f, 243f, 215f, 200f), new Rect(256f, 0f, 64f, 64f), new Rect(0f, 0f, (float) this.runtimeTexture.width, (float) this.runtimeTexture.height) };
         Vector2[] anchors = new Vector2[] { new Vector2(regions[0].width / 2f, regions[0].height / 2f), new Vector2(0f, regions[1].height), new Vector2(0f, regions[1].height) };
         this.spriteCollectionInstance = tk2dSpriteCollectionData.CreateFromTexture(this.runtimeTexture, spriteCollectionSize, names, regions, anchors);
         GameObject obj4 = new GameObject("sprite");
         obj4.transform.localPosition = new Vector3(-1f, 0f, 0f);
         this.spriteInstance = obj4.AddComponent<tk2dSprite>();
         this.spriteInstance.SetSprite(this.spriteCollectionInstance, 0);
         obj4 = new GameObject("sprite2");
         obj4.transform.parent = this.spriteInstance.transform;
         obj4.transform.localPosition = new Vector3(2f, 0f, 0f);
         obj4.AddComponent<tk2dSprite>().SetSprite(this.spriteCollectionInstance, "Another region");
     }
 }
    public void Create( tk2dSpriteCollectionSize spriteCollectionSize, Texture texture, tk2dBaseSprite.Anchor anchor )
    {
        DestroyInternal();
        if (texture != null) {
            // Copy values
            this.spriteCollectionSize.CopyFrom( spriteCollectionSize );
            this.texture = texture;
            this.anchor = anchor;

            Vector2 anchorPos = tk2dSpriteGeomGen.GetAnchorOffset( anchor, texture.width, texture.height );
            spriteCollection = tk2dRuntime.SpriteCollectionGenerator.CreateFromTexture(
                gameObject,
                texture,
                spriteCollectionSize,
                new Vector2(texture.width, texture.height),
                new string[] { "unnamed" } ,
                new Rect[] { new Rect(0, 0, texture.width, texture.height) },
                null,
                new Vector2[] { anchorPos },
                new bool[] { false } );

            // don't want to save or see this
            spriteCollection.hideFlags = HideFlags.HideInInspector;

            string objName = "SpriteFromTexture " + texture.name;
            spriteCollection.spriteCollectionName = objName;
            spriteCollection.spriteDefinitions[0].material.name = objName;
            spriteCollection.spriteDefinitions[0].material.hideFlags = HideFlags.DontSave | HideFlags.HideInInspector;

            Sprite.SetSprite( spriteCollection, 0 );
        }
    }
	public void CopyFrom(tk2dSpriteAnimationFrame source, bool full)
	{
		spriteCollection = source.spriteCollection;
		spriteId = source.spriteId;
		
		if (full) CopyTriggerFrom(source);
	}
Ejemplo n.º 7
0
	public void Create( tk2dSpriteCollectionSize spriteCollectionSize, Texture texture, tk2dBaseSprite.Anchor anchor ) {
		DestroyInternal();
		if (texture != null) {
			// Copy values
			this.spriteCollectionSize.CopyFrom( spriteCollectionSize );
			this.texture = texture;
			this.anchor = anchor;

			GameObject go = new GameObject("tk2dSpriteFromTexture - " + texture.name);
			go.transform.localPosition = Vector3.zero;
			go.transform.localRotation = Quaternion.identity;
			go.transform.localScale = Vector3.one;
			go.hideFlags = HideFlags.DontSave;
			
			Vector2 anchorPos = tk2dSpriteGeomGen.GetAnchorOffset( anchor, texture.width, texture.height );
			spriteCollection = tk2dRuntime.SpriteCollectionGenerator.CreateFromTexture(
				go, 
				texture, 
				spriteCollectionSize,
				new Vector2(texture.width, texture.height),
				new string[] { "unnamed" } ,
				new Rect[] { new Rect(0, 0, texture.width, texture.height) },
				null,
				new Vector2[] { anchorPos },
				new bool[] { false } );

			string objName = "SpriteFromTexture " + texture.name;
			spriteCollection.spriteCollectionName = objName;
			spriteCollection.spriteDefinitions[0].material.name = objName;
			spriteCollection.spriteDefinitions[0].material.hideFlags = HideFlags.DontSave | HideFlags.HideInInspector;

			Sprite.SetSprite( spriteCollection, 0 );
		}
	}
		public TransientData( tk2dSpriteCollectionData data ) {
			name = data.spriteCollectionName;
			dataWeakRef = new System.WeakReference(data);
			if (data.needMaterialInstance) {
				createdMaterials = data.materialInsts;
				createdTextures = data.textureInsts;
			}
		}
	void DoDemoRuntimeSpriteCollection(tk2dSpriteCollectionSize spriteCollectionSize) {
		if (GUILayout.Button("Use Full Texture")) {
			DestroyData();

			// Create a sprite, using the entire texture as the sprite
			Rect region = new Rect(0, 0, runtimeTexture.width, runtimeTexture.height);
			Vector2 anchor = new Vector2(region.width / 2, region.height / 2);
			GameObject go = tk2dSprite.CreateFromTexture(runtimeTexture, spriteCollectionSize, region, anchor);
			spriteInstance = go.GetComponent<tk2dSprite>();
			spriteCollectionInstance = spriteInstance.Collection;
		}

		if (GUILayout.Button("Extract Region)")) {
			DestroyData();

			// Create a sprite, using a region of the texture as the sprite
			Rect region = new Rect(79, 243, 215, 200);
			Vector2 anchor = new Vector2(region.width / 2, region.height / 2);
			GameObject go = tk2dSprite.CreateFromTexture(runtimeTexture, spriteCollectionSize, region, anchor);
			spriteInstance = go.GetComponent<tk2dSprite>();
			spriteCollectionInstance = spriteInstance.Collection;
		}

		if (GUILayout.Button("Extract multiple Sprites")) {
			DestroyData();

			string[] names = new string[] {
				"Extracted region",
				"Another region",
				"Full sprite",
			};
			Rect[] regions = new Rect[] {
				new Rect(79, 243, 215, 200), 
				new Rect(256, 0, 64, 64),
				new Rect(0, 0, runtimeTexture.width, runtimeTexture.height)
			};
			Vector2[] anchors = new Vector2[] {
				new Vector2(regions[0].width / 2, regions[0].height / 2),
				new Vector2(0, regions[1].height),
				new Vector2(0, regions[1].height)
			};

			// Create a sprite collection with multiple sprites, using regions of the texture
			spriteCollectionInstance = tk2dSpriteCollectionData.CreateFromTexture(runtimeTexture, spriteCollectionSize, names, regions, anchors);
			GameObject go = new GameObject("sprite");
			go.transform.localPosition = new Vector3(-1, 0, 0);
			spriteInstance = go.AddComponent<tk2dSprite>();
			spriteInstance.SetSprite(spriteCollectionInstance, 0);

			go = new GameObject("sprite2");
			go.transform.parent = spriteInstance.transform;
			go.transform.localPosition = new Vector3(2, 0, 0);
			tk2dSprite sprite = go.AddComponent<tk2dSprite>();
			sprite.SetSprite(spriteCollectionInstance, "Another region");
		}		
	}
Ejemplo n.º 10
0
    public void CopyFrom(tk2dSpriteAnimationFrame source)
    {
        spriteCollection = source.spriteCollection;
        spriteId = source.spriteId;

        triggerEvent = source.triggerEvent;
        eventInfo = source.eventInfo;
        eventInt = source.eventInt;
        eventFloat = source.eventFloat;
    }
Ejemplo n.º 11
0
 public static int GetValidSpriteId(tk2dSpriteCollectionData spriteCollection, int spriteId)
 {
     if (! (spriteId > 0 && spriteId < spriteCollection.spriteDefinitions.Length &&
         spriteCollection.spriteDefinitions[spriteId].Valid) )
     {
         spriteId = spriteCollection.FirstValidDefinitionIndex;
         if (spriteId == -1) spriteId = 0;
     }
     return spriteId;
 }
    public static Texture2D GetThumbnailTexture(tk2dSpriteCollectionData gen, int spriteId)
    {
        gen = gen.inst;

        // If we already have a cached texture which matches the requirements, use that
        foreach (var thumb in thumbnailCache)
        {
            if (thumb.cachedTexture	!= null && thumb.cachedSpriteCollection	== gen && thumb.cachedSpriteId == spriteId)
                return thumb.cachedTexture;
        }

        // Generate a texture
        var param = gen.spriteDefinitions[spriteId];
        if (param.sourceTextureGUID == null || param.sourceTextureGUID.Length != 0)
        {
            string assetPath = AssetDatabase.GUIDToAssetPath(param.sourceTextureGUID);
            if (assetPath.Length > 0)
            {
                Texture2D tex = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)) as Texture2D;
                if (tex != null)
                {
                    SpriteThumbnailCache thumbnail = new SpriteThumbnailCache();

                    if (param.extractRegion)
                    {
                        Texture2D localTex = new Texture2D(param.regionW, param.regionH);
                        for (int y = 0; y < param.regionH; ++y)
                        {
                            for (int x = 0; x < param.regionW; ++x)
                            {
                                localTex.SetPixel(x, y, tex.GetPixel(param.regionX + x, param.regionY + y));
                            }
                        }
                        localTex.Apply();
                        thumbnail.cachedTexture = localTex;
                        thumbnail.needDestroy = true;
                    }
                    else
                    {
                        thumbnail.cachedTexture = tex;
                    }

                    // Prime cache for next time
                    thumbnail.cachedSpriteCollection = gen;
                    thumbnail.cachedSpriteId = spriteId;
                    thumbnailCache.Add(thumbnail);

                    return thumbnail.cachedTexture;
                }
            }
        }

        return null;
    }
Ejemplo n.º 13
0
 static void Processtk2dSpriteCollection(tk2dSpriteCollectionData spriteCollectionData)
 {
     if (spriteCollectionData != null)
     {
         BuildSpriteCollection(spriteCollectionData);
     }
     else
     {
         Logger.LogWarning("空的SpriteCollectionData在SpriteCollection");
     }
 }
 private void DestroyInternal()
 {
     if (this.spriteCollection != null)
     {
         if (this.spriteCollection.spriteDefinitions[0].material != null)
         {
             UnityEngine.Object.DestroyImmediate(this.spriteCollection.spriteDefinitions[0].material);
         }
         UnityEngine.Object.DestroyImmediate(this.spriteCollection.gameObject);
         this.spriteCollection = null;
     }
 }
		// Sprite changed callback
		// Create an instance - only ever use the instance through the property
		void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data) {
			FrameGroup fg = data as FrameGroup;
			// Ensure the user hasn't switched sprite collection
			if (fg != null && frameGroups.IndexOf(fg) != -1) {
				fg.spriteCollection = spriteCollection;
				fg.spriteId = spriteId;
				foreach (tk2dSpriteAnimationFrame frame in fg.frames) {
					frame.spriteCollection = spriteCollection;
					frame.spriteId = spriteId;
				}
				RecalculateFrames();
				Repaint();
			}
		}
    /// <summary>
    /// Unloads the atlas texture data in this sprite collection.
    /// This will be reloaded when the data is accessed again.
    /// Make sure all sprites using this collection have already been destroyed.
    /// </summary>
    public void UnloadTextures()
    {
        // Debug.Log(Resources.FindObjectsOfTypeAll(typeof(Texture2D)).Length);

        tk2dSpriteCollectionData theInst = inst;

        foreach (Texture2D texture in theInst.textures)
        {
            Resources.UnloadAsset(texture);
        }

        theInst.DestroyMaterialInsts();
        theInst.DestroyTextureInsts();

        // Debug.Log(Resources.FindObjectsOfTypeAll(typeof(Texture2D)).Length);
    }
Ejemplo n.º 17
0
    public virtual void ForceBuild()
    {
        if (collection == null)
        {
            return;
        }
        collectionInst = collection.inst;
        if (spriteId < 0 || spriteId >= collectionInst.spriteDefinitions.Length)
        {
            spriteId = 0;
        }
        Build();
#if UNITY_EDITOR
        EditMode__CreateCollider();
#endif
    }
	int GetSpriteCollectionId(tk2dSpriteCollectionData data)
	{
		if (indexLookup.ContainsKey(data))
			return indexLookup[data];
		
		var guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(data));	
		for (int i = 0; i < spriteCollectionIndex.Length; ++i)
		{
			if (spriteCollectionIndex[i].spriteCollectionDataGUID == guid)
			{
				indexLookup[data] = i;
				return i;
			}
		}
		return 0; // default
	}
Ejemplo n.º 19
0
    public static void SpriteSelector(tk2dSpriteCollectionData spriteCollection, int spriteId, SpriteChangedCallback callback, object callbackData)
    {
        tk2dSpriteCollectionData newCollection = spriteCollection;
        int newSpriteId = spriteId;

        GUILayout.BeginHorizontal();

        GUILayout.BeginVertical();
        newCollection = SpriteCollectionList("Collection", spriteCollection);
        if (spriteCollection != null && spriteCollection.Count != 0)
        {
            if (spriteId < 0 || spriteId >= spriteCollection.Count || !spriteCollection.inst.spriteDefinitions[spriteId].Valid)
            {
                newSpriteId = spriteCollection.FirstValidDefinitionIndex;
            }

            GUILayout.BeginHorizontal();
            newSpriteId = SpriteList("Sprite", newSpriteId, spriteCollection);

            if (tk2dPreferences.inst.displayEditSpriteButton &&
                spriteCollection != null && spriteCollection.dataGuid != TransientGUID &&
                GUILayout.Button("Edit...", EditorStyles.miniButton, GUILayout.MaxWidth(40f), GUILayout.MaxHeight(14f)))
            {
                tk2dSpriteCollection gen = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(spriteCollection.spriteCollectionGUID), typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
                if (gen != null)
                {
                    tk2dSpriteCollectionEditorPopup v = EditorWindow.GetWindow(typeof(tk2dSpriteCollectionEditorPopup), false, "Sprite Collection Editor") as tk2dSpriteCollectionEditorPopup;
                    v.SetGeneratorAndSelectedSprite(gen, spriteId);
                }
            }

            GUILayout.EndHorizontal();
        }

        if (callback != null && (newCollection != spriteCollection || newSpriteId != spriteId))
        {
            callback(newCollection, newSpriteId, callbackData);
        }
        GUILayout.EndVertical();

        if (GUILayout.Button("...", GUILayout.Height(32), GUILayout.Width(32)))
        {
            SpriteSelectorPopup(spriteCollection, spriteId, callback, callbackData);
        }

        GUILayout.EndHorizontal();
    }
Ejemplo n.º 20
0
    public void AddSpriteCollectionData(tk2dSpriteCollectionData sc)
    {
        #if UNITY_EDITOR
        // prune list
        GetSpriteCollectionIndex();
        spriteCollectionIndex.RemoveAll(item => item == null);
        string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(sc));

        bool existing = false;
        tk2dSpriteCollectionIndex indexEntry = null;
        foreach (var v in spriteCollectionIndex)
        {
            if (v.spriteCollectionDataGUID == guid)
            {
                indexEntry = v;
                existing = true;
                break;
            }
        }
        if (indexEntry == null)
            indexEntry = new tk2dSpriteCollectionIndex();

        indexEntry.name = sc.spriteCollectionName;
        indexEntry.spriteCollectionDataGUID = guid;
        indexEntry.spriteCollectionGUID = sc.spriteCollectionGUID;
        indexEntry.spriteNames = new string[sc.spriteDefinitions.Length];
        indexEntry.spriteTextureGUIDs = new string[sc.spriteDefinitions.Length];
        indexEntry.version = sc.version;
        for (int i = 0; i < sc.spriteDefinitions.Length; ++i)
        {
            var s = sc.spriteDefinitions[i];
            if (s != null)
            {
                indexEntry.spriteNames[i] = sc.spriteDefinitions[i].name;
                indexEntry.spriteTextureGUIDs[i] = sc.spriteDefinitions[i].sourceTextureGUID;
            }
            else
            {
                indexEntry.spriteNames[i] = "";
                indexEntry.spriteTextureGUIDs[i] = "";
            }
        }

        if (!existing)
            spriteCollectionIndex.Add(indexEntry);
        #endif
    }
	static void Create()
	{
		tk2dSpriteCollectionData sprColl = null;
		if (sprColl == null)
		{
			// try to inherit from other TileMaps in scene
			tk2dTileMap sceneTileMaps = GameObject.FindObjectOfType(typeof(tk2dTileMap)) as tk2dTileMap;
			if (sceneTileMaps)
			{
				sprColl = sceneTileMaps.Editor__SpriteCollection;
			}
		}

		if (sprColl == null)
		{
			tk2dSpriteCollectionIndex[] spriteCollections = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
			foreach (var v in spriteCollections)
			{
				if (v.managedSpriteCollection) continue; // don't wanna pick a managed one
				
				GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
				var sc = scgo.GetComponent<tk2dSpriteCollectionData>();
				if (sc != null && sc.spriteDefinitions != null && sc.spriteDefinitions.Length > 0 && sc.allowMultipleAtlases == false)
				{
					sprColl = sc;
					break;
				}
			}

			if (sprColl == null)
			{
				EditorUtility.DisplayDialog("Create TileMap", "Unable to create sprite as no SpriteCollections have been found.", "Ok");
				return;
			}
		}

		GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TileMap");
		go.transform.position = Vector3.zero;
		go.transform.rotation = Quaternion.identity;
		tk2dTileMap tileMap = go.AddComponent<tk2dTileMap>();
		tileMap.Editor__SpriteCollection = sprColl;
		
		tileMap.Build(tk2dTileMap.BuildFlags.ForceBuild);
		
		Selection.activeGameObject = go;
		Undo.RegisterCreatedObjectUndo(go, "Create TileMap");
	}
Ejemplo n.º 22
0
        public static void Replace(Action <tk2dSpriteCollectionData> orig, tk2dSpriteCollectionData self)
        {
            orig(self);


            if (replacedCollections.Contains(self))
            {
                return;
            }

            bool found       = false;
            bool spriteSheet = false;

            foreach (string collectionName in collectionsToReplace)
            {
                if (self.name.Equals(collectionName))
                {
                    found = true;
                }
            }

            foreach (string sheetName in spriteSheetsToReplace)
            {
                if (self.name.Equals(sheetName))
                {
                    found       = true;
                    spriteSheet = true;
                }
            }

            if (!found)
            {
                return;
            }

            ETGModConsole.Log("Replacing collection: " + self.name);
            if (spriteSheet)
            {
                ReplaceWithSpriteSheet(self);
            }
            else
            {
                ReplaceWithTextures(self);
            }

            replacedCollections.Add(self);
        }
Ejemplo n.º 23
0
        public static tk2dSpriteCollectionData HandleAnimations(tk2dBaseSprite sprite, Texture2D playerSheet)
        {
            tk2dSpriteCollectionData orig = sprite.Collection;

            var copyCollection = GameObject.Instantiate(orig);

            GameObject.DontDestroyOnLoad(copyCollection);

            tk2dSpriteDefinition[] copyDefinitions = new tk2dSpriteDefinition[orig.spriteDefinitions.Length];
            for (int i = 0; i < copyCollection.spriteDefinitions.Length; i++)
            {
                copyDefinitions[i] = Copy(orig.spriteDefinitions[i]);
            }
            copyCollection.spriteDefinitions = copyDefinitions;

            if (playerSheet != null)
            {
                var materialsToCopy = orig.materials;
                copyCollection.materials = new Material[orig.materials.Length];
                for (int i = 0; i < copyCollection.materials.Length; i++)
                {
                    if (materialsToCopy[i] == null)
                    {
                        continue;
                    }
                    var mat = new Material(materialsToCopy[i]);
                    GameObject.DontDestroyOnLoad(mat);
                    mat.mainTexture             = playerSheet;
                    mat.name                    = materialsToCopy[i].name;
                    copyCollection.materials[i] = mat;
                }

                for (int i = 0; i < copyCollection.spriteDefinitions.Length; i++)
                {
                    foreach (var mat in copyCollection.materials)
                    {
                        if (mat != null && copyDefinitions[i].material.name.Equals(mat.name))
                        {
                            copyDefinitions[i].material     = mat;
                            copyDefinitions[i].materialInst = new Material(mat);
                        }
                    }
                }
            }

            return(copyCollection);
        }
Ejemplo n.º 24
0
        public static void ReplaceWithTextures(tk2dSpriteCollectionData data)
        {
            List <Texture2D> replacements = ResourceExtractor.GetTexturesFromFolder(data.name);

            foreach (Texture2D texture in replacements)
            {
                tk2dSpriteDefinition def = GetDefinition(data, texture.name);
                if (def != null)
                {
                    def.ReplaceTexture(texture);
                }
                else
                {
                    ETGModConsole.Log("<color=#FF0000FF>" + texture.name + " not found. </color>");
                }
            }
        }
Ejemplo n.º 25
0
    public void setItemIcon(tk2dSprite ui, GameObject obj)
    {
        item_property            itemproperty   = obj.GetComponent <item_property>();
        GameObject               collection     = (GameObject)Resources.LoadAssetAtPath("Assets/Sprites/sheet/itemicon/itemIconCollection Data/itemIconCollection.prefab", typeof(Object));
        tk2dSpriteCollectionData collectionData = collection.GetComponent <tk2dSpriteCollectionData> ();
        int iconId = itemproperty.ID;

        if (iconId != 0)
        {
            ui.gameObject.GetComponent <MeshRenderer>().enabled = true;
            ui.SetSprite(collectionData, "item_" + iconId);
        }
        else
        {
            ui.gameObject.GetComponent <MeshRenderer>().enabled = false;
        }
    }
        // Internal set clip, reset all
        void SetClip(tk2dSpriteAnimationClip clip)
        {
            if (this.clip != clip)
            {
                // reset stuff
                this.clip = clip;

                timelineEditor.Reset();

                if (!repeatPlayAnimation)
                {
                    playAnimation = false;
                }
                this.Sprite.Stop();

                // build frame groups
                if (clip != null)
                {
                    frameGroups.Clear();
                    tk2dSpriteCollectionData lastSc = null;
                    int        lastSpriteId         = -1;
                    FrameGroup frameGroup           = null;
                    for (int i = 0; i < clip.frames.Length; ++i)
                    {
                        tk2dSpriteAnimationFrame f = clip.frames[i];
                        if (f.spriteCollection != lastSc || f.spriteId != lastSpriteId)
                        {
                            if (frameGroup != null)
                            {
                                frameGroups.Add(frameGroup);
                            }
                            frameGroup = new FrameGroup();
                            frameGroup.spriteCollection = f.spriteCollection;
                            frameGroup.spriteId         = f.spriteId;
                        }
                        lastSc       = f.spriteCollection;
                        lastSpriteId = f.spriteId;
                        frameGroup.frames.Add(f);
                    }
                    if (frameGroup != null)
                    {
                        frameGroups.Add(frameGroup);
                    }
                }
            }
        }
Ejemplo n.º 27
0
    public void ResetPlatformData()
    {
        tk2dEditorSpriteDataUnloader.Unregister(this);

        if (platformSpecificData != null)
        {
            platformSpecificData.DestroyTextureInsts();
        }
        DestroyTextureInsts();

        if (platformSpecificData)
        {
            platformSpecificData = null;
        }

        materialInsts = null;
    }
Ejemplo n.º 28
0
        string BuildTextSpriteList(List <ClipEditor.FrameGroup> frameGroups)
        {
            bool fromSameCollection       = true;
            bool areNamesValid            = true;
            tk2dSpriteCollectionData coll = null;
            List <string>            s    = new List <string>();

            foreach (ClipEditor.FrameGroup frameGroup in frameGroups)
            {
                tk2dSpriteDefinition def = frameGroup.spriteCollection.spriteDefinitions[frameGroup.spriteId];
                if (coll == null)
                {
                    coll = frameGroup.spriteCollection;
                }
                if (coll != frameGroup.spriteCollection)
                {
                    fromSameCollection = false;
                }
                string spriteName = def.name;
                if (spriteName.IndexOf(";") != -1)
                {
                    areNamesValid = false;
                }
                int frameCount = frameGroup.frames.Count;
                s.Add((frameCount == 1) ? (spriteName) : (spriteName + ";" + frameCount.ToString()));
            }
            if (!fromSameCollection)
            {
                EditorUtility.DisplayDialog("Text importer failed", "Current animation clip contains sprites from multiple collections", "Ok");
                return("");
            }
            if (!areNamesValid)
            {
                EditorUtility.DisplayDialog("Text importer failed", "Sprite names contain the ; character", "Ok");
                return("");
            }

            string spriteList = "";

            for (int i = 0; i < s.Count; ++i)
            {
                spriteList += s[i] + "\n";
            }
            return(spriteList);
        }
Ejemplo n.º 29
0
    static void DoCreateSpriteObject()
    {
        tk2dSpriteCollectionData sprColl = null;

        if (sprColl == null)
        {
            // try to inherit from other Sprites in scene
            tk2dSprite spr = GameObject.FindObjectOfType(typeof(tk2dSprite)) as tk2dSprite;
            if (spr)
            {
                sprColl = spr.collection;
            }
        }

        if (sprColl == null)
        {
            tk2dSpriteCollectionIndex[] spriteCollections = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
            foreach (var v in spriteCollections)
            {
                GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
                var        sc   = scgo.GetComponent <tk2dSpriteCollectionData>();
                if (sc != null && sc.spriteDefinitions != null && sc.spriteDefinitions.Length > 0)
                {
                    sprColl = sc;
                    break;
                }
            }

            if (sprColl == null)
            {
                EditorUtility.DisplayDialog("Create Sprite", "Unable to create sprite as no SpriteCollections have been found.", "Ok");
                return;
            }
        }

        GameObject go     = tk2dEditorUtility.CreateGameObjectInScene("Sprite");
        tk2dSprite sprite = go.AddComponent <tk2dSprite>();

        sprite.collection        = sprColl;
        sprite.renderer.material = sprColl.FirstValidDefinition.material;
        sprite.Build();

        Selection.activeGameObject = go;
        Undo.RegisterCreatedObjectUndo(go, "Create Sprite");
    }
Ejemplo n.º 30
0
    /// <summary>
    /// Sets sprite by identifier from the new collection.
    /// </summary>
    public void SetSprite(tk2dSpriteCollectionData newCollection, int newSpriteId)
    {
        bool switchedCollection = false;

        if (Collection != newCollection)
        {
            Collection         = newCollection;
            _spriteId          = -1;    // force an update, but only when the collection has changed
            switchedCollection = true;
        }

        spriteId = newSpriteId;

        if (switchedCollection)
        {
            UpdateMaterial();
        }
    }
Ejemplo n.º 31
0
        public static int AddTk2dSpriteDefinitions(this tk2dSpriteCollectionData collection, tk2dSpriteCollectionData addcollection, int startIndex = 0, int?endIndex = null)
        {
            int offset = collection.spriteDefinitions.Length - startIndex;
            List <tk2dSpriteDefinition> definitions = collection.spriteDefinitions.ToList();

            if (endIndex == null)
            {
                endIndex = addcollection.spriteDefinitions.Length;
            }

            for (int i = startIndex; i < endIndex; i++)
            {
                definitions.Add(addcollection.spriteDefinitions[i]);
            }

            collection.spriteDefinitions = definitions.ToArray();
            return(offset);
        }
Ejemplo n.º 32
0
        // Sprite changed callback
        // Create an instance - only ever use the instance through the property
        void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data)
        {
            FrameGroup fg = data as FrameGroup;

            // Ensure the user hasn't switched sprite collection
            if (fg != null && frameGroups.IndexOf(fg) != -1)
            {
                fg.spriteCollection = spriteCollection;
                fg.spriteId         = spriteId;
                foreach (tk2dSpriteAnimationFrame frame in fg.frames)
                {
                    frame.spriteCollection = spriteCollection;
                    frame.spriteId         = spriteId;
                }
                RecalculateFrames();
                Repaint();
            }
        }
Ejemplo n.º 33
0
        public SpriteFlatData(string name, Texture2D texture, float width, float height, ScaleType scaleType)
        {
            this.name = name;

            float textureWidth  = texture.width;
            float textureHeight = texture.height;

            switch (scaleType)
            {
            case ScaleType.NONE:
                this.width  = textureWidth;
                this.height = textureHeight;
                break;

            case ScaleType.SCALED_WIDTH:
                this.width  = width;
                this.height = width * textureHeight / textureWidth;
                break;

            case ScaleType.SCALED_HEIGHT:
                this.width  = height * textureWidth / textureHeight;
                this.height = height;
                break;

            case ScaleType.SCALED:
            default:
                this.width  = width;
                this.height = height;
                break;
            }
            this.regionWidth  = textureWidth;
            this.regionHeight =
                texture.wrapMode == TextureWrapMode.Repeat ?
                this.height * textureWidth / this.width :
                textureHeight
            ;

            Rect    region = new Rect(0f, 0f, this.regionWidth, this.regionHeight);
            Vector2 anchor = new Vector2(this.regionWidth / 2, this.regionHeight / 2);

            tk2dRuntime.SpriteCollectionSize size = tk2dRuntime.SpriteCollectionSize.ForTk2dCamera();
            this.data = tk2dRuntime.SpriteCollectionGenerator.CreateFromTexture(texture, size, region, anchor);
            this.data.gameObject.name = String.Format("DataSpriteFlat{0}", name);
        }
    public void Build()
    {
        UpgradeData();

        if (spriteCollection != null)
        {
            spriteCollectionInst = spriteCollection.inst;
        }

        if (mesh == null)
        {
            mesh = new Mesh();
#if UNITY_EDITOR
            mesh.name = "tk2d mesh";
#endif
            mesh.hideFlags = HideFlags.DontSave;
            GetComponent <MeshFilter>().mesh = mesh;
        }
        else
        {
            // this happens when the sprite rebuilds
            mesh.Clear();
        }

        if (colliderMesh)
        {
#if UNITY_EDITOR
            DestroyImmediate(colliderMesh);
#else
            Destroy(colliderMesh);
#endif
            colliderMesh = null;
        }

        if (!spriteCollectionInst || batchedSprites == null || batchedSprites.Length == 0)
        {
        }
        else
        {
            SortBatchedSprites();
            BuildRenderMesh();
            BuildPhysicsMesh();
        }
    }
    int GetSpriteCollectionId(tk2dSpriteCollectionData data)
    {
        if (indexLookup.ContainsKey(data))
        {
            return(indexLookup[data]);
        }

        var guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(data));

        for (int i = 0; i < spriteCollectionIndex.Length; ++i)
        {
            if (spriteCollectionIndex[i].spriteCollectionDataGUID == guid)
            {
                indexLookup[data] = i;
                return(i);
            }
        }
        return(0);        // default
    }
Ejemplo n.º 36
0
        private static void SetupBeamPart(tk2dSpriteAnimation beamAnimation, List <string> animSpritePaths, string animationName, int fps, Vector2?colliderDimensions = null, Vector2?colliderOffsets = null, Vector3[] overrideVertices = null)
        {
            tk2dSpriteAnimationClip clip = new tk2dSpriteAnimationClip()
            {
                name = animationName, frames = new tk2dSpriteAnimationFrame[0], fps = fps
            };
            List <string> spritePaths = animSpritePaths;

            List <tk2dSpriteAnimationFrame> frames = new List <tk2dSpriteAnimationFrame>();

            foreach (string path in spritePaths)
            {
                tk2dSpriteCollectionData collection = ETGMod.Databases.Items.ProjectileCollection;
                int frameSpriteId             = SpriteBuilder.AddSpriteToCollection(path, collection);
                tk2dSpriteDefinition frameDef = collection.spriteDefinitions[frameSpriteId];
                frameDef.ConstructOffsetsFromAnchor(tk2dBaseSprite.Anchor.MiddleCenter);
                if (overrideVertices != null)
                {
                    frameDef.colliderVertices = overrideVertices;
                }
                else
                {
                    if (colliderDimensions == null || colliderOffsets == null)
                    {
                        ETGModConsole.Log("<size=100><color=#ff0000ff>BEAM ERROR: colliderDimensions or colliderOffsets was null with no override vertices!</color></size>", false);
                    }
                    else
                    {
                        Vector2 actualDimensions = (Vector2)colliderDimensions;
                        Vector2 actualOffsets    = (Vector2)colliderDimensions;
                        frameDef.colliderVertices = new Vector3[] {
                            new Vector3(actualOffsets.x / 16, actualOffsets.y / 16, 0f),
                            new Vector3(actualDimensions.x / 16, actualDimensions.y / 16, 0f)
                        };
                    }
                }
                frames.Add(new tk2dSpriteAnimationFrame {
                    spriteId = frameSpriteId, spriteCollection = collection
                });
            }
            clip.frames         = frames.ToArray();
            beamAnimation.clips = beamAnimation.clips.Concat(new tk2dSpriteAnimationClip[] { clip }).ToArray();
        }
Ejemplo n.º 37
0
    public static void UpdateAnimations(this Gun gun, tk2dSpriteCollectionData collection = null)
    {
        collection = collection ?? ETGMod.Databases.Items.WeaponCollection;

        gun.idleAnimation            = gun.UpdateAnimation("idle", collection);
        gun.introAnimation           = gun.UpdateAnimation("intro", collection, true);
        gun.emptyAnimation           = gun.UpdateAnimation("empty", collection);
        gun.shootAnimation           = gun.UpdateAnimation("fire", collection, true);
        gun.reloadAnimation          = gun.UpdateAnimation("reload", collection, true);
        gun.chargeAnimation          = gun.UpdateAnimation("charge", collection);
        gun.outOfAmmoAnimation       = gun.UpdateAnimation("out_of_ammo", collection);
        gun.dischargeAnimation       = gun.UpdateAnimation("discharge", collection);
        gun.finalShootAnimation      = gun.UpdateAnimation("final_fire", collection, true);
        gun.emptyReloadAnimation     = gun.UpdateAnimation("empty_reload", collection, true);
        gun.criticalFireAnimation    = gun.UpdateAnimation("critical_fire", collection, true);
        gun.enemyPreFireAnimation    = gun.UpdateAnimation("enemy_pre_fire", collection);
        gun.alternateShootAnimation  = gun.UpdateAnimation("alternate_shoot", collection, true);
        gun.alternateReloadAnimation = gun.UpdateAnimation("alternate_reload", collection, true);
    }
Ejemplo n.º 38
0
    /*
     */
    void OnEnable()
    {
        tk2dSpineSkeletonDataAsset skeletonDataAsset = target as tk2dSpineSkeletonDataAsset;

        if (skeletonDataAsset != null)
        {
            tk2dSpriteCollectionData spritesData = skeletonDataAsset.spritesData;

            if (spritesData != null)
            {
                sprites = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(spritesData.spriteCollectionGUID), typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
            }
        }

        skeletonJSON  = serializedObject.FindProperty("skeletonJSON");
        fromAnimation = serializedObject.FindProperty("fromAnimation");
        toAnimation   = serializedObject.FindProperty("toAnimation");
        duration      = serializedObject.FindProperty("duration");
    }
Ejemplo n.º 39
0
        private List <tk2dSpriteAnimation> GetUsedIns(tk2dSpriteCollectionData cln, List <tk2dSpriteAnimation> anims)
        {
            List <tk2dSpriteAnimation> used = new List <tk2dSpriteAnimation>();

            foreach (tk2dSpriteAnimation anim in anims)
            {
                foreach (tk2dSpriteAnimationClip clip in anim.clips)
                {
                    foreach (tk2dSpriteAnimationFrame frame in clip.frames)
                    {
                        if (frame.spriteCollection.name == cln.name && !used.Contains(anim))
                        {
                            used.Add(anim);
                        }
                    }
                }
            }
            return(used);
        }
Ejemplo n.º 40
0
	static int GetNamedSpriteInNewCollection(tk2dSpriteCollectionData spriteCollection, int spriteId, tk2dSpriteCollectionData newCollection) {
		int newSpriteId = spriteId;
		string oldSpriteName = (spriteCollection == null || spriteCollection.inst == null) ? "" : spriteCollection.inst.spriteDefinitions[spriteId].name;
		int distance = -1;
		for (int i = 0; i < newCollection.inst.spriteDefinitions.Length; ++i) {
			if (newCollection.inst.spriteDefinitions[i].Valid) {
				string newSpriteName = newCollection.inst.spriteDefinitions[i].name;

				int tmpDistance = (newSpriteName == oldSpriteName) ? 0 :
								  Mathf.Abs ( (oldSpriteName.ToLower()).CompareTo(newSpriteName.ToLower ()));

				if (distance == -1 || tmpDistance < distance) {
					distance = tmpDistance;
					newSpriteId = i;
				}
			}
		}
		return newSpriteId;
	}
Ejemplo n.º 41
0
        /// <summary>
        /// Is this a 2dToolkit collection?
        /// </summary>
        /// <returns>Yes or no</returns>
        bool AttemptTk2dCollection()
        {
#if PS2D_TK2D
            tk2dSpriteCollectionIndex[] collectionIndexes = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
            if (collectionIndexes == null || collectionIndexes.Length == 0)
            {
                return(false);
            }

            List <tk2dSpriteCollectionIndex> collections = new List <tk2dSpriteCollectionIndex>(collectionIndexes);

            // look for identical names
            string basename = layout.GetFriendlyDocumentName();
            tk2dSpriteCollectionIndex foundIndex = collections.Find(each => each.name.Equals(basename, System.StringComparison.CurrentCultureIgnoreCase));
            if (foundIndex == null)
            {
                return(false);
            }

            // found it ... load it
            GameObject go = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(foundIndex.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
            if (go == null)
            {
                return(false);
            }

            // grab the data from it
            tk2dSpriteCollectionData spriteCollectionData = go.GetComponent <tk2dSpriteCollectionData>();
            if (spriteCollectionData == null)
            {
                return(false);
            }

            // all good.
            layout.imageSource        = TextureSource.Tk2dSpriteCollection;
            this.spriteCollectionData = spriteCollectionData;

            return(true);
#else
            return(false);
#endif
        }
Ejemplo n.º 42
0
    public static void SetupSprite(this Gun gun, tk2dSpriteCollectionData collection = null, string defaultSprite = null, int fps = 0)
    {
        AmmonomiconController.ForceInstance.EncounterIconCollection.Handle();
        ETGMod.Databases.Items.ProjectileCollection.Handle();
        collection = collection ?? ETGMod.Databases.Items.WeaponCollection;
        collection.Handle();

        if (defaultSprite != null)
        {
            gun.encounterTrackable.journalData.AmmonomiconSprite = defaultSprite;
        }

        gun.UpdateAnimations(collection);
        gun.GetSprite().SetSprite(collection, gun.DefaultSpriteID = collection.GetSpriteIdByName(gun.encounterTrackable.journalData.AmmonomiconSprite));

        if (fps != 0)
        {
            gun.SetAnimationFPS(fps);
        }
    }
    static tk2dSpriteCollectionData GetSpriteCollectionDataAtIndex(int index, tk2dSpriteCollectionData defaultValue)
    {
        if (index >= allSpriteCollections.Count)
        {
            return(defaultValue);
        }
        GameObject go = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(allSpriteCollections[index].spriteCollectionDataGUID), typeof(GameObject)) as GameObject;

        if (go == null)
        {
            return(defaultValue);
        }
        tk2dSpriteCollectionData data = go.GetComponent <tk2dSpriteCollectionData>();

        if (data == null)
        {
            return(defaultValue);
        }
        return(data);
    }
Ejemplo n.º 44
0
        /// <summary>
        /// Reload the collection that changed.
        /// </summary>
        public void ReloadCollection()
        {
            // safety
            if (_spriteCollectionData == null)
            {
                return;
            }

            // grab the sprite collection path
            string collectionPath = AssetDatabase.GUIDToAssetPath(_spriteCollectionData.spriteCollectionGUID);

            // reload the collection
            tk2dSpriteCollection spriteCollectionReload = AssetDatabase.LoadAssetAtPath(collectionPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;

            if (spriteCollectionReload != null)
            {
                // reassign the collection instance
                _spriteCollectionData = spriteCollectionReload.spriteCollection.inst;
            }
        }
Ejemplo n.º 45
0
        public static void AddAnimationToObject(this GameObject target, tk2dSpriteCollectionData spriteCollection, string animationName, List <string> spritePaths, int fps, Vector2 colliderDimensions, Vector2 colliderOffsets, tk2dBaseSprite.Anchor anchor, tk2dSpriteAnimationClip.WrapMode wrapMode, bool isDefaultAnimation = false)
        {
            tk2dSpriteAnimator  animator  = target.GetOrAddComponent <tk2dSpriteAnimator>();
            tk2dSpriteAnimation animation = target.GetOrAddComponent <tk2dSpriteAnimation>();

            animation.clips  = new tk2dSpriteAnimationClip[0];
            animator.Library = animation;

            tk2dSpriteAnimationClip clip = new tk2dSpriteAnimationClip()
            {
                name = animationName, frames = new tk2dSpriteAnimationFrame[0], fps = fps
            };

            List <tk2dSpriteAnimationFrame> frames = new List <tk2dSpriteAnimationFrame>();

            foreach (string path in spritePaths)
            {
                tk2dSpriteCollectionData collection = spriteCollection;
                int frameSpriteId             = SpriteBuilder.AddSpriteToCollection(path, collection);
                tk2dSpriteDefinition frameDef = collection.spriteDefinitions[frameSpriteId];

                frameDef.colliderVertices = new Vector3[] {
                    new Vector3(colliderOffsets.x / 16, colliderOffsets.y / 16, 0f),
                    new Vector3((colliderDimensions.x / 16), (colliderDimensions.y / 16), 0f)
                };

                frameDef.ConstructOffsetsFromAnchor(anchor);
                frames.Add(new tk2dSpriteAnimationFrame {
                    spriteId = frameSpriteId, spriteCollection = collection
                });
            }
            clip.frames     = frames.ToArray();
            clip.wrapMode   = wrapMode;
            animation.clips = animation.clips.Concat(new tk2dSpriteAnimationClip[] { clip }).ToArray();

            if (isDefaultAnimation)
            {
                animator.DefaultClipId     = animation.GetClipIdByName(animationName);
                animator.playAutomatically = true;
            }
        }
Ejemplo n.º 46
0
    public override void EnterState(EActionState eState)
    {
        base.EnterState(eState);

        if (m_bHasInit)
        {
            return;
        }

        if (m_skillLoader == null)
        {
            m_skillLoader = ConfigManager.Instance.GetLoader <SkillLoader>();
        }

        if (m_lstFixedEffectId == null)
        {
            m_lstFixedEffectId = m_skillLoader.GetFixedEffectIdList(m_skillData.Id);
        }

        if (m_lstFixedEffectId != null && m_lstFixedEffectId.Count > 0)
        {
            for (int i = 0; i < m_lstFixedEffectId.Count; i++)
            {
                var fixedEffectLoaderData = ConfigManager.Instance.GetData <FixedEffectLoader, FixedEffectLoader.Data>(m_lstFixedEffectId[i]);

                GameObject m_effectObj = new GameObject("effect_" + m_skillData.ActionName + "_" + fixedEffectLoaderData.Id);
                m_effectObj.transform.parent        = m_tk2DSpriteAnimator.transform.Find("Effect");
                m_effectObj.transform.localPosition = Vector3.zero;
                tk2dSprite m_effectSprite = Common.GetOrAddComponent <tk2dSprite>(m_effectObj);
                tk2dSpriteCollectionData tk2DSpriteCollectionData = tk2dSystem.LoadResourceByName <tk2dSpriteCollectionData>(fixedEffectLoaderData.CollectionName);
                m_effectSprite.SetSprite(tk2DSpriteCollectionData, 0);
                m_effectSprite.SortingLevel = 3;
                m_effectObj.SetActive(false);
                m_lstEffectObj.Add(m_effectObj);
                m_lstEffectSprite.Add(m_effectSprite);
                m_lstStartFramName.Add(int.Parse(fixedEffectLoaderData.StartFrameName));
                m_lstEndFramName.Add(int.Parse(fixedEffectLoaderData.EndFrameName));
            }
        }
        m_bHasInit = true;
    }
Ejemplo n.º 47
0
        private static tk2dSpriteCollectionData GenerateNewSpriteCollection(GameObject targetObject, string CollectionName = null, tk2dSpriteDefinition[] spriteDefinitions = null, bool initDictionary = false)
        {
            tk2dSpriteCollectionData newCollection = targetObject.AddComponent <tk2dSpriteCollectionData>();

            newCollection.version          = 3;
            newCollection.materialIdsValid = true;
            if (spriteDefinitions != null)
            {
                newCollection.spriteDefinitions = spriteDefinitions;
            }
            newCollection.spriteDefinitions  = new tk2dSpriteDefinition[0];
            newCollection.premultipliedAlpha = false;
            newCollection.shouldGenerateTilemapReflectionData = false;
            newCollection.materials            = new Material[0];
            newCollection.textures             = new Texture[0];
            newCollection.pngTextures          = new TextAsset[0];
            newCollection.textureFilterMode    = FilterMode.Point;
            newCollection.textureMipMaps       = false;
            newCollection.allowMultipleAtlases = false;
            newCollection.spriteCollectionGUID = Guid.NewGuid().ToString();
            if (!string.IsNullOrEmpty(CollectionName))
            {
                newCollection.spriteCollectionName = CollectionName;
            }
            else
            {
                newCollection.spriteCollectionName = targetObject.name + "_Collection";
            }
            newCollection.loadable = false;
            newCollection.buildKey = UnityEngine.Random.Range(800000000, 999999999);
            newCollection.dataGuid = Guid.NewGuid().ToString();
            newCollection.managedSpriteCollection       = false;
            newCollection.hasPlatformData               = false;
            newCollection.spriteCollectionPlatforms     = new string[0];
            newCollection.spriteCollectionPlatformGUIDs = new string[0];
            if (initDictionary)
            {
                newCollection.InitDictionary();
            }
            return(newCollection);
        }
Ejemplo n.º 48
0
    private static tk2dSpriteAnimationClip[] CreateAnimationClip(tk2dSpriteCollectionData spriteCollectionData, string name, string action, string[] directionNames, tk2dSpriteAnimationClip.WrapMode wrapMode)
    {
        List <tk2dSpriteDefinition> frames = new List <tk2dSpriteDefinition>();

        foreach (var spriteDefine in spriteCollectionData.spriteDefinitions)
        {
            if (spriteDefine.name.Contains(name + "_" + action.ToLower()))
            {
                frames.Add(spriteDefine);
            }
        }
        frames = frames.OrderBy(o => o.name).ToList();
        var frameCount = frames.Count / directionNames.Length;

        tk2dSpriteAnimationClip[] clips = new tk2dSpriteAnimationClip[directionNames.Length];
        for (int i = 0; i < directionNames.Length; i++)
        {
            var clip = new tk2dSpriteAnimationClip();
            clips[i] = clip;
            clip.fps = 10;
            if (directionNames[i] == "")
            {
                clip.name = name + "_" + action;
            }
            else
            {
                clip.name = name + "_" + action + "_" + directionNames[i];
            }
            clip.frames   = new tk2dSpriteAnimationFrame[frameCount];
            clip.wrapMode = wrapMode;
            for (int j = 0; j < clip.frames.Length; ++j)
            {
                tk2dSpriteAnimationFrame frame = new tk2dSpriteAnimationFrame();
                frame.spriteCollection = spriteCollectionData;
                frame.spriteId         = frame.spriteCollection.GetSpriteIdByName(frames[i * frameCount + j].name);

                clip.frames[j] = frame;
            }
        }
        return(clips);
    }
Ejemplo n.º 49
0
        public SpriteFlatData(string name, Texture2D texture, float width, float height, ScaleType scaleType)
        {
            this.name = name;

            float textureWidth = texture.width;
            float textureHeight = texture.height;
            switch (scaleType) {
                case ScaleType.NONE:
                    this.width = textureWidth;
                    this.height = textureHeight;
                    break;
                case ScaleType.SCALED_WIDTH:
                    this.width = width;
                    this.height = width * textureHeight / textureWidth;
                    break;
                case ScaleType.SCALED_HEIGHT:
                    this.width = height * textureWidth / textureHeight;
                    this.height = height;
                    break;
                case ScaleType.SCALED:
                default:
                    this.width = width;
                    this.height = height;
                    break;
            }
            this.regionWidth = textureWidth;
            this.regionHeight =
                texture.wrapMode == TextureWrapMode.Repeat ?
                this.height * textureWidth / this.width :
                textureHeight
            ;

            Rect region = new Rect(0f, 0f, this.regionWidth, this.regionHeight);
            Vector2 anchor = new Vector2(this.regionWidth / 2, this.regionHeight / 2);

            tk2dRuntime.SpriteCollectionSize size = tk2dRuntime.SpriteCollectionSize.ForTk2dCamera();
            this.data = tk2dRuntime.SpriteCollectionGenerator.CreateFromTexture(texture, size, region, anchor);
            this.data.gameObject.name = String.Format("DataSpriteFlat{0}", name);
        }
Ejemplo n.º 50
0
    public void Build()
    {
        UpgradeData();

        if (spriteCollection != null)
            spriteCollectionInst = spriteCollection.inst;

        if (mesh == null)
        {
            mesh = new Mesh();
            mesh.hideFlags = HideFlags.DontSave;
            GetComponent<MeshFilter>().mesh = mesh;
        }
        else
        {
            // this happens when the sprite rebuilds
            mesh.Clear();
        }

        if (colliderMesh)
        {
        #if UNITY_EDITOR
            DestroyImmediate(colliderMesh);
        #else
            Destroy(colliderMesh);
        #endif
            colliderMesh = null;
        }

        if (!spriteCollectionInst || batchedSprites == null || batchedSprites.Length == 0)
        {
        }
        else
        {
            SortBatchedSprites();
            BuildRenderMesh();
            BuildPhysicsMesh();
        }
    }
 private void DoDemoTexturePacker(tk2dSpriteCollectionSize spriteCollectionSize)
 {
     if (GUILayout.Button("Import", new GUILayoutOption[0]))
     {
         this.DestroyData();
         this.spriteCollectionInstance = tk2dSpriteCollectionData.CreateFromTexturePacker(spriteCollectionSize, this.texturePackerExportFile.text, this.texturePackerTexture);
         GameObject obj2 = new GameObject("sprite");
         obj2.transform.localPosition = new Vector3(-1f, 0f, 0f);
         this.spriteInstance = obj2.AddComponent<tk2dSprite>();
         this.spriteInstance.SetSprite(this.spriteCollectionInstance, "sun");
         obj2 = new GameObject("sprite2");
         obj2.transform.parent = this.spriteInstance.transform;
         obj2.transform.localPosition = new Vector3(2f, 0f, 0f);
         obj2.AddComponent<tk2dSprite>().SetSprite(this.spriteCollectionInstance, "2dtoolkit_logo");
         obj2 = new GameObject("sprite3");
         obj2.transform.parent = this.spriteInstance.transform;
         obj2.transform.localPosition = new Vector3(1f, 1f, 0f);
         obj2.AddComponent<tk2dSprite>().SetSprite(this.spriteCollectionInstance, "button_up");
         obj2 = new GameObject("sprite4");
         obj2.transform.parent = this.spriteInstance.transform;
         obj2.transform.localPosition = new Vector3(1f, -1f, 0f);
         obj2.AddComponent<tk2dSprite>().SetSprite(this.spriteCollectionInstance, "Rock");
     }
 }
Ejemplo n.º 52
0
	/// <summary>
	/// Adds a tk2dSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry.
	/// Convenience alias of tk2dBaseSprite.AddComponent<tk2dSprite>(...).
	/// </summary>
	public static tk2dSprite AddComponent(GameObject go, tk2dSpriteCollectionData spriteCollection, string spriteName)
	{
		return tk2dBaseSprite.AddComponent<tk2dSprite>(go, spriteCollection, spriteName);
	}
		void AttachPointSpriteHandler(tk2dSpriteCollectionData newSpriteCollection, int newSpriteId, object callbackData) {
			string attachPointName = (string)callbackData;
			tk2dSpriteCollection.AttachPointTestSprite proxy = null;
			if (SpriteCollection.attachPointTestSprites.TryGetValue(attachPointName, out proxy)) {
				proxy.spriteCollection = newSpriteCollection;
				proxy.spriteId = newSpriteId;
				HandleUtility.Repaint();
			}
		}
Ejemplo n.º 54
0
	// tk2dRuntime.ISpriteCollectionEditor
	public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
	{
		if (data.font != null && data.font.spriteCollection != null)
			return data.font.spriteCollection == spriteCollection;
		
		// No easy way to identify this at this stage
		return true;
	}
Ejemplo n.º 55
0
 // tk2dRuntime.ISpriteCollectionEditor
 public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
 {
     // No easy way to identify this at this stage
     return true;
 }
	// Sanitize data, returns true if needs rebuild
	bool UpgradeData()
	{
		if (version == CURRENT_VERSION) {
			return false;
		}
		
		if (_scale == Vector3.zero) {
			_scale = Vector3.one;
		}
		
		if (version < 2)
		{
			if (batchedSprites != null)
			{
				// Parented to this object
				foreach (var sprite in batchedSprites)
					sprite.parentId = -1;
			}
		}

		if (version < 3)
		{
			if (batchedSprites != null)
			{
				foreach (var sprite in batchedSprites)
				{
					if (sprite.spriteId == -1)
					{
						sprite.type = tk2dBatchedSprite.Type.EmptyGameObject;
					}
					else {
						sprite.type = tk2dBatchedSprite.Type.Sprite;
						if (sprite.spriteCollection == null) { 
							sprite.spriteCollection = spriteCollection;
						}
					}
				}

				UpdateMatrices();
			}

			spriteCollection = null;
		}
		
		version = CURRENT_VERSION;

#if UNITY_EDITOR
		UnityEditor.EditorUtility.SetDirty(this);
#endif
		
		return true;
	}
	public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection)
	{
		return this.spriteCollection == spriteCollection;	
	}
Ejemplo n.º 58
0
	void DestroyInternal() {
		if (spriteCollection != null) {
			if (spriteCollection.spriteDefinitions[0].material != null) {
				DestroyImmediate( spriteCollection.spriteDefinitions[0].material );
			}
			DestroyImmediate( spriteCollection.gameObject );
			spriteCollection = null;
		}
	}
Ejemplo n.º 59
0
 // Callback and delegate
 void SpriteChangedCallbackImpl(tk2dSpriteCollectionData spriteCollection, int spriteId, object data)
 {
     tk2dBaseSprite s = target as tk2dBaseSprite;
     if (s != null)
     {
         s.SwitchCollectionAndSprite(spriteCollection, spriteId);
         s.EditMode__CreateCollider();
         EditorUtility.SetDirty(target);
     }
 }
Ejemplo n.º 60
0
    // Prefab build, 单次build缓存
    public static string BuildSpriteCollection(tk2dSpriteCollectionData data)
    {
        if (data == null)
        {
            Log.Error("[BuildSpriteColleccion]Null SpriteCol Data!!!");
            return "";
        }
        GameObject spriteColPrefab = PrefabUtility.FindPrefabRoot(data.gameObject) as GameObject;
        Log.Assert(spriteColPrefab);

        string path = AssetDatabase.GetAssetPath(spriteColPrefab);  // prefab只用来获取路径,不打包不挖空
        if (string.IsNullOrEmpty(path))
        {
            Log.Info("Null Sprite Collection {0}", path);
            return "";   // !!! SpriteCollection可能动态生成的,不打包它
        }
        bool needBuild = BuildTools.CheckNeedBuild(path);
        if (needBuild)
            BuildTools.MarkBuildVersion(path);

        path = __GetPrefabBuildPath(path);

        GameObject copySpriteColObj = GameObject.Instantiate(spriteColPrefab) as GameObject;
        tk2dSpriteCollectionData spriteColData = copySpriteColObj.GetComponent<tk2dSpriteCollectionData>();

        foreach (Material mat in spriteColData.materials) // many materials
        {
            string matPath = BuildDepMaterial(mat, GameDef.PictureScale);
            if (!string.IsNullOrEmpty(matPath))  // 材质可能动态创建的,无需打包
                //CResourceDependencies.Create(spriteColData, CResourceDependencyType.SPRITE_COLLECTION, matPath);
                KAssetDep.Create<CTk2dSpriteCollectionDep>(spriteColData, matPath);
        }

        spriteColData.materials = new Material[0]; // 挖空spriteCollections
        spriteColData.textures = new Texture[0];
        foreach (var def in spriteColData.spriteDefinitions)
        {
            def.material = null;
            // 进行缩放!
            //if (def.positions != null)
            //{
            //    // position!  size!
            //    for (var ip = 0; ip < def.positions.Length; ip++)
            //    {
            //        def.positions[ip] = def.positions[ip] / GameDef.PictureScale;
            //    }
            //    for (var ip = 0; ip < def.untrimmedBoundsData.Length; ip++)
            //    {
            //        def.untrimmedBoundsData[ip] = def.untrimmedBoundsData[ip] / GameDef.PictureScale;
            //    }
            //    for (var ip = 0; ip < def.boundsData.Length; ip++)
            //    {
            //        def.boundsData[ip] = def.boundsData[ip] / GameDef.PictureScale;
            //    }
            //}
        }

        var result = DoBuildAssetBundle(DepBuildToFolder + "/Col_" + path, copySpriteColObj, needBuild);  // Build主对象, 被挖空Material了的

        GameObject.DestroyImmediate(copySpriteColObj);

        return result.Path;
    }