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

namespace WPFMA.Team
{
    /// <summary>
    /// How teammates see you in their Scene view: one of the built-in shapes (in your own colour if you like), with
    /// an optional hat and face item. Only names and a colour are sent, and everything is drawn from shapes built into
    /// the SDK. There is deliberately no "your own model" option: a model from someone's project is something a bad
    /// actor could use to put anything on a teammate's screen.
    /// </summary>
    [InitializeOnLoad]
    internal static class TeamLook
    {
        internal static readonly string[] Shapes = { "Ball", "Cube", "Cone", "Cylinder", "Camera" };
        internal static readonly string[] Hats = { "None", "Top hat", "Party hat", "Crown", "Halo", "Cap", "Beanie", "Antenna", "Horns" };
        internal static readonly string[] Faces = { "None", "Sunglasses", "Round glasses", "Googly eyes", "Mustache", "Clown nose", "Monocle", "Eye patch" };

        private const string ShapeKey = "WPFMA.Team.Look.Shape";
        private const string ColorKey = "WPFMA.Team.Look.Color";
        private const string HatKey = "WPFMA.Team.Look.Hat";
        private const string FaceKey = "WPFMA.Team.Look.Face";

        // Dragging the colour picker changes the colour many times a second; send at most a few times a second.
        private static bool pending;
        private static double lastSent;

        static TeamLook()
        {
            AssemblyReloadEvents.beforeAssemblyReload += ReleasePreview;
            EditorApplication.quitting += ReleasePreview;
            EditorApplication.update += () =>
            {
                if (!pending || EditorApplication.timeSinceStartup - lastSent < 0.3)
                    return;
                pending = false;
                lastSent = EditorApplication.timeSinceStartup;
                if (TeamSession.State == TeamState.Connected)
                    TeamSession.Send(Message());
            };
        }

        internal static string Shape
        {
            get { return Pick(EditorPrefs.GetString(ShapeKey, Shapes[0]), Shapes); }
            set
            {
                if (value == Shape)
                    return;
                EditorPrefs.SetString(ShapeKey, value);
                pending = true;
            }
        }

        internal static string Hat
        {
            get { return Pick(EditorPrefs.GetString(HatKey, Hats[0]), Hats); }
            set
            {
                if (value == Hat)
                    return;
                EditorPrefs.SetString(HatKey, value);
                pending = true;
            }
        }

        internal static string Face
        {
            get { return Pick(EditorPrefs.GetString(FaceKey, Faces[0]), Faces); }
            set
            {
                if (value == Face)
                    return;
                EditorPrefs.SetString(FaceKey, value);
                pending = true;
            }
        }

        /// <summary>Your shape's colour; null means your teammate colour (each teammate's own colour for you).</summary>
        internal static Color? ShapeColor
        {
            get { return ParseColor(EditorPrefs.GetString(ColorKey, string.Empty)); }
            set
            {
                string text = value.HasValue ? "#" + ColorUtility.ToHtmlStringRGB(value.Value) : string.Empty;
                if (text == EditorPrefs.GetString(ColorKey, string.Empty))
                    return;
                EditorPrefs.SetString(ColorKey, text);
                pending = true;
            }
        }

        // Anything a teammate sends that isn't one of the built-in choices becomes the default.
        private static string Pick(string value, string[] options)
        {
            return Array.IndexOf(options, value) >= 0 ? value : options[0];
        }

        private static Color? ParseColor(string text)
        {
            Color color;
            return !string.IsNullOrEmpty(text) && ColorUtility.TryParseHtmlString(text, out color) ? (Color?)new Color(color.r, color.g, color.b, 1f) : null;
        }

        internal static TeamMessage Message()
        {
            return new TeamMessage { t = "look", m = Shape, h = EditorPrefs.GetString(ColorKey, string.Empty), d = Hat, s = Face };
        }

