// 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 UnityEditor.Animations;
using UnityEngine;

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
#endif

namespace WPFMA
{
#if WPFMA_VRC_AVATARS
    /// <summary>
    /// A 2D mouth that talks: a sprite sheet cut into frames, one material per frame, and an FX layer that swaps the
    /// mouth's material from VRChat's built-in Viseme parameter (which mouth shape you're making) or Voice parameter
    /// (how loud you are). Both are synced by VRChat itself, so it costs no parameter bits and needs no scripts.
    /// Whole materials are swapped instead of animating the texture's tiling, so it works with any shader, locked
    /// Poiyomi included.
    /// </summary>
    internal static class WPFMASpriteMouth
    {
        internal enum Mode
        {
            Visemes,
            Loudness
        }

        /// <summary>VRChat's visemes, in the order of its Viseme parameter (0-14), with a hint of the sound.</summary>
        internal static readonly string[] VisemeNames =
        {
            "sil (silent)", "PP (p, b, m)", "FF (f, v)", "TH (th)", "DD (d, t)", "kk (k, g)", "CH (ch, j, sh)", "SS (s, z)",
            "nn (n, l)", "RR (r)", "aa (a in 'car')", "E (e in 'bed')", "ih (i in 'sit')", "oh (o in 'go')", "ou (oo in 'you')"
        };

        internal sealed class Request
        {
            public VRCAvatarDescriptor Avatar;
            public Texture2D Sheet;
            public int Columns = 4;
            public int Rows = 1;
            public int Frames = 4;
            public bool UseSprites = true;
            public Mode Mode = Mode.Visemes;
            /// <summary>For Visemes: the frame each of the 15 visemes shows.</summary>
            public int[] Map = new int[15];
            /// <summary>For Loudness: how loud (VRChat's Voice, 0-1) before the mouth opens.</summary>
            public float TalkStart = 0.05f;
            public Renderer Target;
            public int Slot;
        }

        internal sealed class Result
        {
            public bool Success;
            public string Message;
            public readonly List<string> Notes = new List<string>();
            public readonly List<string> Created = new List<string>();
        }

        // ---- Frames -----------------------------------------------------------------------------------------------

        /// <summary>The sprites cut in Unity's Sprite Editor, in the order they're named (frame_0, frame_1...).</summary>
        internal static List<Sprite> Sprites(Texture2D sheet)
        {
            if (sheet == null)
                return new List<Sprite>();
            return AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(sheet)).OfType<Sprite>()
                .OrderBy(s => s.name.Length).ThenBy(s => s.name, StringComparer.OrdinalIgnoreCase).ToList();
        }

        /// <summary>Each frame's place on the sheet, as a 0-1 rectangle (bottom-left origin), in reading order.</summary>
        internal static List<Rect> FrameRects(Request request)
        {
            var rects = new List<Rect>();
            var sheet = request.Sheet;
            if (sheet == null)
                return rects;

            var sprites = request.UseSprites ? Sprites(sheet) : new List<Sprite>();
            if (sprites.Count > 1)
            {
                foreach (var sprite in sprites)
                {
                    var r = sprite.rect;
                    rects.Add(new Rect(r.x / sheet.width, r.y / sheet.height, r.width / sheet.width, r.height / sheet.height));
                }
                return rects;
            }

            int columns = Mathf.Max(1, request.Columns), rows = Mathf.Max(1, request.Rows);
            int frames = Mathf.Clamp(request.Frames, 1, columns * rows);
            for (int i = 0; i < frames; i++)
            {
                int column = i % columns, row = i / columns;
                rects.Add(new Rect((float)column / columns, 1f - (float)(row + 1) / rows, 1f / columns, 1f / rows));
            }
            return rects;
        }

        /// <summary>A sensible frame for each viseme: closed for silence, small for most sounds, wide, open and round.</summary>
        internal static int[] DefaultMap(int frames)
        {
            var map = new int[15];
            if (frames >= 15)
            {
                for (int v = 0; v < 15; v++)
                    map[v] = v;
                return map;
            }

            // 0 closed, 1 small, 2 wide, 3 open, 4 round - folded down to however many frames there are.
            int[] kind = { 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 2, 4, 4 };
            int[][] fold =
            {
                new[] { 0, 0, 0, 0, 0 },
                new[] { 0, 1, 1, 1, 1 },
                new[] { 0, 1, 1, 2, 2 },
                new[] { 0, 1, 2, 2, 3 },
                new[] { 0, 1, 2, 3, 4 }
            };
            var row = fold[Mathf.Clamp(frames, 1, 5) - 1];
            for (int v = 0; v < 15; v++)
                map[v] = Mathf.Min(row[kind[v]], frames - 1);
            return map;
        }

