private List <AnimationClip> GenerateAnimations(AseFile aseFile, List <Sprite> sprites)
        {
            List <AnimationClip> res = new List <AnimationClip>();
            var animations           = aseFile.GetAnimations();

            if (animations.Length <= 0)
            {
                return(res);
            }

            var metadatas = aseFile.GetMetaData(Settings.spritePivot, Settings.pixelsPerUnit);

            int index = 0;

            foreach (var animation in animations)
            {
                var           path = directoryName + "/" + fileName + "_" + animation.TagName + ".anim";
                AnimationClip clip = AssetDatabase.LoadAssetAtPath <AnimationClip>(path);
                if (clip == null)
                {
                    clip = new AnimationClip();
                    AssetDatabase.CreateAsset(clip, path);
                    clip.wrapMode = GetDefaultWrapMode(animation.TagName);
                }
                else
                {
                    AnimationClipSettings animSettings = AnimationUtility.GetAnimationClipSettings(clip);
                    clip.wrapMode = animSettings.loopTime ? WrapMode.Loop : WrapMode.Once;
                }

                clip.name      = fileName + "_" + animation.TagName;
                clip.frameRate = 25;

                EditorCurveBinding editorBinding = new EditorCurveBinding();
                editorBinding.path         = "";
                editorBinding.propertyName = "m_Sprite";

                switch (Settings.bindType)
                {
                case AseAnimationBindType.SpriteRenderer:
                    editorBinding.type = typeof(SpriteRenderer);
                    break;

                case AseAnimationBindType.UIImage:
                    editorBinding.type = typeof(Image);
                    break;
                }

                // plus last frame to keep the duration
                int length = animation.FrameTo - animation.FrameFrom + 1;
                ObjectReferenceKeyframe[]           spriteKeyFrames = new ObjectReferenceKeyframe[length + 1];
                Dictionary <string, AnimationCurve> transformCurveX = new Dictionary <string, AnimationCurve>(),
                                                    transformCurveY = new Dictionary <string, AnimationCurve>();

                float time = 0;
                int   from = (animation.Animation != LoopAnimation.Reverse) ? animation.FrameFrom : animation.FrameTo;
                int   step = (animation.Animation != LoopAnimation.Reverse) ? 1 : -1;

                int keyIndex = from;
                for (int i = 0; i < length; i++)
                {
                    if (i >= length)
                    {
                        keyIndex = from;
                    }

                    ObjectReferenceKeyframe frame = new ObjectReferenceKeyframe();
                    frame.time  = time;
                    frame.value = sprites[keyIndex];

                    time += aseFile.Frames[keyIndex].FrameDuration / 1000f;
                    spriteKeyFrames[i] = frame;

                    foreach (var metadata in metadatas)
                    {
                        if (metadata.Type == MetaDataType.TRANSFORM && metadata.Transforms.ContainsKey(keyIndex))
                        {
                            var childTransform = metadata.Args[0];
                            if (!transformCurveX.ContainsKey(childTransform))
                            {
                                transformCurveX[childTransform] = new AnimationCurve();
                                transformCurveY[childTransform] = new AnimationCurve();
                            }
                            var pos = metadata.Transforms[keyIndex];
                            transformCurveX[childTransform].AddKey(i, pos.x);
                            transformCurveY[childTransform].AddKey(i, pos.y);
                        }
                    }

                    keyIndex += step;
                }

                float frameTime = 1f / clip.frameRate;
                ObjectReferenceKeyframe lastFrame = new ObjectReferenceKeyframe();
                lastFrame.time  = time - frameTime;
                lastFrame.value = sprites[keyIndex - step];

                spriteKeyFrames[spriteKeyFrames.Length - 1] = lastFrame;
                foreach (var metadata in metadatas)
                {
                    if (metadata.Type == MetaDataType.TRANSFORM && metadata.Transforms.ContainsKey(keyIndex - step))
                    {
                        var childTransform = metadata.Args[0];
                        var pos            = metadata.Transforms[keyIndex - step];
                        transformCurveX[childTransform].AddKey(spriteKeyFrames.Length - 1, pos.x);
                        transformCurveY[childTransform].AddKey(spriteKeyFrames.Length - 1, pos.y);
                    }
                }

                AnimationUtility.SetObjectReferenceCurve(clip, editorBinding, spriteKeyFrames);
                foreach (var childTransform in transformCurveX.Keys)
                {
                    EditorCurveBinding
                             bindingX = new EditorCurveBinding {
                        path         = childTransform,
                        type         = typeof(Transform),
                        propertyName = "m_LocalPosition.x"
                    },
                             bindingY = new EditorCurveBinding {
                        path         = childTransform,
                        type         = typeof(Transform),
                        propertyName = "m_LocalPosition.y"
                    };
                    MakeConstant(transformCurveX[childTransform]);
                    AnimationUtility.SetEditorCurve(clip, bindingX, transformCurveX[childTransform]);
                    MakeConstant(transformCurveY[childTransform]);
                    AnimationUtility.SetEditorCurve(clip, bindingY, transformCurveY[childTransform]);
                }

                AnimationClipSettings clipSettings = AnimationUtility.GetAnimationClipSettings(clip);
                clipSettings.loopTime = (clip.wrapMode == WrapMode.Loop);

                AnimationUtility.SetAnimationClipSettings(clip, clipSettings);
                EditorUtility.SetDirty(clip);
                index++;
                res.Add(clip);
            }

            return(res);
        }