        internal static void Receive(TeamPeer peer, TeamMessage message)
        {
            peer.LookShape = Pick(message.m, Shapes);
            peer.LookColor = ParseColor(message.h);
            peer.LookHat = Pick(message.d, Hats);
            peer.LookFace = Pick(message.s, Faces);
            TeamView.Repaint();
        }

        /// <summary>Queues the teammate's shape, arrow, hat and face item for the Scene view camera, before it renders.</summary>
        internal static void DrawMarker(TeamPeer peer, Vector3 position, Quaternion rotation, float size, Camera camera)
        {
            if (camera == null)
                return;
            Submit(peer, position, rotation, size, (mesh, matrix, material, sub, block) =>
                Graphics.DrawMesh(mesh, matrix, material, 0, camera, sub, block));
        }

        private delegate void MeshDraw(Mesh mesh, Matrix4x4 matrix, Material material, int sub, MaterialPropertyBlock block);

        private static void Submit(TeamPeer peer, Vector3 position, Quaternion rotation, float size, MeshDraw draw)
        {
            DrawShapeMesh(peer.LookShape, position, rotation, size, peer.LookColor ?? peer.Color, draw);
            DrawArrowMesh(position, rotation, size * 1.6f, Accent(peer), draw);

            if (peer.LookHat != null && peer.LookHat != "None")
                DrawHat(peer.LookHat, position + Vector3.up * size * 0.45f, Quaternion.Euler(0f, rotation.eulerAngles.y, 0f), size * 0.8f, Accent(peer), draw);

            if (peer.LookFace != null && peer.LookFace != "None")
            {
                Vector3 centre;
                float width;
                FaceSpot(peer, position, rotation, size, out centre, out width);
                DrawFace(peer.LookFace, centre, rotation, width, draw);
            }
        }

        /// <summary>How far the label must sit above the marker's centre to clear the shape and hat.</summary>
        internal static float LabelHeight(TeamPeer peer, float size)
        {
            float top = size * 0.5f;
            if (peer.LookHat != null && peer.LookHat != "None")
                top = Mathf.Max(top, size * 0.45f + size * 0.8f * (HatTop(peer.LookHat) + 0.05f));
            return top;
        }

        /// <summary>The colour of their arrow and hat: the shape colour they picked, else their teammate colour.</summary>
        internal static Color Accent(TeamPeer peer)
        {
            return peer.LookColor ?? peer.Color;
        }

        // ---- Hats ---------------------------------------------------------------------------------------------------
        // Built from a few simple meshes, so every teammate can draw them without any file. Sizes are in "widths":
        // one width is the size of the head (or shape) the hat sits on. Accent is your shape colour, or your teammate
        // colour when you haven't picked one.

        private static readonly Dictionary<string, Mesh> hatMeshes = new Dictionary<string, Mesh>();
        private static Material paint;
        private static Material glow;

        private static readonly Color HatBlack = new Color(0.06f, 0.06f, 0.07f);
        private static readonly Color Gold = new Color(1f, 0.78f, 0.25f);
        private static readonly Color White = new Color(0.95f, 0.95f, 0.95f);
        private static readonly Color HornRed = new Color(0.55f, 0.07f, 0.07f);
        private static readonly Color Stalk = new Color(0.3f, 0.3f, 0.33f);

        /// <summary>How far above where it sits each hat reaches, in widths, so the name clears it.</summary>
        private static float HatTop(string hat)
        {
            switch (hat)
            {
                case "Top hat": return 0.9f;
                case "Party hat": return 1.15f;
                case "Crown": return 0.6f;
                case "Halo": return 0.45f;
                case "Cap": return 0.35f;
                case "Beanie": return 0.65f;
                case "Antenna": return 0.85f;
                case "Horns": return 0.45f;
                default: return 0f;
            }
        }