        /// <summary>The sheet as a readable copy (works whatever its import settings, without changing them).</summary>
        private static Texture2D ReadableCopy(Texture2D sheet)
        {
            var rt = RenderTexture.GetTemporary(sheet.width, sheet.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
            var previous = RenderTexture.active;
            try
            {
                Graphics.Blit(sheet, rt);
                RenderTexture.active = rt;
                var copy = new Texture2D(sheet.width, sheet.height, TextureFormat.RGBA32, false);
                copy.ReadPixels(new Rect(0, 0, sheet.width, sheet.height), 0, 0);
                copy.Apply();
                return copy;
            }
            finally
            {
                RenderTexture.active = previous;
                RenderTexture.ReleaseTemporary(rt);
            }
        }

        // ---- Building ---------------------------------------------------------------------------------------------

        internal static List<string> Validate(Request request)
        {
            var problems = new List<string>();
            if (request.Avatar == null)
                problems.Add("Select the avatar in the Hierarchy.");
            if (request.Sheet == null)
                problems.Add("Pick the sprite sheet.");
            else if (FrameRects(request).Count < 2)
                problems.Add("The sheet needs at least 2 frames.");
            if (request.Target == null)
                problems.Add("Pick the mouth's renderer, or make a mouth quad.");
            else if (request.Avatar != null && !request.Target.transform.IsChildOf(request.Avatar.transform))
                problems.Add("The mouth has to be inside the avatar.");
            else if (request.Slot < 0 || request.Slot >= Mathf.Max(1, request.Target.sharedMaterials.Length))
                problems.Add("That material slot doesn't exist on the mouth.");
            if (request.Avatar != null)
            {
                var fx = WPFMAToggleCreator.FindFxController(request.Avatar) as AnimatorController;
                if (fx == null || string.IsNullOrEmpty(AssetDatabase.GetAssetPath(fx)))
                    problems.Add("The avatar needs an FX controller saved as an asset. Avatar setup makes one.");
            }
            return problems;
        }

        /// <summary>Puts a quad in front of the face, on the head bone, ready to show the mouth.</summary>
        internal static MeshRenderer MakeQuad(VRCAvatarDescriptor avatar, Texture2D sheet, Rect frame)
        {
            var root = avatar.transform;
            var animator = avatar.GetComponent<Animator>();
            var head = animator != null && animator.isHuman ? animator.GetBoneTransform(HumanBodyBones.Head) : null;

            var quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
            UnityEngine.Object.DestroyImmediate(quad.GetComponent<Collider>());
            quad.name = "Mouth Sprite";
            Undo.RegisterCreatedObjectUndo(quad, "Make mouth quad");

            // Facing the same way as the avatar (Unity's quad faces -Z), on the mouth (or a guess near it).
            quad.transform.rotation = root.rotation * Quaternion.Euler(0f, 180f, 0f);
            float aspect = sheet != null && frame.height > 0f ? frame.width * sheet.width / (frame.height * sheet.height) : 1f;
            quad.transform.localScale = new Vector3(aspect, 1f, 1f);
            PlaceOnMouth(avatar, quad.transform, true);
            // Keeps where it was put, so it follows the head from there.
            Undo.SetTransformParent(quad.transform, head != null ? head : root, "Make mouth quad");
            return quad.GetComponent<MeshRenderer>();
        }

        // Names of a "mouth open" shape, most specific first (VRChat's viseme, MMD's a, common rigs, ARKit).
        private static readonly string[] OpenShapes =
        {
            "vrc.v_aa", "v_aa", "viseme_aa", "aa", "あ", "mth_a", "mouth_a", "mouth_open", "mouthopen", "mouth open", "jawopen", "jaw_open", "a"
        };

        /// <summary>
        /// Where the mouth is: the middle of what the avatar's "aa" (mouth open) shape moves, at the front of the lips.
        /// Also how wide the mouth is. False when the avatar has no mouth shape to go by.
        /// </summary>
        internal static bool FindMouth(VRCAvatarDescriptor avatar, out Vector3 front, out float width, out string how)
        {
            front = Vector3.zero;
            width = 0f;
            how = null;
            if (avatar == null)
                return false;
            var root = avatar.transform;
            var meshes = avatar.GetComponentsInChildren<SkinnedMeshRenderer>(true).Where(s => s.sharedMesh != null && s.sharedMesh.blendShapeCount > 0).ToList();
            if (avatar.VisemeSkinnedMesh != null && meshes.Remove(avatar.VisemeSkinnedMesh))
                meshes.Insert(0, avatar.VisemeSkinnedMesh);

            SkinnedMeshRenderer best = null;
            int bestShape = -1, bestRank = int.MaxValue;
            foreach (var skinned in meshes)
            {
                var mesh = skinned.sharedMesh;
                for (int i = 0; i < mesh.blendShapeCount; i++)
                {
                    int rank = Array.IndexOf(OpenShapes, mesh.GetBlendShapeName(i).Trim().ToLowerInvariant());
                    if (rank >= 0 && rank < bestRank)
                    {
                        best = skinned;
                        bestShape = i;
                        bestRank = rank;
                    }
                }
            }
            if (best == null)
                return false;

            var m = best.sharedMesh;
            var deltas = new Vector3[m.vertexCount];
            m.GetBlendShapeFrameVertices(bestShape, m.GetBlendShapeFrameCount(bestShape) - 1, deltas, null, null);
            float most = 0f;
            foreach (var d in deltas)
                most = Mathf.Max(most, d.sqrMagnitude);
            if (most <= 0f)
                return false;

            // The vertices it moves most (the lips and the inside of the mouth), where they are on the avatar now.
            var baked = new Mesh();
            try
            {
                best.BakeMesh(baked, true);
                var verts = baked.vertices;
                var toWorld = Matrix4x4.TRS(best.transform.position, best.transform.rotation, Vector3.one);
                var points = new List<Vector3>();
                for (int i = 0; i < deltas.Length && i < verts.Length; i++)
                    if (deltas[i].sqrMagnitude >= most * 0.25f)
                        points.Add(toWorld.MultiplyPoint3x4(verts[i]));
                if (points.Count == 0)
                    return false;
                var center = Vector3.zero;
                foreach (var p in points)
                    center += p;
                center /= points.Count;
                float ahead = points.Max(p => Vector3.Dot(p - center, root.forward));
                float left = points.Min(p => Vector3.Dot(p - center, root.right));
                float right = points.Max(p => Vector3.Dot(p - center, root.right));
                front = center + root.forward * ahead;
                width = right - left;
                how = "'" + m.GetBlendShapeName(bestShape) + "' on " + best.name;
                return true;
            }
            finally
            {
                UnityEngine.Object.DestroyImmediate(baked);
            }
        }

        /// <summary>
        /// Moves a mouth quad onto the mouth, just in front of the lips (resize: and makes it as wide as the mouth).
        /// Without a mouth shape to go by, a little below and in front of the eyes. Returns what happened, for the panel.
        /// </summary>
        internal static string PlaceOnMouth(VRCAvatarDescriptor avatar, Transform quad, bool resize)
        {
            var root = avatar.transform;
            float eyes = avatar.ViewPosition.y > 0.01f ? avatar.ViewPosition.y : 1.3f;
            float scale = eyes / 1.3f;
            Vector3 front;
            float width;
            string how;
            bool found = FindMouth(avatar, out front, out width, out how);
            Undo.RecordObject(quad, "Put the mouth on the mouth");
            if (found)
                quad.position = front + root.forward * (0.002f * scale);
            else
                quad.position = root.position + avatar.ViewPosition - root.up * (eyes * 0.05f) + root.forward * (eyes * 0.06f);
            if (resize)
            {
                float size = found && width > 0.005f * scale ? width * 1.4f : eyes * 0.08f;
                var s = quad.lossyScale;
                float aspect = Mathf.Abs(s.y) > 1e-6f ? Mathf.Abs(s.x / s.y) : 1f;
                SetWorldSize(quad, new Vector2(size * aspect, size));
            }
            return found ? "Put it on the mouth (found from " + how + ")." : "No mouth shape found on this avatar, so it's a guess near the mouth. Move it with the arrows.";
        }

        /// <summary>Moves a mouth quad: x left/right as seen in the Scene view, y up/down along the avatar, z out of/into the face.</summary>
        internal static void Nudge(VRCAvatarDescriptor avatar, Transform quad, Vector3 step)
        {
            var root = avatar.transform;
            var view = SceneView.lastActiveSceneView;
            var side = view != null && view.camera != null ? Vector3.ProjectOnPlane(view.camera.transform.right, root.up) : root.right;
            if (side.sqrMagnitude < 1e-6f)
                side = root.right;
            side.Normalize();
            Undo.RecordObject(quad, "Move the mouth");
            quad.position += side * step.x + root.up * step.y + root.forward * step.z;
        }

        internal static void Resize(Transform quad, float factor)
        {
            Undo.RecordObject(quad, "Resize the mouth");
            quad.localScale = new Vector3(quad.localScale.x * factor, quad.localScale.y * factor, quad.localScale.z);
        }

        private static void SetWorldSize(Transform quad, Vector2 size)
        {
            var parent = quad.parent != null ? quad.parent.lossyScale : Vector3.one;
            quad.localScale = new Vector3(size.x / Mathf.Max(1e-6f, Mathf.Abs(parent.x)), size.y / Mathf.Max(1e-6f, Mathf.Abs(parent.y)), quad.localScale.z);
        }

        internal static Result Build(Request request)
        {
            var result = new Result();
            var problems = Validate(request);
            if (problems.Count > 0)
            {
                result.Message = problems[0];
                return result;
            }

            var avatar = request.Avatar;
            var root = avatar.gameObject;
            var fx = (AnimatorController)WPFMAToggleCreator.FindFxController(avatar);
            var rects = FrameRects(request);
            var renderer = request.Target;
            string rendererPath = AnimationUtility.CalculateTransformPath(renderer.transform, root.transform);
            string name = WPFMAPaths.SafeFileName(request.Sheet.name);
            string folder = WPFMAAvatarFolders.For(root) + "/Sprite Mouth/" + name;
            WPFMAAvatarFolders.Ensure(folder);

            // 1. One picture per frame, cut from the sheet.
            var frames = new List<Texture2D>();
            var copy = ReadableCopy(request.Sheet);
            var sheetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(request.Sheet)) as TextureImporter;
            try
            {
                for (int i = 0; i < rects.Count; i++)
                {
                    var r = rects[i];
                    int x = Mathf.RoundToInt(r.x * copy.width), y = Mathf.RoundToInt(r.y * copy.height);
                    int w = Mathf.Max(1, Mathf.RoundToInt(r.width * copy.width)), h = Mathf.Max(1, Mathf.RoundToInt(r.height * copy.height));
                    w = Mathf.Min(w, copy.width - x);
                    h = Mathf.Min(h, copy.height - y);
                    var frame = new Texture2D(w, h, TextureFormat.RGBA32, false);
                    frame.SetPixels(copy.GetPixels(x, y, w, h));
                    frame.Apply();
                    string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + name + " " + (i + 1) + ".png");
                    File.WriteAllBytes(path, frame.EncodeToPNG());
                    UnityEngine.Object.DestroyImmediate(frame);
                    result.Created.Add(path);
                }
            }
            finally
            {
                UnityEngine.Object.DestroyImmediate(copy);
            }

