// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    [Serializable]
    internal sealed class WPFMAThumbnailLayer
    {
        public int kind;
        public bool visible = true;
        public bool expanded = true;

        public string text = "My Avatar";
        public string fontGuid = string.Empty;
        public int fontSize = 110;
        public bool bold = true;
        public bool italic;
        public int align = 1;
        public bool outline = true;
        public Color outlineColor = new Color(0f, 0f, 0f, 1f);
        public float outlineSize = 6f;
        public bool shadow = true;
        public Color shadowColor = new Color(0f, 0f, 0f, 0.6f);
        public Vector2 shadowOffset = new Vector2(6f, 6f);
        public float shadowSoftness = 6f;
        public bool glow;
        public Color glowColor = new Color(0.5f, 0.75f, 1f, 1f);
        public float glowSize = 18f;

        public Color color = Color.white;
        public Vector2 position = new Vector2(0.5f, 0.15f);
        public float rotation;
        public float opacity = 1f;

        public string imageGuid = string.Empty;
        public float scale = 0.3f;
        public Vector2 size = new Vector2(0.6f, 0.14f);

        public string Title
        {
            get
            {
                switch (kind)
                {
                    case 0: return "Text: " + (string.IsNullOrEmpty(text) ? "(empty)" : text.Replace("\n", " "));
                    case 1: return "Image";
                    case 2: return "Box";
                    default: return "Circle";
                }
            }
        }
    }

    [Serializable]
    internal sealed class WPFMAThumbnailSettings
    {
        public int width = 1200;
        public int height = 900;

        public int source;
        public bool sceneGrabbed;
        public Vector3 scenePosition;
        public Quaternion sceneRotation = Quaternion.identity;
        public float sceneFov = 60f;

        public int framing = 1;
        public float yaw;
        public float pitch = 5f;
        public float zoom = 1f;
        public float lift;
        public float side;
        public float fov = 30f;

        public float keyIntensity = 1.1f;
        public float keyYaw = -35f;
        public float keyPitch = 35f;
        public Color keyColor = Color.white;
        public bool rim = true;
        public float rimIntensity = 0.8f;
        public Color rimColor = new Color(0.65f, 0.8f, 1f, 1f);
        public float ambient = 0.55f;
        public Color ambientColor = Color.white;

        public int background = 1;
        public Color backgroundColor = new Color(0.07f, 0.08f, 0.1f, 1f);
        public Color gradientTop = new Color(0.16f, 0.35f, 0.52f, 1f);
        public Color gradientBottom = new Color(0.04f, 0.05f, 0.08f, 1f);
        public float gradientAngle;
        public string backgroundImageGuid = string.Empty;

        public bool glow = true;
        public Color glowColor = new Color(0.49f, 0.71f, 0.87f, 1f);
        public float glowSize = 28f;
        public float glowStrength = 0.9f;
        public bool outline;
        public Color outlineColor = Color.white;
        public float outlineSize = 5f;
        public bool shadow = true;
        public Color shadowColor = new Color(0f, 0f, 0f, 0.55f);
        public Vector2 shadowOffset = new Vector2(18f, 14f);
        public float shadowSoftness = 16f;

        public float brightness;
        public float contrast = 0.05f;
        public float saturation = 0.1f;
        public Color tint = Color.white;
        public float tintAmount;
        public float vignette = 0.35f;
        public float grain;
        public float chromatic;
        public float scanlines;

        public List<WPFMAThumbnailLayer> layers = new List<WPFMAThumbnailLayer>();
    }

    internal static class WPFMAThumbnailRenderer
    {
        internal static void GrabSceneView(WPFMAThumbnailSettings s)
        {
            var view = SceneView.lastActiveSceneView;
            if (view == null || view.camera == null)
                return;

            s.scenePosition = view.camera.transform.position;
            s.sceneRotation = view.camera.transform.rotation;
            s.sceneFov = Mathf.Clamp(view.camera.fieldOfView, 10f, 100f);
            s.sceneGrabbed = true;
        }

        private static Color[] RenderScene(WPFMAThumbnailSettings s, int w, int h)
        {
            if (!s.sceneGrabbed)
                GrabSceneView(s);

            var hidden = new List<GameObject>();
            foreach (var go in UnityEngine.Object.FindObjectsOfType<GameObject>())
            {
                if (go.activeSelf && go.CompareTag("EditorOnly") && go.scene.IsValid())
                {
                    go.SetActive(false);
                    hidden.Add(go);
                }
            }

            var rig = new GameObject("WPFMA Thumbnail Scene Camera") { hideFlags = HideFlags.HideAndDontSave };
            RenderTexture msaa = null, resolved = null;
            try
            {
                var camera = rig.AddComponent<Camera>();
                camera.enabled = false;
                camera.clearFlags = CameraClearFlags.Skybox;
                camera.allowHDR = false;
                camera.allowMSAA = true;
                camera.nearClipPlane = 0.05f;
                camera.farClipPlane = 2000f;
                camera.fieldOfView = s.sceneFov;
                camera.aspect = w / (float)h;
                rig.transform.position = s.scenePosition;
                rig.transform.rotation = s.sceneRotation;

                msaa = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4 };
                resolved = new RenderTexture(w, h, 0, RenderTextureFormat.ARGB32);
                camera.targetTexture = msaa;
                camera.Render();
                camera.targetTexture = null;

                var pixels = Read(msaa, resolved, w, h);
                for (int i = 0; i < pixels.Length; i++)
                    pixels[i].a = 1f;
                return pixels;
            }
            finally
            {
                foreach (var go in hidden)
                    if (go != null)
                        go.SetActive(true);

                UnityEngine.Object.DestroyImmediate(rig);
                if (msaa != null)
                {
                    msaa.Release();
                    UnityEngine.Object.DestroyImmediate(msaa);
                }
                if (resolved != null)
                {
                    resolved.Release();
                    UnityEngine.Object.DestroyImmediate(resolved);
                }
            }
        }

        internal static Color[] Render(GameObject avatar, WPFMAThumbnailSettings s, int w, int h, float scale)
        {
            if (s.source == 1)
            {
                var scene = RenderScene(s, w, h);
                Grade(scene, s, w, h, scale);
                foreach (var layer in s.layers)
                {
                    if (!layer.visible)
                        continue;
                    try
                    {
                        DrawLayer(scene, layer, w, h, scale);
                    }
                    catch (Exception e)
                    {
                        Debug.LogWarning("[WPFMA-SDK] Thumbnail layer '" + layer.Title + "' failed: " + e.Message);
                    }
                }
                return scene;
            }

            Color[] avatarColor = null;
            float[] alpha = null;

            if (avatar != null)
                RenderAvatar(avatar, s, w, h, out avatarColor, out alpha);

            var image = Background(s, w, h);

            if (alpha != null)
            {
                if (s.shadow)
                {
                    var shadow = Blur(Shift(alpha, w, h, s.shadowOffset.x * scale, -s.shadowOffset.y * scale), w, h, Mathf.RoundToInt(s.shadowSoftness * scale));
                    Over(image, shadow, s.shadowColor);
                }

                if (s.glow)
                {
                    var glow = Blur(alpha, w, h, Mathf.Max(1, Mathf.RoundToInt(s.glowSize * scale)));
                    for (int i = 0; i < glow.Length; i++)
                        glow[i] = Mathf.Clamp01(glow[i] * 2f * s.glowStrength);
                    Over(image, glow, s.glowColor);
                }

                if (s.outline)
                    Over(image, Dilate(alpha, w, h, Mathf.Max(1, Mathf.RoundToInt(s.outlineSize * scale))), s.outlineColor);

                for (int i = 0; i < image.Length; i++)
                {
                    float a = alpha[i];
                    if (a <= 0f)
                        continue;

                    var c = avatarColor[i];
                    var bg = image[i];
                    image[i] = new Color(c.r * a + bg.r * (1f - a), c.g * a + bg.g * (1f - a), c.b * a + bg.b * (1f - a),
                        a + bg.a * (1f - a));
                }
            }

            Grade(image, s, w, h, scale);

            foreach (var layer in s.layers)
            {
                if (!layer.visible)
                    continue;

                try
                {
                    DrawLayer(image, layer, w, h, scale);
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[WPFMA-SDK] Thumbnail layer '" + layer.Title + "' failed: " + e.Message);
                }
            }

            return image;
        }

        private static void RenderAvatar(GameObject avatar, WPFMAThumbnailSettings s, int w, int h, out Color[] color, out float[] alpha)
        {
            int layer = FreeLayer();
            var transforms = avatar.GetComponentsInChildren<Transform>(true);
            var oldLayers = transforms.Select(t => t.gameObject.layer).ToArray();

            var ambientMode = RenderSettings.ambientMode;
            var ambientLight = RenderSettings.ambientLight;

            var rig = new GameObject("WPFMA Thumbnail Rig") { hideFlags = HideFlags.HideAndDontSave };
            RenderTexture msaa = null, resolved = null;

            try
            {
                foreach (var t in transforms)
                    t.gameObject.layer = layer;

                var camera = rig.AddComponent<Camera>();
                camera.enabled = false;
                camera.cullingMask = 1 << layer;
                camera.clearFlags = CameraClearFlags.SolidColor;
                camera.allowHDR = false;
                camera.allowMSAA = true;
                camera.nearClipPlane = 0.01f;
                camera.farClipPlane = 200f;
                camera.fieldOfView = s.fov;
                camera.aspect = w / (float)h;

                Frame(camera.transform, avatar, s);

                var key = AddLight(rig, layer, s.keyColor, s.keyIntensity,
                    Quaternion.Euler(s.keyPitch, s.keyYaw, 0f) * Quaternion.LookRotation(-avatar.transform.forward));
                if (s.rim)
                    AddLight(rig, layer, s.rimColor, s.rimIntensity,
                        Quaternion.Euler(15f, 180f + s.keyYaw * -0.5f, 0f) * Quaternion.LookRotation(-avatar.transform.forward));
                key.shadows = LightShadows.Soft;

                RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat;
                RenderSettings.ambientLight = s.ambientColor * s.ambient;

                msaa = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32) { antiAliasing = 4 };
                resolved = new RenderTexture(w, h, 0, RenderTextureFormat.ARGB32);
                camera.targetTexture = msaa;

                camera.backgroundColor = new Color(0f, 0f, 0f, 0f);
                camera.Render();
                var black = Read(msaa, resolved, w, h);

                camera.backgroundColor = new Color(1f, 1f, 1f, 0f);
                camera.Render();
                var white = Read(msaa, resolved, w, h);

                camera.targetTexture = null;

                color = new Color[w * h];
                alpha = new float[w * h];
                for (int i = 0; i < color.Length; i++)
                {
                    var b = black[i];
                    var wh = white[i];
                    float a = 1f - ((wh.r - b.r) + (wh.g - b.g) + (wh.b - b.b)) / 3f;
                    a = Mathf.Clamp01(a);
                    alpha[i] = a;
                    color[i] = a > 0.002f ? new Color(Mathf.Clamp01(b.r / a), Mathf.Clamp01(b.g / a), Mathf.Clamp01(b.b / a), 1f) : Color.clear;
                }
            }
            finally
            {
                for (int i = 0; i < transforms.Length; i++)
                {
                    if (transforms[i] != null)
                        transforms[i].gameObject.layer = oldLayers[i];
                }

                RenderSettings.ambientMode = ambientMode;
                RenderSettings.ambientLight = ambientLight;

                UnityEngine.Object.DestroyImmediate(rig);
                if (msaa != null)
                {
                    msaa.Release();
                    UnityEngine.Object.DestroyImmediate(msaa);
                }
                if (resolved != null)
                {
                    resolved.Release();
                    UnityEngine.Object.DestroyImmediate(resolved);
                }
            }
        }

        private static Light AddLight(GameObject rig, int layer, Color color, float intensity, Quaternion rotation)
        {
            var holder = new GameObject("Light") { hideFlags = HideFlags.HideAndDontSave };
            holder.transform.SetParent(rig.transform, false);
            holder.transform.rotation = rotation;
            var light = holder.AddComponent<Light>();
            light.type = LightType.Directional;
            light.color = color;
            light.intensity = intensity;
            light.cullingMask = 1 << layer;
            return light;
        }

        private static void Frame(Transform camera, GameObject avatar, WPFMAThumbnailSettings s)
        {
            var renderers = avatar.GetComponentsInChildren<Renderer>(false).Where(r => r.enabled && !(r is ParticleSystemRenderer)).ToList();
            var bounds = renderers.Count > 0 ? renderers[0].bounds : new Bounds(avatar.transform.position + Vector3.up, Vector3.one);
            foreach (var renderer in renderers.Skip(1))
                bounds.Encapsulate(renderer.bounds);

            float height = Mathf.Max(0.1f, bounds.size.y);
            var animator = avatar.GetComponent<Animator>();
            var head = animator != null && animator.isHuman ? animator.GetBoneTransform(HumanBodyBones.Head) : null;

            Vector3 target;
            float span;
            switch (s.framing)
            {
                case 0:
                    target = head != null ? head.position + Vector3.up * height * 0.04f : new Vector3(bounds.center.x, bounds.min.y + height * 0.9f, bounds.center.z);
                    span = height * 0.3f;
                    break;
                case 2:
                    target = bounds.center;
                    span = height * 1.1f;
                    break;
                default:
                    target = new Vector3(bounds.center.x, bounds.min.y + height * 0.72f, bounds.center.z);
                    span = height * 0.62f;
                    break;
            }

            target += Vector3.up * s.lift * height;
            float distance = span * 0.5f / Mathf.Tan(s.fov * 0.5f * Mathf.Deg2Rad) / Mathf.Max(0.1f, s.zoom);

            var forward = avatar.transform.forward;
            forward.y = 0f;
            if (forward.sqrMagnitude < 0.001f)
                forward = Vector3.forward;
            forward.Normalize();

            var orbit = Quaternion.AngleAxis(s.yaw, Vector3.up) * Quaternion.AngleAxis(-s.pitch, Vector3.Cross(Vector3.up, forward)) * forward;
            var right = Vector3.Cross(Vector3.up, orbit).normalized;

            camera.position = target + orbit * distance + right * s.side * height;
            camera.rotation = Quaternion.LookRotation(target + right * s.side * height - camera.position, Vector3.up);
        }

        private static int FreeLayer()
        {
            for (int i = 31; i >= 8; i--)
            {
                if (string.IsNullOrEmpty(LayerMask.LayerToName(i)))
                    return i;
            }

            return 31;
        }

        private static Color[] Read(RenderTexture source, RenderTexture resolved, int w, int h)
        {
            Graphics.Blit(source, resolved);
            var previous = RenderTexture.active;
            RenderTexture.active = resolved;
            var texture = new Texture2D(w, h, TextureFormat.RGBA32, false);
            texture.ReadPixels(new Rect(0, 0, w, h), 0, 0);
            texture.Apply();
            RenderTexture.active = previous;
            var pixels = texture.GetPixels();
            UnityEngine.Object.DestroyImmediate(texture);
            return pixels;
        }

        internal static Color[] Readable(Texture texture, int w, int h)
        {
            var rt = RenderTexture.GetTemporary(w, h, 0, RenderTextureFormat.ARGB32);
            Graphics.Blit(texture, rt);
            var previous = RenderTexture.active;
            RenderTexture.active = rt;
            var copy = new Texture2D(w, h, TextureFormat.RGBA32, false);
            copy.ReadPixels(new Rect(0, 0, w, h), 0, 0);
            copy.Apply();
            RenderTexture.active = previous;
            RenderTexture.ReleaseTemporary(rt);
            var pixels = copy.GetPixels();
            UnityEngine.Object.DestroyImmediate(copy);
            return pixels;
        }

        private static Color[] Background(WPFMAThumbnailSettings s, int w, int h)
        {
            var image = new Color[w * h];

            if (s.background == 0)
            {
                for (int i = 0; i < image.Length; i++)
                    image[i] = s.backgroundColor;
            }
            else if (s.background == 1)
            {
                float angle = s.gradientAngle * Mathf.Deg2Rad;
                var direction = new Vector2(Mathf.Sin(angle), Mathf.Cos(angle));
                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {
                        var uv = new Vector2(x / (float)(w - 1) - 0.5f, y / (float)(h - 1) - 0.5f);
                        float t = Mathf.Clamp01(Vector2.Dot(uv, direction) + 0.5f);
                        image[y * w + x] = Color.Lerp(s.gradientBottom, s.gradientTop, t);
                    }
                }
            }
            else if (s.background == 2)
            {
                var texture = Load<Texture2D>(s.backgroundImageGuid);
                if (texture == null)
                {
                    for (int i = 0; i < image.Length; i++)
                        image[i] = s.backgroundColor;
                }
                else
                {
                    float coverScale = Mathf.Max(w / (float)texture.width, h / (float)texture.height);
                    int tw = Mathf.Max(1, Mathf.RoundToInt(texture.width * coverScale));
                    int th = Mathf.Max(1, Mathf.RoundToInt(texture.height * coverScale));
                    var pixels = Readable(texture, tw, th);
                    int ox = (tw - w) / 2, oy = (th - h) / 2;
                    for (int y = 0; y < h; y++)
                        for (int x = 0; x < w; x++)
                            image[y * w + x] = pixels[Mathf.Clamp(y + oy, 0, th - 1) * tw + Mathf.Clamp(x + ox, 0, tw - 1)];
                }
            }

            return image;
        }

        private static void Grade(Color[] image, WPFMAThumbnailSettings s, int w, int h, float scale)
        {
            bool grade = Mathf.Abs(s.brightness) > 0.001f || Mathf.Abs(s.contrast) > 0.001f ||
                         Mathf.Abs(s.saturation) > 0.001f || s.tintAmount > 0.001f;

            if (grade)
            {
                for (int i = 0; i < image.Length; i++)
                {
                    var c = image[i];
                    float r = c.r + s.brightness, g = c.g + s.brightness, b = c.b + s.brightness;
                    r = (r - 0.5f) * (1f + s.contrast) + 0.5f;
                    g = (g - 0.5f) * (1f + s.contrast) + 0.5f;
                    b = (b - 0.5f) * (1f + s.contrast) + 0.5f;
                    float gray = r * 0.299f + g * 0.587f + b * 0.114f;
                    r = gray + (r - gray) * (1f + s.saturation);
                    g = gray + (g - gray) * (1f + s.saturation);
                    b = gray + (b - gray) * (1f + s.saturation);
                    r = Mathf.Lerp(r, r * s.tint.r, s.tintAmount);
                    g = Mathf.Lerp(g, g * s.tint.g, s.tintAmount);
                    b = Mathf.Lerp(b, b * s.tint.b, s.tintAmount);
                    image[i] = new Color(Mathf.Clamp01(r), Mathf.Clamp01(g), Mathf.Clamp01(b), c.a);
                }
            }

            int shift = Mathf.RoundToInt(s.chromatic * 12f * scale);
            if (shift > 0)
            {
                var copy = (Color[])image.Clone();
                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {
                        int i = y * w + x;
                        var c = image[i];
                        c.r = copy[y * w + Mathf.Clamp(x - shift, 0, w - 1)].r;
                        c.b = copy[y * w + Mathf.Clamp(x + shift, 0, w - 1)].b;
                        image[i] = c;
                    }
                }
            }

            if (s.scanlines > 0.001f)
            {
                int spacing = Mathf.Max(2, Mathf.RoundToInt(4f * scale));
                for (int y = 0; y < h; y++)
                {
                    if (y % spacing != 0)
                        continue;
                    for (int x = 0; x < w; x++)
                    {
                        var c = image[y * w + x];
                        float k = 1f - s.scanlines * 0.6f;
                        image[y * w + x] = new Color(c.r * k, c.g * k, c.b * k, c.a);
                    }
                }
            }

            if (s.vignette > 0.001f)
            {
                for (int y = 0; y < h; y++)
                {
                    for (int x = 0; x < w; x++)
                    {
                        float dx = (x / (float)w - 0.5f) * 2f, dy = (y / (float)h - 0.5f) * 2f;
                        float d = Mathf.Sqrt(dx * dx + dy * dy) / 1.4142f;
                        float k = 1f - s.vignette * Mathf.SmoothStep(0f, 1f, Mathf.InverseLerp(0.35f, 1f, d));
                        var c = image[y * w + x];
                        image[y * w + x] = new Color(c.r * k, c.g * k, c.b * k, c.a);
                    }
                }
            }

            if (s.grain > 0.001f)
            {
                var random = new System.Random(1234);
                for (int i = 0; i < image.Length; i++)
                {
                    float n = ((float)random.NextDouble() - 0.5f) * s.grain * 0.25f;
                    var c = image[i];
                    image[i] = new Color(Mathf.Clamp01(c.r + n), Mathf.Clamp01(c.g + n), Mathf.Clamp01(c.b + n), c.a);
                }
            }
        }

        private static void DrawLayer(Color[] image, WPFMAThumbnailLayer layer, int w, int h, float scale)
        {
            float[] mask;
            Color[] colors = null;

            switch (layer.kind)
            {
                case 0:
                    mask = TextMask(layer, w, h, scale);
                    break;
                case 1:
                    mask = ImageMask(layer, w, h, out colors);
                    break;
                default:
                    mask = ShapeMask(layer, w, h, layer.kind == 3);
                    break;
            }

            if (mask == null)
                return;

            if (layer.kind == 0 || layer.kind >= 2)
            {
                if (layer.shadow)
                {
                    var shadow = Blur(Shift(mask, w, h, layer.shadowOffset.x * scale, -layer.shadowOffset.y * scale), w, h,
                        Mathf.RoundToInt(layer.shadowSoftness * scale));
                    Over(image, shadow, layer.shadowColor, layer.opacity);
                }

                if (layer.glow)
                {
                    var glow = Blur(mask, w, h, Mathf.Max(1, Mathf.RoundToInt(layer.glowSize * scale)));
                    for (int i = 0; i < glow.Length; i++)
                        glow[i] = Mathf.Clamp01(glow[i] * 2f);
                    Over(image, glow, layer.glowColor, layer.opacity);
                }

                if (layer.outline)
                    Over(image, Dilate(mask, w, h, Mathf.Max(1, Mathf.RoundToInt(layer.outlineSize * scale))), layer.outlineColor, layer.opacity);
            }

            if (colors != null)
            {
                for (int i = 0; i < image.Length; i++)
                {
                    float a = mask[i] * layer.opacity;
                    if (a <= 0f)
                        continue;
                    var c = colors[i];
                    var bg = image[i];
                    image[i] = new Color(Mathf.Lerp(bg.r, c.r * layer.color.r, a), Mathf.Lerp(bg.g, c.g * layer.color.g, a),
                        Mathf.Lerp(bg.b, c.b * layer.color.b, a), a + bg.a * (1f - a));
                }
            }
            else
            {
                Over(image, mask, layer.color, layer.opacity);
            }
        }

        private static float[] TextMask(WPFMAThumbnailLayer layer, int w, int h, float scale)
        {
            if (string.IsNullOrEmpty(layer.text))
                return null;

            var font = Load<Font>(layer.fontGuid) ?? DefaultFont();
            if (font == null)
                return null;

            int size = Mathf.Max(4, Mathf.RoundToInt(layer.fontSize * scale));
            var style = layer.bold && layer.italic ? FontStyle.BoldAndItalic
                : layer.bold ? FontStyle.Bold
                : layer.italic ? FontStyle.Italic
                : FontStyle.Normal;

            font.RequestCharactersInTexture(layer.text, size, style);

            var atlas = font.material != null ? font.material.mainTexture : null;
            if (atlas == null)
                return null;

            var atlasPixels = Readable(atlas, atlas.width, atlas.height);
            bool useRed = atlasPixels.All(p => p.a > 0.99f);
            int aw = atlas.width, ah = atlas.height;

            var lines = layer.text.Replace("\r", string.Empty).Split('\n');
            float lineHeight = size * 1.2f;
            float ascent = size * 0.8f;

            var glyphs = new List<KeyValuePair<Rect, CharacterInfo>>();
            var widths = new List<float>();

            foreach (var line in lines)
            {
                float width = 0f;
                foreach (var ch in line)
                {
                    CharacterInfo info;
                    if (font.GetCharacterInfo(ch, out info, size, style))
                        width += info.advance;
                }
                widths.Add(width);
            }

            float blockWidth = widths.Count > 0 ? widths.Max() : 0f;
            float blockHeight = lines.Length * lineHeight;

            for (int l = 0; l < lines.Length; l++)
            {
                float pen = layer.align == 0 ? 0f : layer.align == 2 ? blockWidth - widths[l] : (blockWidth - widths[l]) * 0.5f;
                float baseline = l * lineHeight + ascent;

                foreach (var ch in lines[l])
                {
                    CharacterInfo info;
                    if (!font.GetCharacterInfo(ch, out info, size, style))
                        continue;

                    var rect = Rect.MinMaxRect(pen + info.minX, baseline - info.maxY, pen + info.maxX, baseline - info.minY);
                    if (rect.width > 0f && rect.height > 0f)
                        glyphs.Add(new KeyValuePair<Rect, CharacterInfo>(rect, info));
                    pen += info.advance;
                }
            }

            var anchor = new Vector2(layer.position.x * w, layer.position.y * h);
            float offsetX = layer.align == 0 ? 0f : layer.align == 2 ? -blockWidth : -blockWidth * 0.5f;
            var origin = new Vector2(anchor.x + offsetX, anchor.y - blockHeight * 0.5f);

            float radians = layer.rotation * Mathf.Deg2Rad;
            float cos = Mathf.Cos(radians), sin = Mathf.Sin(radians);

            var mask = new float[w * h];

            foreach (var glyph in glyphs)
            {
                var rect = glyph.Key;
                var info = glyph.Value;

                var corners = new[]
                {
                    Rotate(origin + new Vector2(rect.xMin, rect.yMin), anchor, cos, sin),
                    Rotate(origin + new Vector2(rect.xMax, rect.yMin), anchor, cos, sin),
                    Rotate(origin + new Vector2(rect.xMin, rect.yMax), anchor, cos, sin),
                    Rotate(origin + new Vector2(rect.xMax, rect.yMax), anchor, cos, sin)
                };

                int minX = Mathf.Max(0, Mathf.FloorToInt(corners.Min(c => c.x)));
                int maxX = Mathf.Min(w - 1, Mathf.CeilToInt(corners.Max(c => c.x)));
                int minY = Mathf.Max(0, Mathf.FloorToInt(corners.Min(c => c.y)));
                int maxY = Mathf.Min(h - 1, Mathf.CeilToInt(corners.Max(c => c.y)));

                for (int py = minY; py <= maxY; py++)
                {
                    for (int px = minX; px <= maxX; px++)
                    {
                        var local = Rotate(new Vector2(px + 0.5f, py + 0.5f), anchor, cos, -sin) - origin;
                        if (local.x < rect.xMin || local.x > rect.xMax || local.y < rect.yMin || local.y > rect.yMax)
                            continue;

                        float u = (local.x - rect.xMin) / rect.width;
                        float v = (rect.yMax - local.y) / rect.height;
                        var bottom = Vector2.Lerp(info.uvBottomLeft, info.uvBottomRight, u);
                        var top = Vector2.Lerp(info.uvTopLeft, info.uvTopRight, u);
                        var uv = Vector2.Lerp(bottom, top, v);

                        float coverage = Sample(atlasPixels, aw, ah, uv, useRed);
                        int index = (h - 1 - py) * w + px;
                        if (coverage > mask[index])
                            mask[index] = coverage;
                    }
                }
            }

            return mask;
        }

        private static float[] ImageMask(WPFMAThumbnailLayer layer, int w, int h, out Color[] colors)
        {
            colors = null;
            var texture = Load<Texture2D>(layer.imageGuid);
            if (texture == null)
                return null;

            float drawWidth = Mathf.Max(1f, layer.scale * w);
            float drawHeight = drawWidth * texture.height / Mathf.Max(1f, texture.width);
            int tw = Mathf.Max(1, Mathf.Min(2048, Mathf.RoundToInt(drawWidth)));
            int th = Mathf.Max(1, Mathf.Min(2048, Mathf.RoundToInt(drawHeight)));
            var pixels = Readable(texture, tw, th);

            var anchor = new Vector2(layer.position.x * w, layer.position.y * h);
            float radians = layer.rotation * Mathf.Deg2Rad;
            float cos = Mathf.Cos(radians), sin = Mathf.Sin(radians);
            float radius = Mathf.Sqrt(drawWidth * drawWidth + drawHeight * drawHeight) * 0.5f;

            var mask = new float[w * h];
            colors = new Color[w * h];

            int minX = Mathf.Max(0, Mathf.FloorToInt(anchor.x - radius)), maxX = Mathf.Min(w - 1, Mathf.CeilToInt(anchor.x + radius));
            int minY = Mathf.Max(0, Mathf.FloorToInt(anchor.y - radius)), maxY = Mathf.Min(h - 1, Mathf.CeilToInt(anchor.y + radius));

            for (int py = minY; py <= maxY; py++)
            {
                for (int px = minX; px <= maxX; px++)
                {
                    var local = Rotate(new Vector2(px + 0.5f, py + 0.5f), anchor, cos, -sin) - anchor;
                    float u = local.x / drawWidth + 0.5f;
                    float v = 0.5f - local.y / drawHeight;
                    if (u < 0f || u > 1f || v < 0f || v > 1f)
                        continue;

                    var c = pixels[Mathf.Clamp((int)(v * th), 0, th - 1) * tw + Mathf.Clamp((int)(u * tw), 0, tw - 1)];
                    int index = (h - 1 - py) * w + px;
                    mask[index] = c.a;
                    colors[index] = c;
                }
            }

            return mask;
        }

        private static float[] ShapeMask(WPFMAThumbnailLayer layer, int w, int h, bool circle)
        {
            var anchor = new Vector2(layer.position.x * w, layer.position.y * h);
            float halfW = layer.size.x * w * 0.5f, halfH = layer.size.y * h * 0.5f;
            float radians = layer.rotation * Mathf.Deg2Rad;
            float cos = Mathf.Cos(radians), sin = Mathf.Sin(radians);
            float radius = Mathf.Sqrt(halfW * halfW + halfH * halfH);

            var mask = new float[w * h];
            int minX = Mathf.Max(0, Mathf.FloorToInt(anchor.x - radius)), maxX = Mathf.Min(w - 1, Mathf.CeilToInt(anchor.x + radius));
            int minY = Mathf.Max(0, Mathf.FloorToInt(anchor.y - radius)), maxY = Mathf.Min(h - 1, Mathf.CeilToInt(anchor.y + radius));

            for (int py = minY; py <= maxY; py++)
            {
                for (int px = minX; px <= maxX; px++)
                {
                    var local = Rotate(new Vector2(px + 0.5f, py + 0.5f), anchor, cos, -sin) - anchor;
                    float coverage;
                    if (circle)
                    {
                        float d = Mathf.Sqrt((local.x * local.x) / (halfW * halfW) + (local.y * local.y) / (halfH * halfH));
                        coverage = Mathf.Clamp01((1f - d) * Mathf.Min(halfW, halfH));
                    }
                    else
                    {
                        coverage = Mathf.Clamp01(halfW - Mathf.Abs(local.x) + 0.5f) * Mathf.Clamp01(halfH - Mathf.Abs(local.y) + 0.5f);
                    }

                    if (coverage > 0f)
                        mask[(h - 1 - py) * w + px] = coverage;
                }
            }

            return mask;
        }

        private static Vector2 Rotate(Vector2 point, Vector2 pivot, float cos, float sin)
        {
            var d = point - pivot;
            return pivot + new Vector2(d.x * cos - d.y * sin, d.x * sin + d.y * cos);
        }

        private static float Sample(Color[] pixels, int w, int h, Vector2 uv, bool useRed)
        {
            float x = uv.x * w - 0.5f, y = uv.y * h - 0.5f;
            int x0 = Mathf.Clamp(Mathf.FloorToInt(x), 0, w - 1), y0 = Mathf.Clamp(Mathf.FloorToInt(y), 0, h - 1);
            int x1 = Mathf.Min(x0 + 1, w - 1), y1 = Mathf.Min(y0 + 1, h - 1);
            float fx = Mathf.Clamp01(x - x0), fy = Mathf.Clamp01(y - y0);

            Func<int, float> value = i => useRed ? pixels[i].r : pixels[i].a;
            float a = Mathf.Lerp(value(y0 * w + x0), value(y0 * w + x1), fx);
            float b = Mathf.Lerp(value(y1 * w + x0), value(y1 * w + x1), fx);
            return Mathf.Lerp(a, b, fy);
        }

        private static void Over(Color[] image, float[] mask, Color color, float opacity = 1f)
        {
            for (int i = 0; i < image.Length; i++)
            {
                float a = mask[i] * color.a * opacity;
                if (a <= 0f)
                    continue;
                var bg = image[i];
                image[i] = new Color(Mathf.Lerp(bg.r, color.r, a), Mathf.Lerp(bg.g, color.g, a), Mathf.Lerp(bg.b, color.b, a),
                    a + bg.a * (1f - a));
            }
        }

        private static float[] Shift(float[] mask, int w, int h, float dx, float dy)
        {
            int ox = Mathf.RoundToInt(dx), oy = Mathf.RoundToInt(dy);
            var result = new float[mask.Length];
            for (int y = 0; y < h; y++)
            {
                int sy = y - oy;
                if (sy < 0 || sy >= h)
                    continue;
                for (int x = 0; x < w; x++)
                {
                    int sx = x - ox;
                    if (sx >= 0 && sx < w)
                        result[y * w + x] = mask[sy * w + sx];
                }
            }
            return result;
        }

        private static float[] Dilate(float[] mask, int w, int h, int radius)
        {
            var blurred = Blur(mask, w, h, radius);
            for (int i = 0; i < blurred.Length; i++)
                blurred[i] = Mathf.Clamp01(Mathf.Max(mask[i], blurred[i] * 4f));
            return blurred;
        }

        private static float[] Blur(float[] source, int w, int h, int radius)
        {
            if (radius <= 0)
                return (float[])source.Clone();

            var a = (float[])source.Clone();
            var b = new float[source.Length];
            for (int pass = 0; pass < 3; pass++)
            {
                BoxHorizontal(a, b, w, h, radius);
                BoxVertical(b, a, w, h, radius);
            }
            return a;
        }

        private static void BoxHorizontal(float[] src, float[] dst, int w, int h, int r)
        {
            float norm = 1f / (r * 2 + 1);
            for (int y = 0; y < h; y++)
            {
                int row = y * w;
                float sum = 0f;
                for (int k = -r; k <= r; k++)
                    sum += src[row + Mathf.Clamp(k, 0, w - 1)];
                for (int x = 0; x < w; x++)
                {
                    dst[row + x] = sum * norm;
                    sum += src[row + Mathf.Min(x + r + 1, w - 1)] - src[row + Mathf.Max(x - r, 0)];
                }
            }
        }

        private static void BoxVertical(float[] src, float[] dst, int w, int h, int r)
        {
            float norm = 1f / (r * 2 + 1);
            for (int x = 0; x < w; x++)
            {
                float sum = 0f;
                for (int k = -r; k <= r; k++)
                    sum += src[Mathf.Clamp(k, 0, h - 1) * w + x];
                for (int y = 0; y < h; y++)
                {
                    dst[y * w + x] = sum * norm;
                    sum += src[Mathf.Min(y + r + 1, h - 1) * w + x] - src[Mathf.Max(y - r, 0) * w + x];
                }
            }
        }

        internal static T Load<T>(string guid) where T : UnityEngine.Object
        {
            if (string.IsNullOrEmpty(guid))
                return null;
            string path = AssetDatabase.GUIDToAssetPath(guid);
            return string.IsNullOrEmpty(path) ? null : AssetDatabase.LoadAssetAtPath<T>(path);
        }

        internal static string Guid(UnityEngine.Object asset)
        {
            if (asset == null)
                return string.Empty;
            string path = AssetDatabase.GetAssetPath(asset);
            return string.IsNullOrEmpty(path) ? string.Empty : AssetDatabase.AssetPathToGUID(path);
        }

        private static Font defaultFont;

        internal static Font DefaultFont()
        {
            if (defaultFont != null)
                return defaultFont;

            foreach (var name in new[] { "LegacyRuntime.ttf", "Arial.ttf" })
            {
                try
                {
                    defaultFont = Resources.GetBuiltinResource<Font>(name);
                    if (defaultFont != null)
                        return defaultFont;
                }
                catch (Exception)
                {
                }
            }

            return null;
        }
    }

    internal sealed class WPFMAThumbnailStudio : EditorWindow
    {
        [Serializable]
        private sealed class NamedPreset
        {
            public string name;
            public string json;
        }

        [Serializable]
        private sealed class PresetFile
        {
            public List<NamedPreset> presets = new List<NamedPreset>();
        }

        private static readonly string[] FramingNames = { "Head", "Upper body", "Full body" };
        private static readonly string[] BackgroundNames = { "Solid colour", "Gradient", "Image", "Transparent" };
        private static readonly string[] AlignNames = { "Left", "Centre", "Right" };
        private static readonly string[] SizeNames = { "1200 x 900 (4:3)", "1920 x 1080 (16:9)", "1024 x 1024 (square)" };
        private static readonly Vector2Int[] Sizes = { new Vector2Int(1200, 900), new Vector2Int(1920, 1080), new Vector2Int(1024, 1024) };

        private const float PreviewWidth = 640f;
        private const string SettingsKey = "WPFMA.ThumbnailStudio.Settings";

        private GameObject avatar;
        private WPFMAThumbnailSettings settings;
        private Texture2D preview;
        private bool dirty = true;
        private double lastChange;
        private Vector2 scroll;
        private string presetName = string.Empty;
        private int presetIndex;
        private string status;
        private readonly HashSet<string> open = new HashSet<string> { "camera", "background", "effects", "layers", "export" };

        internal static void OpenForScene()
        {
            var window = GetWindow<WPFMAThumbnailStudio>(false, "Thumbnail Studio", true);
            window.minSize = new Vector2(980f, 640f);
            window.settings.source = 1;
            WPFMAThumbnailRenderer.GrabSceneView(window.settings);
            window.dirty = true;
            window.Show();
        }

        internal static void Open(GameObject avatar)
        {
            var window = GetWindow<WPFMAThumbnailStudio>(false, "Thumbnail Studio", true);
            window.minSize = new Vector2(980f, 640f);
            if (avatar != null)
                window.avatar = avatar;
            window.dirty = true;
            window.Show();
        }

        private void OnEnable()
        {
            settings = LoadLast() ?? Starter();
            EditorApplication.update += Tick;
        }

        private void OnDisable()
        {
            EditorApplication.update -= Tick;
            SaveLast();
            if (preview != null)
                DestroyImmediate(preview);
        }

        private void Tick()
        {
            if (!dirty || EditorApplication.isPlayingOrWillChangePlaymode)
                return;

            if (EditorApplication.timeSinceStartup - lastChange < 0.15)
                return;

            dirty = false;
            RenderPreview();
            Repaint();
        }

        private void RenderPreview()
        {
            float scale = Mathf.Min(1f, PreviewWidth / settings.width);
            int w = Mathf.Max(16, Mathf.RoundToInt(settings.width * scale));
            int h = Mathf.Max(16, Mathf.RoundToInt(settings.height * scale));

            try
            {
                var pixels = WPFMAThumbnailRenderer.Render(avatar, settings, w, h, scale);
                if (preview == null || preview.width != w || preview.height != h)
                {
                    if (preview != null)
                        DestroyImmediate(preview);
                    preview = new Texture2D(w, h, TextureFormat.RGBA32, false) { hideFlags = HideFlags.HideAndDontSave };
                }

                preview.SetPixels(pixels);
                preview.Apply();
                status = null;
            }
            catch (Exception e)
            {
                status = "Preview failed: " + e.Message;
                Debug.LogWarning("[WPFMA-SDK] Thumbnail preview failed: " + e);
            }
        }

        private void OnGUI()
        {
            if (settings == null)
                settings = Starter();

            var left = new Rect(0f, 0f, 380f, position.height);
            var right = new Rect(left.xMax, 0f, position.width - left.xMax, position.height);

            GUILayout.BeginArea(new Rect(left.x + 8f, left.y + 8f, left.width - 12f, left.height - 16f));
            scroll = EditorGUILayout.BeginScrollView(scroll);
            EditorGUI.BeginChangeCheck();

            DrawControls();

            if (EditorGUI.EndChangeCheck())
            {
                dirty = true;
                lastChange = EditorApplication.timeSinceStartup;
            }

            EditorGUILayout.EndScrollView();
            GUILayout.EndArea();

            EditorGUI.DrawRect(right, new Color(0.09f, 0.1f, 0.12f));
            DrawPreview(right);
        }

        private void DrawPreview(Rect area)
        {
            if (preview == null)
            {
                GUI.Label(area, avatar == null && settings.source == 0 ? "Pick an avatar on the left." : "Rendering...",
                    new GUIStyle(EditorStyles.centeredGreyMiniLabel) { fontSize = 13 });
                return;
            }

            float aspect = settings.width / (float)settings.height;
            float maxW = area.width - 24f, maxH = area.height - 60f;
            float w = Mathf.Min(maxW, maxH * aspect), h = w / aspect;
            var rect = new Rect(area.x + (area.width - w) * 0.5f, area.y + 16f, w, h);

            if (settings.background == 3)
            {
                for (int y = 0; y < Mathf.CeilToInt(h / 16f); y++)
                    for (int x = 0; x < Mathf.CeilToInt(w / 16f); x++)
                        EditorGUI.DrawRect(new Rect(rect.x + x * 16f, rect.y + y * 16f, Mathf.Min(16f, w - x * 16f), Mathf.Min(16f, h - y * 16f)),
                            (x + y) % 2 == 0 ? new Color(0.3f, 0.3f, 0.3f) : new Color(0.22f, 0.22f, 0.22f));
            }

            GUI.DrawTexture(rect, preview, ScaleMode.StretchToFill, true);
            GUI.Label(new Rect(rect.x, rect.yMax + 6f, rect.width, 18f),
                settings.width + " x " + settings.height + "  -  preview is shown smaller; the saved image is full size.",
                EditorStyles.centeredGreyMiniLabel);

            if (!string.IsNullOrEmpty(status))
                GUI.Label(new Rect(rect.x, rect.yMax + 24f, rect.width, 18f), status, EditorStyles.centeredGreyMiniLabel);
        }

        private void DrawControls()
        {
            EditorGUILayout.LabelField("Thumbnail Studio", new GUIStyle(EditorStyles.boldLabel) { fontSize = 15 });
            settings.source = GUILayout.Toolbar(settings.source, new[] { "Avatar", "Scene view (worlds)" });

            if (settings.source == 1)
            {
                EditorGUILayout.LabelField("Frame the shot in the Scene view, then grab it. Editor-only objects are hidden in the picture.",
                    EditorStyles.wordWrappedMiniLabel);
                if (GUILayout.Button("Use the current Scene view angle", GUILayout.Height(24f)))
                {
                    WPFMAThumbnailRenderer.GrabSceneView(settings);
                    GUI.changed = true;
                }
                settings.sceneFov = EditorGUILayout.Slider("Lens (FOV)", settings.sceneFov, 10f, 100f);
            }
            else
            {
                var picked = (GameObject)EditorGUILayout.ObjectField("Avatar", avatar, typeof(GameObject), true);
                if (picked != avatar)
                    avatar = picked != null && !EditorUtility.IsPersistent(picked) ? WPFMAAvatarFolders.AvatarRoot(picked) ?? picked : null;
            }

            if (settings.source == 0 && Section("camera", "Camera"))
            {
                settings.framing = GUILayout.Toolbar(settings.framing, FramingNames);
                settings.yaw = EditorGUILayout.Slider("Turn", settings.yaw, -180f, 180f);
                settings.pitch = EditorGUILayout.Slider("Tilt", settings.pitch, -45f, 60f);
                settings.zoom = EditorGUILayout.Slider("Zoom", settings.zoom, 0.4f, 3f);
                settings.lift = EditorGUILayout.Slider("Move up/down", settings.lift, -0.5f, 0.5f);
                settings.side = EditorGUILayout.Slider("Move left/right", settings.side, -0.5f, 0.5f);
                settings.fov = EditorGUILayout.Slider("Lens (FOV)", settings.fov, 10f, 70f);
            }

            if (settings.source == 0 && Section("light", "Lighting"))
            {
                settings.keyIntensity = EditorGUILayout.Slider("Key light", settings.keyIntensity, 0f, 3f);
                settings.keyColor = EditorGUILayout.ColorField("Key colour", settings.keyColor);
                settings.keyYaw = EditorGUILayout.Slider("Key direction", settings.keyYaw, -180f, 180f);
                settings.keyPitch = EditorGUILayout.Slider("Key height", settings.keyPitch, -30f, 90f);
                settings.rim = EditorGUILayout.Toggle("Rim light", settings.rim);
                if (settings.rim)
                {
                    settings.rimIntensity = EditorGUILayout.Slider("Rim strength", settings.rimIntensity, 0f, 3f);
                    settings.rimColor = EditorGUILayout.ColorField("Rim colour", settings.rimColor);
                }
                settings.ambient = EditorGUILayout.Slider("Ambient", settings.ambient, 0f, 2f);
                settings.ambientColor = EditorGUILayout.ColorField("Ambient colour", settings.ambientColor);
            }

            if (settings.source == 0 && Section("background", "Background"))
            {
                settings.background = GUILayout.Toolbar(settings.background, BackgroundNames);
                switch (settings.background)
                {
                    case 0:
                        settings.backgroundColor = EditorGUILayout.ColorField("Colour", settings.backgroundColor);
                        break;
                    case 1:
                        settings.gradientTop = EditorGUILayout.ColorField("Top", settings.gradientTop);
                        settings.gradientBottom = EditorGUILayout.ColorField("Bottom", settings.gradientBottom);
                        settings.gradientAngle = EditorGUILayout.Slider("Angle", settings.gradientAngle, -180f, 180f);
                        break;
                    case 2:
                        var image = (Texture2D)EditorGUILayout.ObjectField("Image", WPFMAThumbnailRenderer.Load<Texture2D>(settings.backgroundImageGuid), typeof(Texture2D), false);
                        settings.backgroundImageGuid = WPFMAThumbnailRenderer.Guid(image);
                        break;
                    default:
                        EditorGUILayout.LabelField("Saves as a PNG with a see-through background.", EditorStyles.miniLabel);
                        break;
                }
            }

            if (settings.source == 0 && Section("effects", "Avatar effects"))
            {
                settings.glow = EditorGUILayout.Toggle("Glow", settings.glow);
                if (settings.glow)
                {
                    settings.glowColor = EditorGUILayout.ColorField("  Glow colour", settings.glowColor);
                    settings.glowSize = EditorGUILayout.Slider("  Glow size", settings.glowSize, 2f, 120f);
                    settings.glowStrength = EditorGUILayout.Slider("  Glow strength", settings.glowStrength, 0.1f, 3f);
                }

                settings.outline = EditorGUILayout.Toggle("Outline", settings.outline);
                if (settings.outline)
                {
                    settings.outlineColor = EditorGUILayout.ColorField("  Outline colour", settings.outlineColor);
                    settings.outlineSize = EditorGUILayout.Slider("  Outline width", settings.outlineSize, 1f, 40f);
                }

                settings.shadow = EditorGUILayout.Toggle("Drop shadow", settings.shadow);
                if (settings.shadow)
                {
                    settings.shadowColor = EditorGUILayout.ColorField("  Shadow colour", settings.shadowColor);
                    settings.shadowOffset = EditorGUILayout.Vector2Field("  Shadow offset", settings.shadowOffset);
                    settings.shadowSoftness = EditorGUILayout.Slider("  Softness", settings.shadowSoftness, 0f, 80f);
                }
            }

            if (Section("look", "Image effects"))
            {
                settings.brightness = EditorGUILayout.Slider("Brightness", settings.brightness, -0.5f, 0.5f);
                settings.contrast = EditorGUILayout.Slider("Contrast", settings.contrast, -0.8f, 1f);
                settings.saturation = EditorGUILayout.Slider("Saturation", settings.saturation, -1f, 1f);
                settings.tint = EditorGUILayout.ColorField("Tint", settings.tint);
                settings.tintAmount = EditorGUILayout.Slider("Tint amount", settings.tintAmount, 0f, 1f);
                settings.vignette = EditorGUILayout.Slider("Vignette", settings.vignette, 0f, 1f);
                settings.grain = EditorGUILayout.Slider("Film grain", settings.grain, 0f, 1f);
                settings.chromatic = EditorGUILayout.Slider("Colour split", settings.chromatic, 0f, 1f);
                settings.scanlines = EditorGUILayout.Slider("Scanlines", settings.scanlines, 0f, 1f);
            }

            if (Section("layers", "Text, images and shapes"))
                DrawLayers();

            if (Section("presets", "Presets"))
                DrawPresets();

            if (Section("export", "Save"))
                DrawExport();
        }

        private void DrawLayers()
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("+ Text"))
                    settings.layers.Add(new WPFMAThumbnailLayer { kind = 0 });
                if (GUILayout.Button("+ Image"))
                    settings.layers.Add(new WPFMAThumbnailLayer { kind = 1, position = new Vector2(0.85f, 0.85f), outline = false, shadow = false });
                if (GUILayout.Button("+ Box"))
                    settings.layers.Add(new WPFMAThumbnailLayer { kind = 2, color = new Color(0f, 0f, 0f, 0.55f), position = new Vector2(0.5f, 0.88f), size = new Vector2(1f, 0.16f), outline = false, shadow = false });
                if (GUILayout.Button("+ Circle"))
                    settings.layers.Add(new WPFMAThumbnailLayer { kind = 3, color = new Color(1f, 1f, 1f, 0.15f), position = new Vector2(0.5f, 0.5f), size = new Vector2(0.5f, 0.66f), outline = false, shadow = false });
            }

            EditorGUILayout.LabelField("Layers draw top to bottom: the last one is in front. Position 0,0 is the top-left corner.",
                EditorStyles.wordWrappedMiniLabel);

            for (int i = 0; i < settings.layers.Count; i++)
            {
                var layer = settings.layers[i];
                EditorGUILayout.Space(2f);

                using (new EditorGUILayout.HorizontalScope())
                {
                    layer.visible = EditorGUILayout.Toggle(layer.visible, GUILayout.Width(16f));
                    layer.expanded = EditorGUILayout.Foldout(layer.expanded, layer.Title, true);

                    using (new EditorGUI.DisabledScope(i == 0))
                        if (GUILayout.Button("▲", EditorStyles.miniButtonLeft, GUILayout.Width(22f)))
                        {
                            settings.layers.RemoveAt(i);
                            settings.layers.Insert(i - 1, layer);
                            MarkDirty();
                            GUIUtility.ExitGUI();
                        }

                    using (new EditorGUI.DisabledScope(i == settings.layers.Count - 1))
                        if (GUILayout.Button("▼", EditorStyles.miniButtonMid, GUILayout.Width(22f)))
                        {
                            settings.layers.RemoveAt(i);
                            settings.layers.Insert(i + 1, layer);
                            MarkDirty();
                            GUIUtility.ExitGUI();
                        }

                    if (GUILayout.Button("Copy", EditorStyles.miniButtonMid, GUILayout.Width(38f)))
                    {
                        settings.layers.Insert(i + 1, JsonUtility.FromJson<WPFMAThumbnailLayer>(JsonUtility.ToJson(layer)));
                        MarkDirty();
                        GUIUtility.ExitGUI();
                    }

                    if (GUILayout.Button("x", EditorStyles.miniButtonRight, GUILayout.Width(22f)))
                    {
                        settings.layers.RemoveAt(i);
                        MarkDirty();
                        GUIUtility.ExitGUI();
                    }
                }

                if (!layer.expanded)
                    continue;

                EditorGUI.indentLevel++;
                switch (layer.kind)
                {
                    case 0:
                        EditorGUILayout.LabelField("Text");
                        layer.text = EditorGUILayout.TextArea(layer.text, GUILayout.MinHeight(36f));
                        var font = (Font)EditorGUILayout.ObjectField("Font", WPFMAThumbnailRenderer.Load<Font>(layer.fontGuid), typeof(Font), false);
                        layer.fontGuid = WPFMAThumbnailRenderer.Guid(font);
                        layer.fontSize = EditorGUILayout.IntSlider("Size", layer.fontSize, 12, 400);
                        using (new EditorGUILayout.HorizontalScope())
                        {
                            layer.bold = EditorGUILayout.ToggleLeft("Bold", layer.bold, GUILayout.Width(80f));
                            layer.italic = EditorGUILayout.ToggleLeft("Italic", layer.italic, GUILayout.Width(80f));
                        }
                        layer.align = EditorGUILayout.Popup("Align", layer.align, AlignNames);
                        layer.color = EditorGUILayout.ColorField("Colour", layer.color);
                        break;
                    case 1:
                        var image = (Texture2D)EditorGUILayout.ObjectField("Image", WPFMAThumbnailRenderer.Load<Texture2D>(layer.imageGuid), typeof(Texture2D), false);
                        layer.imageGuid = WPFMAThumbnailRenderer.Guid(image);
                        layer.scale = EditorGUILayout.Slider("Width", layer.scale, 0.02f, 1.5f);
                        layer.color = EditorGUILayout.ColorField("Tint", layer.color);
                        break;
                    default:
                        layer.color = EditorGUILayout.ColorField("Colour", layer.color);
                        layer.size = EditorGUILayout.Vector2Field("Size (0-1)", layer.size);
                        break;
                }

                layer.position = EditorGUILayout.Vector2Field("Position (0-1)", layer.position);
                layer.rotation = EditorGUILayout.Slider("Rotation", layer.rotation, -180f, 180f);
                layer.opacity = EditorGUILayout.Slider("Opacity", layer.opacity, 0f, 1f);

                if (layer.kind != 1)
                {
                    layer.outline = EditorGUILayout.Toggle("Outline", layer.outline);
                    if (layer.outline)
                    {
                        layer.outlineColor = EditorGUILayout.ColorField("  Outline colour", layer.outlineColor);
                        layer.outlineSize = EditorGUILayout.Slider("  Outline width", layer.outlineSize, 1f, 30f);
                    }

                    layer.shadow = EditorGUILayout.Toggle("Shadow", layer.shadow);
                    if (layer.shadow)
                    {
                        layer.shadowColor = EditorGUILayout.ColorField("  Shadow colour", layer.shadowColor);
                        layer.shadowOffset = EditorGUILayout.Vector2Field("  Shadow offset", layer.shadowOffset);
                        layer.shadowSoftness = EditorGUILayout.Slider("  Softness", layer.shadowSoftness, 0f, 40f);
                    }

                    layer.glow = EditorGUILayout.Toggle("Glow", layer.glow);
                    if (layer.glow)
                    {
                        layer.glowColor = EditorGUILayout.ColorField("  Glow colour", layer.glowColor);
                        layer.glowSize = EditorGUILayout.Slider("  Glow size", layer.glowSize, 2f, 80f);
                    }
                }
                EditorGUI.indentLevel--;
            }
        }

        private void DrawPresets()
        {
            var presets = LoadPresets();
            if (presets.presets.Count > 0)
            {
                presetIndex = Mathf.Clamp(presetIndex, 0, presets.presets.Count - 1);
                using (new EditorGUILayout.HorizontalScope())
                {
                    presetIndex = EditorGUILayout.Popup(presetIndex, presets.presets.Select(p => p.name).ToArray());
                    if (GUILayout.Button("Load", GUILayout.Width(50f)))
                    {
                        var loaded = JsonUtility.FromJson<WPFMAThumbnailSettings>(presets.presets[presetIndex].json);
                        if (loaded != null)
                        {
                            settings = loaded;
                            GUI.changed = true;
                        }
                    }
                    if (GUILayout.Button("Delete", GUILayout.Width(55f)))
                    {
                        string name = presets.presets[presetIndex].name;
                        EditorApplication.delayCall += () =>
                        {
                            if (!EditorUtility.DisplayDialog("Delete preset", "Delete the thumbnail preset '" + name + "'?", "Delete", "Cancel"))
                                return;
                            var file = LoadPresets();
                            file.presets.RemoveAll(p => p.name == name);
                            SavePresets(file);
                            presetIndex = 0;
                            Repaint();
                        };
                    }
                }
            }
            else
            {
                EditorGUILayout.LabelField("No presets yet. Save a look you like below.", EditorStyles.miniLabel);
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                presetName = EditorGUILayout.TextField(presetName);
                using (new EditorGUI.DisabledScope(string.IsNullOrWhiteSpace(presetName)))
                {
                    if (GUILayout.Button("Save look", GUILayout.Width(80f)))
                    {
                        var file = LoadPresets();
                        string name = presetName.Trim();
                        file.presets.RemoveAll(p => p.name == name);
                        file.presets.Add(new NamedPreset { name = name, json = JsonUtility.ToJson(settings) });
                        file.presets.Sort((a, b) => string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase));
                        SavePresets(file);
                        presetIndex = file.presets.FindIndex(p => p.name == name);
                        presetName = string.Empty;
                    }
                }
            }

            EditorGUILayout.LabelField("Presets are saved on this PC and show up in every project.", EditorStyles.miniLabel);

            if (GUILayout.Button("Reset to the starter look", EditorStyles.miniButton))
            {
                settings = Starter();
                GUI.changed = true;
            }
        }

        private void DrawExport()
        {
            int sizeIndex = Array.FindIndex(Sizes, v => v.x == settings.width && v.y == settings.height);
            int pickedSize = EditorGUILayout.Popup("Size", Mathf.Max(0, sizeIndex), SizeNames);
            if (pickedSize != sizeIndex)
            {
                settings.width = Sizes[pickedSize].x;
                settings.height = Sizes[pickedSize].y;
            }

            using (new EditorGUI.DisabledScope(avatar == null && settings.source == 0))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    if (GUILayout.Button("Save PNG...", GUILayout.Height(28f)))
                        EditorApplication.delayCall += () => Export(false);
                    if (GUILayout.Button("Save into project", GUILayout.Height(28f)))
                        EditorApplication.delayCall += () => Export(true);
                }
            }

            EditorGUILayout.LabelField("Pick the saved image as the thumbnail in VRChat's build panel when you upload.",
                EditorStyles.wordWrappedMiniLabel);
        }

        private void Export(bool intoProject)
        {
            string path;
            if (intoProject)
            {
                string folder = (settings.source == 1 || avatar == null ? WPFMAWorldTypes.SceneFolder() : WPFMAAvatarFolders.For(avatar)) + "/Thumbnails";
                WPFMAAvatarFolders.Ensure(folder);
                string baseName = settings.source == 1 || avatar == null
                    ? UnityEngine.SceneManagement.SceneManager.GetActiveScene().name
                    : avatar.name;
                path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + WPFMAPaths.SafeFileName(baseName) + " thumbnail.png");
            }
            else
            {
                path = EditorUtility.SaveFilePanel("Save thumbnail", Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                    WPFMAPaths.SafeFileName(avatar != null ? avatar.name : "Avatar") + " thumbnail", "png");
                if (string.IsNullOrEmpty(path))
                    return;
            }

            try
            {
                EditorUtility.DisplayProgressBar("Thumbnail Studio", "Rendering " + settings.width + " x " + settings.height, 0.5f);
                var pixels = WPFMAThumbnailRenderer.Render(avatar, settings, settings.width, settings.height, 1f);
                var texture = new Texture2D(settings.width, settings.height, TextureFormat.RGBA32, false);
                texture.SetPixels(pixels);
                texture.Apply();
                File.WriteAllBytes(path, texture.EncodeToPNG());
                DestroyImmediate(texture);
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            if (intoProject)
            {
                AssetDatabase.ImportAsset(path);
                EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Texture2D>(path));
            }
            else
            {
                EditorUtility.RevealInFinder(path);
            }

            status = "Saved " + path;
            Debug.Log("[WPFMA-SDK] Thumbnail saved: " + path);
        }

        private void MarkDirty()
        {
            dirty = true;
            lastChange = EditorApplication.timeSinceStartup;
        }

        private bool Section(string key, string title)
        {
            EditorGUILayout.Space(4f);
            bool expanded = open.Contains(key);
            bool now = EditorGUILayout.Foldout(expanded, title, true, new GUIStyle(EditorStyles.foldout) { fontStyle = FontStyle.Bold });
            if (now != expanded)
            {
                if (now)
                    open.Add(key);
                else
                    open.Remove(key);
            }
            return now;
        }

        private static WPFMAThumbnailSettings Starter()
        {
            var starter = new WPFMAThumbnailSettings();
            starter.layers.Add(new WPFMAThumbnailLayer { kind = 2, color = new Color(0f, 0f, 0f, 0.45f), position = new Vector2(0.5f, 0.9f), size = new Vector2(1f, 0.2f), outline = false, shadow = false, visible = false, expanded = false });
            starter.layers.Add(new WPFMAThumbnailLayer { kind = 0, text = "My Avatar", position = new Vector2(0.5f, 0.9f), expanded = true });
            return starter;
        }

        private static string PresetPath
        {
            get
            {
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "WPFMA-SDK", "thumbnail-presets.json");
            }
        }

        private static PresetFile LoadPresets()
        {
            try
            {
                if (File.Exists(PresetPath))
                    return JsonUtility.FromJson<PresetFile>(File.ReadAllText(PresetPath)) ?? new PresetFile();
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not read thumbnail presets: " + e.Message);
            }

            return new PresetFile();
        }

        private static void SavePresets(PresetFile file)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(PresetPath));
            File.WriteAllText(PresetPath, JsonUtility.ToJson(file, true));
        }

        private WPFMAThumbnailSettings LoadLast()
        {
            string json = EditorPrefs.GetString(SettingsKey, string.Empty);
            if (string.IsNullOrEmpty(json))
                return null;

            try
            {
                return JsonUtility.FromJson<WPFMAThumbnailSettings>(json);
            }
            catch (Exception)
            {
                return null;
            }
        }

        private void SaveLast()
        {
            if (settings != null)
                EditorPrefs.SetString(SettingsKey, JsonUtility.ToJson(settings));
        }
    }

    internal static class WPFMAThumbnailSection
    {
        private const string PrefKey = "WPFMA.Tools.ThumbnailExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Thumbnail studio", "opens its own window", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Make an upload picture.", "Makes an upload picture for the avatar: framing, lighting, a background, glow, outline and shadow, " + "colour effects, plus your own text, images and shapes on top. Save the look as a preset to reuse it."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            if (WPFMA.Editor.WPFMAInstaller.PanelKind == WPFMA.Editor.WPFMAInstaller.ProjectKind.Worlds)
            {
                if (GUILayout.Button("Open Thumbnail Studio (Scene view)", GUILayout.Height(26f)))
                    EditorApplication.delayCall += WPFMAThumbnailStudio.OpenForScene;
                return;
            }

            if (GUILayout.Button("Open Thumbnail Studio", GUILayout.Height(26f)))
            {
                var avatar = WPFMAAvatarFolders.AvatarRoot(Selection.activeGameObject);
                EditorApplication.delayCall += () => WPFMAThumbnailStudio.Open(avatar);
            }
        }
    }
}
#endif