        private static void DrawHat(string hat, Vector3 at, Quaternion yaw, float w, Color accent, MeshDraw draw)
        {
            Action<string, Vector3, Quaternion, Vector3, Color, bool> part = (mesh, offset, turn, scale, color, lit) =>
            {
                var block = new MaterialPropertyBlock();
                block.SetColor("_Color", color);
                if (lit)
                    block.SetColor("_EmissionColor", color * 1.5f);
                draw(HatMesh(mesh), Matrix4x4.TRS(at + yaw * (offset * w), yaw * turn, scale * w), lit ? Glow() : Paint(), 0, block);
            };
            var none = Quaternion.identity;
            var darker = Color.Lerp(accent, Color.black, 0.3f);

            switch (hat)
            {
                case "Top hat":
                    part("cylinder", Vector3.zero, none, new Vector3(1f, 0.05f, 1f), HatBlack, false);
                    part("cylinder", Vector3.up * 0.05f, none, new Vector3(0.6f, 0.85f, 0.6f), HatBlack, false);
                    part("cylinder", Vector3.up * 0.06f, none, new Vector3(0.62f, 0.16f, 0.62f), accent, false);
                    break;
                case "Party hat":
                {
                    var tilt = Quaternion.Euler(0f, 0f, -12f);
                    part("cone", Vector3.zero, tilt, new Vector3(0.7f, 1f, 0.7f), accent, false);
                    part("cylinder", Vector3.zero, tilt, new Vector3(0.72f, 0.08f, 0.72f), White, false);
                    part("sphere", tilt * Vector3.up * 1.02f, none, Vector3.one * 0.18f, White, false);
                    break;
                }
                case "Crown":
                    part("cylinder", Vector3.zero, none, new Vector3(0.76f, 0.3f, 0.76f), Gold, false);
                    for (int i = 0; i < 5; i++)
                    {
                        var round = Quaternion.Euler(0f, i * 72f, 0f);
                        part("cone", round * new Vector3(0f, 0.28f, 0.33f), none, new Vector3(0.17f, 0.3f, 0.17f), Gold, false);
                        part("sphere", round * new Vector3(0f, 0.6f, 0.33f), none, Vector3.one * 0.07f, Gold, false);
                    }
                    part("sphere", new Vector3(0f, 0.15f, 0.38f), none, Vector3.one * 0.11f, accent, false);
                    break;
                case "Halo":
                    part("torus", Vector3.up * 0.35f, none, Vector3.one * 0.8f, Gold, true);
                    break;
                case "Cap":
                    part("dome", Vector3.zero, none, new Vector3(0.82f, 0.32f, 0.82f), accent, false);
                    part("cylinder", new Vector3(0f, 0f, 0.36f), none, new Vector3(0.6f, 0.03f, 0.55f), darker, false);
                    part("sphere", Vector3.up * 0.32f, none, Vector3.one * 0.07f, darker, false);
                    break;
                case "Beanie":
                    part("dome", Vector3.zero, none, new Vector3(0.84f, 0.42f, 0.84f), accent, false);
                    part("cylinder", Vector3.zero, none, new Vector3(0.87f, 0.12f, 0.87f), darker, false);
                    part("sphere", Vector3.up * 0.5f, none, Vector3.one * 0.24f, White, false);
                    break;
                case "Antenna":
                    part("cylinder", Vector3.zero, none, new Vector3(0.05f, 0.7f, 0.05f), Stalk, false);
                    part("sphere", Vector3.up * 0.75f, none, Vector3.one * 0.2f, accent, true);
                    break;
                case "Horns":
                    part("cone", new Vector3(-0.26f, -0.04f, 0f), Quaternion.Euler(0f, 0f, 25f), new Vector3(0.2f, 0.45f, 0.2f), HornRed, false);
                    part("cone", new Vector3(0.26f, -0.04f, 0f), Quaternion.Euler(0f, 0f, -25f), new Vector3(0.2f, 0.45f, 0.2f), HornRed, false);
                    break;
            }
        }

        // ---- Shape and arrow as meshes ------------------------------------------------------------------------------
        // Drawn in the same render as hats and face items, so whatever is in front really is in front.