            foreach (var path in result.Created.ToList())
            {
                AssetDatabase.ImportAsset(path);
                var importer = (TextureImporter)AssetImporter.GetAtPath(path);
                importer.alphaIsTransparency = true;
                importer.wrapMode = TextureWrapMode.Clamp;
                importer.npotScale = TextureImporterNPOTScale.None;
                importer.filterMode = sheetImporter != null ? sheetImporter.filterMode : FilterMode.Bilinear;
                importer.SaveAndReimport();
                frames.Add(AssetDatabase.LoadAssetAtPath<Texture2D>(path));
            }

            // 2. One material per frame: a copy of the mouth's own material (so its shader and settings stay), showing that frame.
            var materials = renderer.sharedMaterials;
            var baseMaterial = request.Slot < materials.Length ? materials[request.Slot] : null;
            var shader = baseMaterial != null ? baseMaterial.shader : Shader.Find("Unlit/Transparent");
            var frameMaterials = new List<Material>();
            for (int i = 0; i < frames.Count; i++)
            {
                var material = baseMaterial != null ? new Material(baseMaterial) : new Material(shader);
                material.name = name + " " + (i + 1);
                material.mainTexture = frames[i];
                if (material.HasProperty("_MainTex"))
                {
                    material.SetTexture("_MainTex", frames[i]);
                    material.SetTextureScale("_MainTex", Vector2.one);
                    material.SetTextureOffset("_MainTex", Vector2.zero);
                }
                string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + material.name + ".mat");
                AssetDatabase.CreateAsset(material, path);
                result.Created.Add(path);
                frameMaterials.Add(material);
            }

            // 3. A clip per frame that puts its material on the mouth's slot.
            var type = renderer.GetType();
            var clips = new List<AnimationClip>();
            for (int i = 0; i < frameMaterials.Count; i++)
            {
                var clip = new AnimationClip { name = name + " " + (i + 1) };
                var binding = EditorCurveBinding.PPtrCurve(rendererPath, type, "m_Materials.Array.data[" + request.Slot + "]");
                AnimationUtility.SetObjectReferenceCurve(clip, binding, new[] { new ObjectReferenceKeyframe { time = 0f, value = frameMaterials[i] } });
                string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + clip.name + ".anim");
                AssetDatabase.CreateAsset(clip, path);
                result.Created.Add(path);
                clips.Add(clip);
            }

            // 4. The layer: a state per frame, picked by VRChat's Viseme or Voice parameter.
            Undo.RegisterCompleteObjectUndo(fx, "Sprite mouth");
            bool writeDefaults = MostlyWriteDefaults(fx);
            var machine = new AnimatorStateMachine { name = "WPFMA Mouth", hideFlags = HideFlags.HideInHierarchy };
            AssetDatabase.AddObjectToAsset(machine, fx);
            var states = new List<AnimatorState>();
            for (int i = 0; i < clips.Count; i++)
            {
                var state = machine.AddState("Frame " + (i + 1), new Vector3(300f, 60f * i, 0f));
                state.motion = clips[i];
                state.writeDefaultValues = writeDefaults;
                states.Add(state);
            }

            if (request.Mode == Mode.Visemes)
            {
                AddParameter(fx, "Viseme", AnimatorControllerParameterType.Int);
                var map = request.Map != null && request.Map.Length == 15 ? request.Map : DefaultMap(states.Count);
                machine.defaultState = states[Mathf.Clamp(map[0], 0, states.Count - 1)];
                for (int v = 0; v < 15; v++)
                {
                    var transition = machine.AddAnyStateTransition(states[Mathf.Clamp(map[v], 0, states.Count - 1)]);
                    Instant(transition);
                    transition.AddCondition(AnimatorConditionMode.Equals, v, "Viseme");
                }
            }
            else
            {
                // Frame 1 is closed, the last fully open; the ones between open up as the voice gets louder.
                AddParameter(fx, "Voice", AnimatorControllerParameterType.Float);
                machine.defaultState = states[0];
                float start = Mathf.Clamp(request.TalkStart, 0.005f, 0.9f), loudest = Mathf.Max(start + 0.05f, 0.6f);
                for (int i = 0; i < states.Count; i++)
                {
                    float from = i == 0 ? -1f : start + (loudest - start) * (i - 1) / Mathf.Max(1, states.Count - 2);
                    float to = i == states.Count - 1 ? 2f : start + (loudest - start) * i / Mathf.Max(1, states.Count - 2);
                    var transition = machine.AddAnyStateTransition(states[i]);
                    Instant(transition);
                    if (i > 0)
                        transition.AddCondition(AnimatorConditionMode.Greater, from, "Voice");
                    if (i < states.Count - 1)
                        transition.AddCondition(AnimatorConditionMode.Less, to, "Voice");
                }
            }

            string layerName = "WPFMA Mouth";
            for (int n = 2; fx.layers.Any(l => l.name == layerName); n++)
                layerName = "WPFMA Mouth " + n;
            fx.AddLayer(new AnimatorControllerLayer { name = layerName, defaultWeight = 1f, stateMachine = machine });
            EditorUtility.SetDirty(fx);

            // 5. The mouth starts on the silent frame, and VRChat has to be sending visemes.
            Undo.RecordObject(renderer, "Sprite mouth");
            var shown = renderer.sharedMaterials;
            if (shown.Length == 0)
                shown = new Material[1];
            shown[Mathf.Clamp(request.Slot, 0, shown.Length - 1)] = frameMaterials[states.IndexOf(machine.defaultState)];
            renderer.sharedMaterials = shown;
            PrefabUtility.RecordPrefabInstancePropertyModifications(renderer);

            if (request.Mode == Mode.Visemes &&
                avatar.lipSync != VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.VisemeBlendShape &&
                avatar.lipSync != VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.VisemeParameterOnly)
            {
                Undo.RecordObject(avatar, "Sprite mouth");
                avatar.lipSync = VRC.SDKBase.VRC_AvatarDescriptor.LipSyncStyle.VisemeParameterOnly;
                EditorUtility.SetDirty(avatar);
                PrefabUtility.RecordPrefabInstancePropertyModifications(avatar);
                result.Notes.Add("Lip sync set to Viseme Parameter Only, so VRChat sends the mouth shapes.");
            }

            AssetDatabase.SaveAssets();
            result.Success = true;
            result.Message = "Made a talking mouth from " + frames.Count + " frames (" + (request.Mode == Mode.Visemes ? "visemes" : "loudness") +
                             ") on '" + renderer.name + "'. Files are in " + folder + ".";
            if (shader != null && !shader.name.StartsWith("VRChat/Mobile/", StringComparison.Ordinal))
                result.Notes.Add("For a Quest version, the mouth's material needs a VRChat/Mobile shader.");
            return result;
        }

        private static void Instant(AnimatorStateTransition transition)
        {
            transition.hasExitTime = false;
            transition.hasFixedDuration = true;
            transition.duration = 0f;
            transition.canTransitionToSelf = false;
        }

        private static void AddParameter(AnimatorController controller, string name, AnimatorControllerParameterType type)
        {
            if (!controller.parameters.Any(p => p.name == name))
                controller.AddParameter(name, type);
        }

        /// <summary>Whether most of the controller's states write defaults (new states match, so it doesn't mix).</summary>
        private static bool MostlyWriteDefaults(AnimatorController controller)
        {
            int on = 0, off = 0;
            foreach (var layer in controller.layers)
            {
                if (layer.stateMachine == null)
                    continue;
                foreach (var child in layer.stateMachine.states)
                {
                    if (child.state == null || (child.state.motion is BlendTree && ((BlendTree)child.state.motion).blendType == BlendTreeType.Direct))
                        continue;
                    if (child.state.writeDefaultValues)
                        on++;
                    else
                        off++;
                }
            }
            return on > off;
        }
    }
