/// By Matt Davis @mattdavisgames
/// Requires "SDF Toolkit Free" (or paid) by Catlike Coding (Jasper Flick)
/// Render using TextMeshPro/Distance Field SSD shader (res 512, gradient scale 52.2) (gradient scale = res * paddingRatio + 1)
///
/// Original image must include a margin of ~10% (or paddingRatio) of the image resolution, to accomodate SDF gradient.

using UnityEditor;
using UnityEngine;
using CatlikeCoding.SDFToolkit;

public class SdfPostProcessor : AssetPostprocessor {
    // Run after the default post processor. (especially after xBRZ)
    public override int GetPostprocessOrder() {
        return 10;
    }

    // After the texture is imported.
    // This occurs after "max size" is applied, meaning the process is "downscale -> convert to sdf" rather than "convert to sdf -> downscale".
    // Not sure whether this makes a significant difference.
    public void OnPostprocessTexture(Texture2D texture) {
        // Import texture as sdf
        var toLower = assetPath.ToLower();
        if (toLower.Contains("_tosdf")) {
            var newResString = toLower.Split("_tosdf")[1].Split(new char[] { '.', '_' })[0];
            var resize = int.TryParse(newResString, out var newRes);

            var paddingRatio = 0.1f;
            // Check the path for a "padding" value
            if (toLower.Contains("_padding")) {
                // There must be an underscore after padding value (to differentiate decimal point from file extension)
                var paddingString = toLower.Split("_padding")[1].Split(new char[] { '_' })[0];
                if (float.TryParse(paddingString, out var paddingArg)) {
                    paddingRatio = paddingArg;
                }
            }

            var dest = new Texture2D(texture.width, texture.height, texture.format, false);
            // TMP padding value is GradientScale - 1
            // Catlike Coding SDF generator padding value is TMPpadding + 0.5.
            var padding = ((texture.width + texture.height) * 0.5f) * paddingRatio - 1f + 0.5f;
            SDFTextureGenerator.Generate(texture, dest, padding, padding, 0, RGBFillMode.Source);
            texture.SetPixels(dest.GetPixels(0), 0);
            texture.Apply();

            if (resize) {
                // Maintain aspect ratio of texture. Use newRes as the longer dimension.
                var denominator = Mathf.Max(texture.width, texture.height);
                ResizeTool.Resize(texture, (texture.width * newRes) / denominator, (texture.height * newRes) / denominator, texture.mipmapCount > 1, FilterMode.Bilinear);
            }
        }
    }
}