        // The shape and arrow glow in their colour, so they're bright even in a dark scene, with a little shading
        // left so they still look round.
        private static void Piece(MeshDraw draw, string mesh, Matrix4x4 matrix, Color color)
        {
            var block = new MaterialPropertyBlock();
            block.SetColor("_Color", color);
            block.SetColor("_EmissionColor", color * 0.8f);
            draw(HatMesh(mesh), matrix, Glow(), 0, block);
        }

        private static void DrawShapeMesh(string shape, Vector3 position, Quaternion rotation, float size, Color color, MeshDraw draw)
        {
            var forward = rotation * Vector3.forward;
            var front = Quaternion.Euler(90f, 0f, 0f);
            switch (shape)
            {
                case "Cube":
                    Piece(draw, "cube", Matrix4x4.TRS(position, rotation, Vector3.one * size * 0.85f), color);
                    break;
                case "Cone":
                    Piece(draw, "cone", Matrix4x4.TRS(position - forward * size * 0.55f, rotation * front, new Vector3(0.9f, 1.1f, 0.9f) * size), color);
                    break;
                case "Cylinder":
                    Piece(draw, "cylinder", Matrix4x4.TRS(position - rotation * Vector3.up * size * 0.5f, rotation, Vector3.one * size), color);
                    break;
                case "Camera":
                    Piece(draw, "cube", Matrix4x4.TRS(position - forward * size * 0.2f, rotation, Vector3.one * size * 0.8f), color);
                    // Lens: a cone widening forward from the body.
                    Piece(draw, "cone", Matrix4x4.TRS(position + forward * size * 0.75f, rotation * Quaternion.Euler(-90f, 0f, 0f), new Vector3(0.6f, 0.55f, 0.6f) * size), color);
                    break;
                default:
                    Piece(draw, "sphere", Matrix4x4.TRS(position, rotation, Vector3.one * size), color);
                    break;
            }
        }

        private static void DrawArrowMesh(Vector3 position, Quaternion rotation, float length, Color color, MeshDraw draw)
        {
            var front = rotation * Quaternion.Euler(90f, 0f, 0f);
            var forward = rotation * Vector3.forward;
            Piece(draw, "cylinder", Matrix4x4.TRS(position, front, new Vector3(length * 0.05f, length * 0.82f, length * 0.05f)), color);
            Piece(draw, "cone", Matrix4x4.TRS(position + forward * length * 0.8f, front, new Vector3(length * 0.16f, length * 0.2f, length * 0.16f)), color);
        }

        // ---- Face items ---------------------------------------------------------------------------------------------
        // Placed on a ball one "face width" across, centred on the shape, looking along +Z, so it looks exactly
        // where its owner looks.

        private static readonly Color Frame = new Color(0.08f, 0.08f, 0.09f);
        private static readonly Color Lens = new Color(0.02f, 0.02f, 0.03f);
        private static readonly Color Pupil = new Color(0.03f, 0.03f, 0.03f);
        private static readonly Color Hair = new Color(0.22f, 0.13f, 0.07f);
        private static readonly Color ClownRed = new Color(0.9f, 0.08f, 0.08f);

        /// <summary>Where the face goes on the shape, and how wide the shape is.</summary>
        private static void FaceSpot(TeamPeer peer, Vector3 position, Quaternion rotation, float size, out Vector3 centre, out float width)
        {
            centre = position;
            switch (peer.LookShape)
            {
                case "Cube": width = size * 0.95f; break;
                case "Cone": width = size * 0.75f; break;
                case "Camera":
                    width = size * 0.9f;
                    centre = position - rotation * Vector3.forward * size * 0.2f;
                    break;
                default: width = size; break;
            }
        }