#endif

    internal static class WPFMASpriteMouthSection
    {
        private const string PrefKey = "WPFMA.Tools.SpriteMouthExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;
            WPFMAToolSection.Draw(sectionStyle, "Sprite mouth", Detail(), PrefKey, Body);
        }

#if !WPFMA_VRC_AVATARS
        private static string Detail()
        {
            return "needs the avatar SDK";
        }

        private static void Body()
        {
            EditorGUILayout.HelpBox("This needs the VRChat avatar SDK, which is not in this project yet.", MessageType.Info);
        }
#else
        private static readonly WPFMASpriteMouth.Request Request = new WPFMASpriteMouth.Request();
        private static Texture2D mappedFor;
        private static int mappedFrames = -1;
        private static bool showMap;
        private static string status;
        private static bool statusIsError;
        private static List<string> notes = new List<string>();

        private static string Detail()
        {
            return Request.Sheet == null ? "no sheet picked" : Request.Sheet.name;
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("A 2D mouth that talks.", "Makes a 2D mouth talk: pick a sprite sheet of mouth frames, and the mouth changes with what you say (visemes) " + "or how loud you are. It uses VRChat's own Viseme and Voice parameters, so it costs no parameter bits."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var active = Selection.activeGameObject;
            var selected = active != null && !EditorUtility.IsPersistent(active) ? active.GetComponentInParent<VRCAvatarDescriptor>() : null;
            if (selected != null)
                Request.Avatar = selected;
            Request.Avatar = (VRCAvatarDescriptor)EditorGUILayout.ObjectField("Avatar", Request.Avatar, typeof(VRCAvatarDescriptor), true);

            Request.Sheet = (Texture2D)EditorGUILayout.ObjectField("Sprite sheet", Request.Sheet, typeof(Texture2D), false);
            if (Request.Sheet == null)
            {
                EditorGUILayout.LabelField(new GUIContent("A PNG of mouth frames.", "A PNG with the mouth frames side by side (or in a grid), like closed, half open, open and round."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            var sprites = WPFMASpriteMouth.Sprites(Request.Sheet);
            if (sprites.Count > 1)
                Request.UseSprites = EditorGUILayout.ToggleLeft("Use the " + sprites.Count + " sprites cut in Unity's Sprite Editor", Request.UseSprites);
            if (sprites.Count <= 1 || !Request.UseSprites)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    Request.Columns = Mathf.Clamp(EditorGUILayout.IntField("Columns", Request.Columns), 1, 64);
                    Request.Rows = Mathf.Clamp(EditorGUILayout.IntField("Rows", Request.Rows), 1, 64);
                }
                Request.Frames = Mathf.Clamp(EditorGUILayout.IntField("Frames", Mathf.Min(Request.Frames, Request.Columns * Request.Rows)), 1, Request.Columns * Request.Rows);
                if (GUILayout.Button("Guess from the picture's shape", EditorStyles.miniButton, GUILayout.Width(200f)))
                    Guess();
            }

            var rects = WPFMASpriteMouth.FrameRects(Request);
            DrawFrames(rects);

            EditorGUILayout.Space(4f);
            Request.Mode = (WPFMASpriteMouth.Mode)EditorGUILayout.EnumPopup("Moves with", Request.Mode);
            if (Request.Sheet != mappedFor || rects.Count != mappedFrames)
            {
                mappedFor = Request.Sheet;
                mappedFrames = rects.Count;
                Request.Map = WPFMASpriteMouth.DefaultMap(rects.Count);
            }

            if (Request.Mode == WPFMASpriteMouth.Mode.Visemes)
                DrawMap(rects);
            else
            {
                EditorGUILayout.LabelField(new GUIContent("Frame 1 quiet, the last one loudest.", "Frame 1 shows when you're quiet and the last one when you're loudest, the rest in between."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                Request.TalkStart = EditorGUILayout.Slider("Opens at loudness", Request.TalkStart, 0.01f, 0.5f);
            }

            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                Request.Target = (Renderer)EditorGUILayout.ObjectField("Mouth", Request.Target, typeof(Renderer), true);
                using (new EditorGUI.DisabledScope(Request.Avatar == null))
                {
                    if (GUILayout.Button("Make a mouth quad", GUILayout.Width(140f)))
                    {
                        var avatar = Request.Avatar;
                        var first = rects.Count > 0 ? rects[0] : new Rect(0, 0, 1, 1);
                        Request.Target = WPFMASpriteMouth.MakeQuad(avatar, Request.Sheet, first);
                        Request.Slot = 0;
                        Selection.activeGameObject = Request.Target.gameObject;
                        status = "Made a mouth quad on the mouth. Fine-tune it with Place it if needed, then press Make it talk.";
                        statusIsError = false;
                    }
                }
            }
            DrawPlacement();
            if (Request.Target != null && Request.Target.sharedMaterials.Length > 1)
                Request.Slot = EditorGUILayout.Popup("Material slot", Mathf.Clamp(Request.Slot, 0, Request.Target.sharedMaterials.Length - 1),
                    Request.Target.sharedMaterials.Select((m, i) => i + ": " + (m != null ? m.name : "(empty)")).ToArray());
            else
                Request.Slot = 0;

            var problems = WPFMASpriteMouth.Validate(Request);
            foreach (var problem in problems.Take(2))
                EditorGUILayout.LabelField(problem, WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));

            using (new EditorGUI.DisabledScope(problems.Count > 0))
            {
                if (GUILayout.Button("Make it talk", GUILayout.Height(26f)))
                {
                    EditorApplication.delayCall += () =>
                    {
                        var fx = WPFMAToggleCreator.FindFxController(Request.Avatar);
                        WPFMASpriteMouth.Result result = null;
                        WPFMAChangeLog.Run("Sprite mouth", "Make a talking mouth on '" + Request.Avatar.name + "'",
                            new[] { AssetDatabase.GetAssetPath(fx) }, true,
                            () => (result = WPFMASpriteMouth.Build(Request)).Message, () => result != null ? result.Created : null);
                        status = result.Message;
                        statusIsError = !result.Success;
                        notes = result.Notes;
                        Debug.Log("[WPFMA-SDK] " + status);
                    };
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(statusIsError ? WPFMAToolSection.WarnAmber : WPFMAToolSection.OkGreen));
            foreach (var note in notes)
                EditorGUILayout.LabelField(note, WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            EditorGUILayout.LabelField(new GUIContent("Test with Gesture Manager's sliders.", "Test it in Play mode with Gesture Manager: its Viseme and Voice sliders move the mouth."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        private static readonly string[] StepNames = { "1 mm", "5 mm", "1 cm" };
        private static readonly float[] Steps = { 0.001f, 0.005f, 0.01f };
        private static int stepIndex = 1;

        /// <summary>Buttons to put the mouth where it belongs: onto the mouth, nudges, and size.</summary>
        private static void DrawPlacement()
        {
            if (Request.Target == null || Request.Avatar == null || !Request.Target.transform.IsChildOf(Request.Avatar.transform))
                return;
            var quad = Request.Target.transform;
            float step = Steps[stepIndex] * (Request.Avatar.ViewPosition.y > 0.01f ? Request.Avatar.ViewPosition.y / 1.3f : 1f);
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.PrefixLabel(new GUIContent("Place it", "Move the mouth onto the face. Arrows go left/right as you see it in the Scene view; Out/In move it off or into the face."));
                if (GUILayout.Button(new GUIContent("Put on the mouth", "Finds the mouth from the avatar's mouth-open shape and puts it just in front of the lips."), EditorStyles.miniButtonLeft))
                {
                    status = WPFMASpriteMouth.PlaceOnMouth(Request.Avatar, quad, false);
                    statusIsError = false;
                }
                if (GUILayout.Button("Select it", EditorStyles.miniButtonRight, GUILayout.Width(70f)))
                {
                    Selection.activeGameObject = quad.gameObject;
                    if (SceneView.lastActiveSceneView != null)
                        SceneView.lastActiveSceneView.Frame(new Bounds(quad.position, quad.lossyScale * 3f), false);
                }
                stepIndex = EditorGUILayout.Popup(stepIndex, StepNames, GUILayout.Width(60f));
            }
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Space(EditorGUIUtility.labelWidth + 2f);
                if (GUILayout.Button(new GUIContent("\u25B2", "Up"), EditorStyles.miniButtonLeft, GUILayout.Width(30f)))
                    WPFMASpriteMouth.Nudge(Request.Avatar, quad, new Vector3(0f, step, 0f));
                if (GUILayout.Button(new GUIContent("\u25BC", "Down"), EditorStyles.miniButtonMid, GUILayout.Width(30f)))
                    WPFMASpriteMouth.Nudge(Request.Avatar, quad, new Vector3(0f, -step, 0f));
                if (GUILayout.Button(new GUIContent("\u25C0", "Left (as seen in the Scene view)"), EditorStyles.miniButtonMid, GUILayout.Width(30f)))
                    WPFMASpriteMouth.Nudge(Request.Avatar, quad, new Vector3(-step, 0f, 0f));
                if (GUILayout.Button(new GUIContent("\u25B6", "Right (as seen in the Scene view)"), EditorStyles.miniButtonMid, GUILayout.Width(30f)))
                    WPFMASpriteMouth.Nudge(Request.Avatar, quad, new Vector3(step, 0f, 0f));
                if (GUILayout.Button(new GUIContent("Out", "Off the face, toward the front"), EditorStyles.miniButtonMid, GUILayout.Width(40f)))
                    WPFMASpriteMouth.Nudge(Request.Avatar, quad, new Vector3(0f, 0f, step));
                if (GUILayout.Button(new GUIContent("In", "Into the face"), EditorStyles.miniButtonRight, GUILayout.Width(40f)))
                    WPFMASpriteMouth.Nudge(Request.Avatar, quad, new Vector3(0f, 0f, -step));
                GUILayout.Space(8f);
                if (GUILayout.Button("Smaller", EditorStyles.miniButtonLeft, GUILayout.Width(56f)))
                    WPFMASpriteMouth.Resize(quad, 1f / 1.1f);
                if (GUILayout.Button("Bigger", EditorStyles.miniButtonRight, GUILayout.Width(56f)))
                    WPFMASpriteMouth.Resize(quad, 1.1f);
            }
        }

        /// <summary>A strip of square-ish frames is one row; otherwise the closest grid of square frames.</summary>
        private static void Guess()
        {
            var sheet = Request.Sheet;
            if (sheet == null || sheet.height == 0)
                return;
            float ratio = (float)sheet.width / sheet.height;
            if (ratio >= 1f)
            {
                Request.Columns = Mathf.Max(1, Mathf.RoundToInt(ratio));
                Request.Rows = 1;
            }
            else
            {
                Request.Columns = 1;
                Request.Rows = Mathf.Max(1, Mathf.RoundToInt(1f / ratio));
            }
            Request.Frames = Request.Columns * Request.Rows;
        }

        private static void DrawFrames(List<Rect> rects)
        {
            if (rects.Count == 0)
                return;
            float size = 52f;
            int perRow = Mathf.Max(1, Mathf.FloorToInt((EditorGUIUtility.currentViewWidth - 60f) / (size + 6f)));
            for (int start = 0; start < rects.Count; start += perRow)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    for (int i = start; i < Mathf.Min(rects.Count, start + perRow); i++)
                    {
                        var box = GUILayoutUtility.GetRect(size, size + 14f, GUILayout.Width(size), GUILayout.Height(size + 14f));
                        var picture = new Rect(box.x, box.y, size, size);
                        EditorGUI.DrawRect(picture, WPFMAToolSection.ToolbarBackground);
                        GUI.DrawTextureWithTexCoords(picture, Request.Sheet, rects[i], true);
                        GUI.Label(new Rect(box.x, box.y + size, size, 14f), (i + 1).ToString(),
                            new GUIStyle(EditorStyles.miniLabel) { alignment = TextAnchor.MiddleCenter });
                        GUILayout.Space(6f);
                    }
                }
            }
        }

        private static void DrawMap(List<Rect> rects)
        {
            var labels = Enumerable.Range(1, rects.Count).Select(i => "Frame " + i).ToArray();
            showMap = EditorGUILayout.Foldout(showMap, "Which frame each mouth shape shows", true);
            if (!showMap)
            {
                EditorGUILayout.LabelField(new GUIContent("Set for you. Open to change.", "Set for you: closed when silent, small for most sounds, open for 'a', round for 'o' and 'oo'."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            for (int v = 0; v < 15; v++)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    Request.Map[v] = EditorGUILayout.Popup(WPFMASpriteMouth.VisemeNames[v], Mathf.Clamp(Request.Map[v], 0, rects.Count - 1), labels);
                    var thumb = GUILayoutUtility.GetRect(18f, 18f, GUILayout.Width(18f));
                    GUI.DrawTextureWithTexCoords(thumb, Request.Sheet, rects[Mathf.Clamp(Request.Map[v], 0, rects.Count - 1)], true);
                }
            }
            if (GUILayout.Button("Back to the automatic choice", EditorStyles.miniButton, GUILayout.Width(190f)))
                Request.Map = WPFMASpriteMouth.DefaultMap(rects.Count);
        }
#endif
    }
}
#endif