Exemple #2
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            name = GetFileName(ctx.assetPath);

            AseFile aseFile    = ReadAseFile(ctx.assetPath);
            int     frameCount = aseFile.Header.Frames;

            SpriteAtlasBuilder atlasBuilder = new SpriteAtlasBuilder(textureSettings, aseFile.Header.Width, aseFile.Header.Height);

            Texture2D[] frames = null;
            if (importType != AseFileImportType.LayerToSprite)
            {
                frames = aseFile.GetFrames(textureSettings.ignoreBackground);
            }
            else
            {
                frames = aseFile.GetLayersAsFrames();
            }

            SpriteImportData[] spriteImportData;

            //if (textureSettings.transparentMask)
            //{
            //    atlas = atlasBuilder.GenerateAtlas(frames, out spriteImportData, textureSettings.transparentColor, false);
            //}
            //else
            //{
            //    atlas = atlasBuilder.GenerateAtlas(frames, out spriteImportData, false);

            //}

            atlas = atlasBuilder.GenerateAtlas(frames, name, out spriteImportData, textureSettings.transparencyMode, false);

            atlas.filterMode          = textureSettings.filterMode;
            atlas.alphaIsTransparency = textureSettings.transparencyMode == TransparencyMode.Alpha;
            atlas.wrapMode            = textureSettings.wrapMode;
            atlas.name = "Texture";

            MetaData[] metadatas = aseFile.GetMetaData(textureSettings.spritePivot, textureSettings.pixelsPerUnit);

            List <SecondarySpriteTexture> secondarySpriteTextures = new List <SecondarySpriteTexture>();

            // Find any metadata with a secondary texture
            foreach (var metadata in metadatas)
            {
                if (metadata.Type == MetaDataType.SECONDARY_TEXTURE)
                {
                    var textureName = metadata.Args[0];

                    var       secondaryTextureFrames = aseFile.GetLayerTexture(metadata.LayerIndex, metadata.Layer);
                    Texture2D secondaryTexture       = atlasBuilder.GenerateAtlas(secondaryTextureFrames.ToArray(), name, out _,
                                                                                  textureSettings.transparencyMode, false);

                    secondaryTexture.alphaIsTransparency = textureSettings.transparencyMode == TransparencyMode.Alpha;;
                    secondaryTexture.wrapMode            = textureSettings.wrapMode;
                    secondaryTexture.filterMode          = textureSettings.filterMode;
                    secondaryTexture.name = textureName;

                    secondarySpriteTextures.Add(new SecondarySpriteTexture()
                    {
                        name = textureName, texture = secondaryTexture
                    });
                }
            }

            TextureGenerationSettings generationSettings = new TextureGenerationSettings();

            generationSettings.platformSettings = new TextureImporterPlatformSettings();

            generationSettings.spriteImportData         = spriteImportData;
            generationSettings.secondarySpriteTextures  = secondarySpriteTextures.ToArray();
            generationSettings.sourceTextureInformation = new SourceTextureInformation()
            {
                width         = atlas.width,
                height        = atlas.height,
                containsAlpha = true,
            };

            generationSettings.textureImporterSettings = new TextureImporterSettings
            {
                textureType         = TextureImporterType.Sprite,
                textureShape        = TextureImporterShape.Texture2D,
                alphaIsTransparency = textureSettings.transparencyMode == TransparencyMode.Alpha,
                alphaSource         = TextureImporterAlphaSource.FromInput,
                spritePixelsPerUnit = textureSettings.pixelsPerUnit,
                spritePivot         = textureSettings.spritePivot,
                spriteMeshType      = SpriteMeshType.Tight,
                convertToNormalMap  = false,
                mipmapEnabled       = false,
                sRGBTexture         = true,
                readable            = false,
                fadeOut             = false,
                wrapMode            = TextureWrapMode.Clamp,
                wrapModeU           = TextureWrapMode.Clamp,
                wrapModeV           = TextureWrapMode.Clamp,
                wrapModeW           = TextureWrapMode.Clamp
            };

            var imageBuffer     = atlas.GetRawTextureData <Color32>();
            var generatedOutput = TextureGenerator.GenerateTexture(generationSettings, imageBuffer);

            generatedOutput.texture.name = "Texture";

            // Main texture atlas
            ctx.AddObjectToAsset("Texture", generatedOutput.texture);
            ctx.SetMainObject(generatedOutput.texture);

            // Add secondary textures
            foreach (var secondarySpriteTexture in secondarySpriteTextures)
            {
                ctx.AddObjectToAsset("SecondaryTex_" + secondarySpriteTexture.name, secondarySpriteTexture.texture);
            }

            // Add sprites
            foreach (var sprite in generatedOutput.sprites)
            {
                ctx.AddObjectToAsset(sprite.name, sprite);
            }

            // Add animations
            if (importType == AseFileImportType.Sprite)
            {
                GenerateAnimations(ctx, aseFile, generatedOutput.sprites, metadatas);
            }

            switch (importType)
            {
            case AseFileImportType.LayerToSprite:
            case AseFileImportType.Sprite:
                // ImportSprites(ctx, aseFile, spriteImportData, metadatas);
                break;

            case AseFileImportType.Tileset:
                ImportTileset(ctx, atlas);
                break;
            }
        }