        private static void DrawFace(string face, Vector3 centre, Quaternion facing, float w, MeshDraw draw)
        {
            Action<string, Vector3, Quaternion, Vector3, Color, bool> part = (mesh, offset, turn, scale, color, lit) =>
            {
                var block = new MaterialPropertyBlock();
                block.SetColor("_Color", color);
                if (lit)
                    block.SetColor("_EmissionColor", color * 1.5f);
                draw(HatMesh(mesh), Matrix4x4.TRS(centre + facing * (offset * w), facing * turn, scale * w), lit ? Glow() : Paint(), 0, block);
            };
            var none = Quaternion.identity;
            var front = Quaternion.Euler(90f, 0f, 0f);   // turns a piece that stands up (+Y) to point forward (+Z)
            var back = Quaternion.Euler(-90f, 0f, 0f);   // ...or backward
            var across = Quaternion.Euler(0f, 0f, 90f);  // ...or sideways (-X)

            switch (face)
            {
                case "Sunglasses":
                case "Round glasses":
                {
                    bool sun = face == "Sunglasses";
                    foreach (float x in new[] { -0.16f, 0.16f })
                    {
                        if (sun)
                            part("cylinder", new Vector3(x, 0.06f, 0.46f), front, new Vector3(0.26f, 0.04f, 0.2f), Lens, false);
                        else
                            part("torus", new Vector3(x, 0.06f, 0.47f), front, new Vector3(0.3f, 0.3f, 0.3f), Frame, false);
                        // Arm back over the ear.
                        part("cylinder", new Vector3(x * 1.85f, 0.08f, 0.44f), back, new Vector3(0.025f, 0.3f, 0.025f), Frame, false);
                    }
                    part("cylinder", new Vector3(0.05f, 0.1f, 0.48f), across, new Vector3(0.025f, 0.1f, 0.025f), Frame, false);
                    break;
                }
                case "Googly eyes":
                    part("sphere", new Vector3(-0.15f, 0.08f, 0.45f), none, new Vector3(0.22f, 0.22f, 0.1f), White, false);
                    part("sphere", new Vector3(0.15f, 0.08f, 0.45f), none, new Vector3(0.22f, 0.22f, 0.1f), White, false);
                    part("sphere", new Vector3(-0.13f, 0.05f, 0.5f), none, new Vector3(0.1f, 0.1f, 0.05f), Pupil, false);
                    part("sphere", new Vector3(0.17f, 0.04f, 0.5f), none, new Vector3(0.1f, 0.1f, 0.05f), Pupil, false);
                    break;
                case "Mustache":
                    part("sphere", new Vector3(-0.1f, -0.15f, 0.46f), Quaternion.Euler(0f, 0f, -15f), new Vector3(0.22f, 0.07f, 0.08f), Hair, false);
                    part("sphere", new Vector3(0.1f, -0.15f, 0.46f), Quaternion.Euler(0f, 0f, 15f), new Vector3(0.22f, 0.07f, 0.08f), Hair, false);
                    break;
                case "Clown nose":
                    part("sphere", new Vector3(0f, -0.02f, 0.5f), none, Vector3.one * 0.17f, ClownRed, false);
                    break;
                case "Monocle":
                    part("torus", new Vector3(0.16f, 0.06f, 0.48f), front, new Vector3(0.32f, 0.32f, 0.32f), Gold, false);
                    part("cylinder", new Vector3(0.16f, -0.08f, 0.48f), Quaternion.Euler(180f, 0f, 0f), new Vector3(0.012f, 0.3f, 0.012f), Gold, false);
                    break;
                case "Eye patch":
                    part("cylinder", new Vector3(-0.16f, 0.06f, 0.45f), front, new Vector3(0.24f, 0.04f, 0.2f), Lens, false);
                    part("torus", new Vector3(0f, 0.08f, 0f), Quaternion.Euler(0f, 0f, -20f), new Vector3(1.04f, 0.5f, 1.04f), Lens, false);
                    break;
            }
        }

        /// <summary>Hat pieces, 1 wide and (except the torus) 1 tall, standing on y = 0.</summary>
        private static Mesh HatMesh(string name)
        {
            Mesh mesh;
            if (hatMeshes.TryGetValue(name, out mesh) && mesh != null)
                return mesh;

            var profile = new List<Vector2>();
            switch (name)
            {
                case "cylinder":
                    profile.AddRange(new[] { new Vector2(0f, 0f), new Vector2(0.5f, 0f), new Vector2(0.5f, 1f), new Vector2(0f, 1f) });
                    break;
                case "cone":
                    profile.AddRange(new[] { new Vector2(0f, 0f), new Vector2(0.5f, 0f), new Vector2(0f, 1f) });
                    break;
                case "dome":
                    profile.Add(new Vector2(0f, 0f));
                    for (int i = 0; i <= 10; i++)
                    {
                        float a = i * Mathf.PI * 0.5f / 10f;
                        profile.Add(new Vector2(Mathf.Cos(a) * 0.5f, Mathf.Sin(a)));
                    }
                    break;
                case "sphere":
                    for (int i = 0; i <= 12; i++)
                    {
                        float a = -Mathf.PI * 0.5f + i * Mathf.PI / 12f;
                        profile.Add(new Vector2(Mathf.Cos(a) * 0.5f, Mathf.Sin(a) * 0.5f));
                    }
                    break;
                case "torus":
                    for (int i = 0; i <= 12; i++)
                    {
                        float a = i * Mathf.PI * 2f / 12f;
                        profile.Add(new Vector2(0.45f + Mathf.Cos(a) * 0.05f, Mathf.Sin(a) * 0.05f));
                    }
                    break;
            }

            mesh = name == "cube" ? Box() : Lathe(profile);
            mesh.name = "WPFMA Team hat " + name;
            hatMeshes[name] = mesh;
            return mesh;
        }

        /// <summary>A cube 1 across, centred on the origin, with sharp edges.</summary>
        private static Mesh Box()
        {
            var vertices = new List<Vector3>();
            var normals = new List<Vector3>();
            var triangles = new List<int>();
            foreach (var n in new[] { Vector3.right, Vector3.left, Vector3.up, Vector3.down, Vector3.forward, Vector3.back })
            {
                var u = Mathf.Abs(n.y) > 0.5f ? Vector3.forward : Vector3.up;
                var v = Vector3.Cross(n, u);
                int b = vertices.Count;
                vertices.Add((n - u - v) * 0.5f);
                vertices.Add((n + u - v) * 0.5f);
                vertices.Add((n + u + v) * 0.5f);
                vertices.Add((n - u + v) * 0.5f);
                for (int i = 0; i < 4; i++)
                    normals.Add(n);
                triangles.AddRange(new[] { b, b + 1, b + 2, b, b + 2, b + 3 });
            }
            var mesh = new Mesh { hideFlags = HideFlags.HideAndDontSave };
            mesh.SetVertices(vertices);
            mesh.SetNormals(normals);
            mesh.SetTriangles(triangles, 0);
            mesh.RecalculateBounds();
            return mesh;
        }

        /// <summary>
        /// Spins a profile (x = distance from the middle, y = height) around the up axis. Each profile step gets its
        /// own vertices, so edges like a brim stay sharp while the way round stays smooth.
        /// </summary>
        private static Mesh Lathe(List<Vector2> profile)
        {
            const int sides = 24;
            var vertices = new List<Vector3>();
            var normals = new List<Vector3>();
            var triangles = new List<int>();

            for (int s = 0; s < profile.Count - 1; s++)
            {
                var p0 = profile[s];
                var p1 = profile[s + 1];
                var d = p1 - p0;
                if (d.sqrMagnitude < 1e-8f)
                    continue;
                var n = new Vector2(d.y, -d.x).normalized;
                int start = vertices.Count;
                for (int i = 0; i <= sides; i++)
                {
                    float a = i * Mathf.PI * 2f / sides;
                    float c = Mathf.Cos(a), sn = Mathf.Sin(a);
                    vertices.Add(new Vector3(p0.x * c, p0.y, p0.x * sn));
                    vertices.Add(new Vector3(p1.x * c, p1.y, p1.x * sn));
                    var normal = new Vector3(n.x * c, n.y, n.x * sn);
                    normals.Add(normal);
                    normals.Add(normal);
                }
                for (int i = 0; i < sides; i++)
                {
                    int b = start + i * 2;
                    triangles.AddRange(new[] { b, b + 1, b + 2, b + 2, b + 1, b + 3 });
                }
            }

            var mesh = new Mesh { hideFlags = HideFlags.HideAndDontSave };
            mesh.SetVertices(vertices);
            mesh.SetNormals(normals);
            mesh.SetTriangles(triangles, 0);
            mesh.RecalculateBounds();
            return mesh;
        }

        private static Material Paint()
        {
            if (paint == null)
                paint = Plain(Color.white, 0.3f);
            return paint;
        }

        private static Material Glow()
        {
            if (glow == null)
            {
                glow = Plain(Color.white, 0.6f);
                glow.EnableKeyword("_EMISSION");
                glow.globalIlluminationFlags = MaterialGlobalIlluminationFlags.None;
            }
            return glow;
        }

        private static Material Plain(Color color, float smoothness)
        {
            var shader = Shader.Find("Standard") ?? Shader.Find("Unlit/Color");
            var material = new Material(shader) { hideFlags = HideFlags.HideAndDontSave, color = color };
            if (material.HasProperty("_Glossiness"))
                material.SetFloat("_Glossiness", smoothness);
            return material;
        }

        // ---- Preview in Settings ----------------------------------------------------------------------------------

        private static PreviewRenderUtility preview;
        private static float previewYaw = 150f;
        private static float previewPitch = 12f;

        /// <summary>
        /// Draws you the way a teammate sees you, using the same drawing as their Scene view. Drag to turn it.
        /// The teammate colour shown is the first one teammates are given; each editor hands out its own.
        /// Returns true while being dragged, so the window repaints.
        /// </summary>
        internal static bool DrawPreview(Rect rect)
        {
            var e = Event.current;
            int id = GUIUtility.GetControlID(FocusType.Passive, rect);
            switch (e.GetTypeForControl(id))
            {
                case EventType.MouseDown:
                    if (rect.Contains(e.mousePosition) && e.button == 0)
                    {
                        GUIUtility.hotControl = id;
                        e.Use();
                    }
                    return false;
                case EventType.MouseDrag:
                    if (GUIUtility.hotControl == id)
                    {
                        previewYaw += e.delta.x * 0.6f;
                        previewPitch = Mathf.Clamp(previewPitch + e.delta.y * 0.4f, -10f, 60f);
                        e.Use();
                        return true;
                    }
                    return false;
                case EventType.MouseUp:
                    if (GUIUtility.hotControl == id)
                    {
                        GUIUtility.hotControl = 0;
                        e.Use();
                    }
                    return false;
                case EventType.Repaint:
                    break;
                default:
                    return false;
            }

            var me = new TeamPeer
            {
                Name = TeamSession.DisplayName,
                Color = TeamSession.Palette[0],
                LookShape = Shape,
                LookColor = ShapeColor,
                LookHat = Hat,
                LookFace = Face
            };

            if (preview == null)
            {
                preview = new PreviewRenderUtility();
                preview.camera.fieldOfView = 30f;
                preview.camera.nearClipPlane = 0.01f;
                preview.camera.farClipPlane = 100f;
                preview.camera.clearFlags = CameraClearFlags.SolidColor;
                preview.lights[0].intensity = 1.2f;
                preview.lights[0].transform.rotation = Quaternion.Euler(40f, 40f, 0f);
                preview.lights[1].intensity = 0.6f;
                preview.lights[1].transform.rotation = Quaternion.Euler(340f, 218f, 0f);
                preview.ambientColor = new Color(0.3f, 0.3f, 0.32f);
            }

            // The marker faces +Z like a camera looking ahead; the preview camera orbits around it.
            const float size = 1f;
            float top = LabelHeight(me, size);
            float bottom = size * 0.6f;
            var centre = Vector3.up * (top - bottom) * 0.5f;
            float distance = Mathf.Max(4.5f, (top + bottom + 1.2f) * 2.4f);
            var orbit = Quaternion.Euler(previewPitch, previewYaw, 0f);
            var cam = preview.camera;
            cam.backgroundColor = EditorGUIUtility.isProSkin ? new Color(0.16f, 0.17f, 0.19f) : new Color(0.72f, 0.73f, 0.75f);
            cam.transform.position = centre - orbit * Vector3.forward * distance;
            cam.transform.rotation = orbit;

            preview.BeginPreview(rect, GUIStyle.none);
            Submit(me, Vector3.zero, Quaternion.identity, size, (mesh, matrix, material, sub, block) =>
                preview.DrawMesh(mesh, matrix, material, sub, block));
            preview.Render(true);

            // The ring under a recoloured shape is a Handles line in the Scene view; draw it into the preview the same way.
            var color = me.Color;
            if (me.LookColor.HasValue)
            {
                var was = RenderTexture.active;
                RenderTexture.active = cam.targetTexture;
                Handles.SetCamera(cam);
                Handles.color = color;
                Handles.DrawWireDisc(-Vector3.up * size * 0.6f, Vector3.up, size * 0.7f);
                RenderTexture.active = was;
            }

            var texture = preview.EndPreview();
            GUI.DrawTexture(rect, texture, ScaleMode.StretchToFill, false);

            // Your name, where teammates see it.
            var label = cam.WorldToScreenPoint(Vector3.up * (top + size * 0.9f));
            float scale = rect.height / Mathf.Max(1f, texture.height);
            var at = new Vector2(rect.x + label.x * scale, rect.yMax - label.y * scale);
            var style = new GUIStyle(EditorStyles.boldLabel) { normal = { textColor = color }, alignment = TextAnchor.LowerCenter };
            GUI.Label(new Rect(at.x - 100f, at.y - 18f, 200f, 18f), me.Name ?? "You", style);
            GUI.Label(new Rect(rect.x + 6f, rect.yMax - 18f, rect.width - 12f, 16f), "Drag to turn", EditorStyles.miniLabel);
            return false;
        }

        internal static void ReleasePreview()
        {
            if (preview == null)
                return;
            preview.Cleanup();
            preview = null;
        }

        /// <summary>Draws one of the built-in shapes with Handles (the colour is set by the caller).</summary>
        internal static void DrawShape(string shape, Vector3 position, Quaternion rotation, float size)
        {
            switch (shape)
            {
                case "Cube":
                    Handles.CubeHandleCap(0, position, rotation, size * 0.85f, EventType.Repaint);
                    break;
                case "Cone":
                    Handles.ConeHandleCap(0, position, rotation, size * 1.2f, EventType.Repaint);
                    break;
                case "Cylinder":
                    Handles.CylinderHandleCap(0, position, rotation * Quaternion.Euler(90f, 0f, 0f), size, EventType.Repaint);
                    break;
                case "Camera":
                    // A small body with a lens pointing where they look.
                    Handles.CubeHandleCap(0, position - rotation * Vector3.forward * size * 0.2f, rotation, size * 0.8f, EventType.Repaint);
                    Handles.ConeHandleCap(0, position + rotation * Vector3.forward * size * 0.45f, rotation * Quaternion.Euler(180f, 0f, 0f), size * 0.6f, EventType.Repaint);
                    break;
                default:
                    Handles.SphereHandleCap(0, position, rotation, size, EventType.Repaint);
                    break;
            }
        }
    }
}
#endif
