// 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 System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace WPFMA.Team
{
    [Serializable]
    internal sealed class TeamNode
    {
        public string id;
        public string parent;
        public int sibling;
        public string name;
        public bool active;
        public int layer;
        public string tag;
        public int flags;
        public string prefab;
        public bool pk;
        public string owner;
        public int pi = -1;
        public string[] types;
        public string[] json;
        public float[] tr;
    }

    [Serializable]
    internal sealed class TeamTree
    {
        public string scene;
        public bool shallow;
        public TeamNode[] nodes;
    }

    [Serializable]
    internal sealed class TeamGo
    {
        public string name;
        public bool active;
        public int layer;
        public string tag;
        public int flags;
    }

    [Serializable]
    internal sealed class TeamSceneSaved
    {
        public int[] objects;
        public string[] ids;
        public string[] live;
        public string want;
    }

    /// <summary>
    /// Live scene editing. Both editors open the same scene from one snapshot, give every GameObject the same id,
    /// then send each change as it happens: properties, new objects, deleted objects, re-parenting, added and
    /// removed components, and material edits. References are sent as ids (scene objects) or asset ids (assets),
    /// never as Unity instance ids, which differ per editor. The host checks now and then that both scenes still
    /// match and sends a fresh copy if they drift.
    /// </summary>
    [InitializeOnLoad]
    internal static partial class TeamScene
    {
        private const string SavedKey = "WPFMA.Team.Scene";
        private const double FlushInterval = 0.05;
        private const double DigestInterval = 10.0;

        private static readonly HashSet<string> StrippedKeys = new HashSet<string>
        {
            "m_GameObject", "m_Children", "m_Father", "m_RootOrder", "m_PrefabInstance", "m_PrefabAsset",
            "m_CorrespondingSourceObject", "m_Script", "m_ObjectHideFlags", "m_EditorHideFlags", "m_EditorClassIdentifier"
        };

        private static readonly Regex InstanceRef = new Regex("\\{\"instanceID\":(-?\\d+)\\}", RegexOptions.Compiled);
        private static readonly Regex PortableRef = new Regex("\\{\"wref\":\"([^\"]*)\"\\}", RegexOptions.Compiled);

        private sealed class Deferred
        {
            public TeamMessage Message;
            public byte[] Blob;
            public double Since;
        }

        private static readonly Dictionary<int, string> idOf = new Dictionary<int, string>();
        private static readonly Dictionary<string, int> objOf = new Dictionary<string, int>();
        private static readonly HashSet<string> live = new HashSet<string>();
        private static readonly HashSet<int> dirty = new HashSet<int>();
        private static readonly HashSet<int> dirtyMaterials = new HashSet<int>();
        private static readonly HashSet<int> knownComponents = new HashSet<int>();
        private static readonly Dictionary<string, string> lastSent = new Dictionary<string, string>();
        private static readonly Dictionary<string, string> lastShape = new Dictionary<string, string>();
        private static readonly List<Deferred> deferred = new List<Deferred>();
        private static readonly Dictionary<Type, bool> typeCache = new Dictionary<Type, bool>();
        private static string wantScene;
        private static double lastFlush;
        private static double lastActivity;
        private static double lastDigest;
        private static double lastRetry;
        private static int digestMisses;
        private static int copying;
        private static string opening;
        private static readonly Dictionary<int, double> localMaterialEdit = new Dictionary<int, double>();
        private static readonly Queue<TeamMessage> held = new Queue<TeamMessage>();
        // Asset references appear as our GlobalObjectIds or as Unity's own {"fileID":..,"guid":"..."} (escaped when nested).
        private static readonly Regex AssetGuid = new Regex(@"(?:GlobalObjectId_V1-\d-|guid\W{1,6})([0-9a-f]{32})", RegexOptions.Compiled);
        private static readonly Dictionary<int, int> dirtyCounts = new Dictionary<int, int>();
        private static readonly Dictionary<int, int> shapes = new Dictionary<int, int>();
        private static readonly Dictionary<int, float[]> poses = new Dictionary<int, float[]>();
        private static double lastSweep;
        private static double lastLocalEdit = -1000;
        private static bool heldNotice;
        private static bool followPending;
        private static WPFMAChangeLog.Entry logEntry;
        private static double logEntryAt = -1000;
        private static readonly HashSet<string> wasLive = new HashSet<string>();

        // Scene edits made this frame, sent together as one message (one packet, compressed together).
        private static readonly List<TeamMessage> outbox = new List<TeamMessage>();
        private static int outboxSize;

        // A teammate dragging something: it glides between their updates instead of jumping 20 times a second.
        private sealed class Glide
        {
            public string Id;
            public Transform T;
            public float[] From;
            public float[] To;
            public float[] LastSet;
            public double Start;
        }

        private const double GlideTime = 0.07;
        private static readonly Dictionary<int, Glide> glides = new Dictionary<int, Glide>();
        private static readonly List<int> glideDone = new List<int>();
        private static readonly Dictionary<int, double> lastRemoteMove = new Dictionary<int, double>();
        private static bool repaintSoon;
        private static double lastRepaintAt;

        // Joining a teammate's scene when you open it (like walking into the same place in Roblox Studio).
        private static double joinAt;
        private static bool joinedOnce;
        private static bool joinAnyway;
        // When this editor went into its open scene.
        private static double localSceneAt;
        // Guest: shared scenes whose other editor is another guest, not the host (the host doesn't have them open).
        private static readonly HashSet<string> liveViaGuest = new HashSet<string>();

        // Host: which guest has which shared scene open (a scene stays shared while anyone has it).
        private static readonly Dictionary<string, HashSet<string>> peerLive = new Dictionary<string, HashSet<string>>();

        private static HashSet<string> LiveFor(TeamPeer peer)
        {
            HashSet<string> set;
            if (peer == null)
                return new HashSet<string>();
            if (!peerLive.TryGetValue(peer.Id, out set))
            {
                set = new HashSet<string>();
                peerLive[peer.Id] = set;
            }
            return set;
        }

        private static bool AnyGuestLive(string path)
        {
            return peerLive.Values.Any(s => s.Contains(path));
        }

        internal static string RemoteActiveScene { get; private set; }
        internal static string Notice { get; private set; }

        static TeamScene()
        {
            ObjectChangeEvents.changesPublished += OnChanges;
            EditorApplication.update += Update;
            EditorSceneManager.sceneClosed += OnSceneClosed;
            EditorSceneManager.sceneSaved += OnSceneSaved;
            EditorSceneManager.activeSceneChangedInEditMode += (a, b) => Arrived();
            EditorSceneManager.sceneOpened += (scene, mode) => Arrived();
            EditorApplication.playModeStateChanged += change =>
            {
                if (change == PlayModeStateChange.ExitingEditMode)
                {
                    FinishGlides();
                    SendOutbox();
                    RememberPlayOrder();
                }
                else if (change == PlayModeStateChange.EnteredEditMode)
                {
                    RelinkAfterPlay();
                    RetryDeferred(true);
                }
            };
            TeamSession.LinkUp += OnLinkUp;
            TeamSession.Received += OnReceived;
            TeamSession.Ended += OnEnded;
            TeamSession.Suspending += Save;
            TeamFiles.SyncFinished += () =>
            {
                if (TeamSession.IsHost)
                    return;
                // The first time, a guest starts in the host's scene; after that everyone stays where they are.
                if (!joinedOnce || FollowScenes)
                {
                    joinedOnce = true;
                    RequestScene(RemoteActiveScene);
                }
                else
                    JoinSoon();
            };
            TeamSession.PeerRestarted += OnPeerRestarted;
            TeamSession.PeerLeft += () =>
            {
                if (TeamSession.Sender != null)
                {
                    peerLive.Remove(TeamSession.Sender.Id);
                    GuestCheck.Remove(TeamSession.Sender.Id);
                }
                snapshotQueue.RemoveAll(q => q.Peer == TeamSession.Sender);
            };
            TeamSession.Restarted += () =>
            {
                string mine = TeamSession.ScenePath();
                bool mineShared = live.Contains(mine);
                ForgetScenes();
                if (!TeamSession.IsHost)
                    Rejoin(mine, mineShared);
            };
            WPFMAChangeLog.Reverted += OnReverted;
            Restore();
        }

        // Off by default: everyone works in their own scene, and opening a scene a teammate is in joins them there.
        private const string FollowKey = "WPFMA.Team.FollowHostScene";

        /// <summary>The guest's follow choice, readable before a session starts (for the setup window).</summary>
        internal static bool FollowPreference
        {
            get { return EditorPrefs.GetBool(FollowKey, false); }
            set { EditorPrefs.SetBool(FollowKey, value); }
        }

        /// <summary>
        /// The guest opens every scene the host switches to (off: a guest joins the host's scene once, when they
        /// connect, then works wherever they like). The host never follows.
        /// </summary>
        internal static bool FollowScenes
        {
            get { return !TeamSession.IsHost && EditorPrefs.GetBool(FollowKey, false); }
            set { EditorPrefs.SetBool(FollowKey, value); }
        }

        /// <summary>After a restart: back into the host's scene if you were there (or follow), else stay and join whoever is in yours.</summary>
        private static void Rejoin(string mine, bool mineShared)
        {
            if (FollowScenes || string.IsNullOrEmpty(mine) || mine == RemoteActiveScene || !mineShared)
            {
                if (!string.IsNullOrEmpty(RemoteActiveScene))
                    RequestScene(RemoteActiveScene);
                else
                    followPending = true;
                return;
            }
            joinAt = TeamSession.Now + 1.0;
            joinAnyway = true;
        }

        private static void Arrived()
        {
            localSceneAt = TeamSession.Now;
            JoinSoon();
        }

        private static void JoinSoon()
        {
            if (TeamSession.IsLinked)
                joinAt = TeamSession.Now + 0.25;
        }

        /// <summary>The teammate (if any) working in this scene.</summary>
        internal static TeamPeer WhoIsIn(string path)
        {
            if (string.IsNullOrEmpty(path))
                return null;
            return TeamSession.Peers.FirstOrDefault(p => p.ScenePath == path && !p.Playing && string.IsNullOrEmpty(p.Prefab) && (p.IsHost || p.Link != null || !TeamSession.IsHost));
        }

        /// <summary>You opened a scene a teammate is working in: get their copy (it has their unsaved edits) and edit it together.</summary>
        private static void TryJoin()
        {
            joinAt = 0;
            bool anyway = joinAnyway;
            joinAnyway = false;
            if (!TeamSession.IsLinked || EditorApplication.isPlayingOrWillChangePlaymode || WaitingForScene)
                return;
            if (TeamFiles.Phase != TeamSyncPhase.Live)
            {
                joinAt = TeamSession.Now + 1.0;
                joinAnyway = anyway;
                return;
            }
            var scene = SceneManager.GetActiveScene();
            if (!scene.IsValid() || string.IsNullOrEmpty(scene.path) || live.Contains(scene.path))
                return;
            var there = WhoIsIn(scene.path);
            // Only the one who came in later joins (takes the other's copy); the one already there waits to be joined.
            // After a restart a guest rejoins the host's copy whoever came first.
            if (there != null && (there.SceneSince <= localSceneAt || (anyway && there.IsHost)))
                Join(scene.path, there);
        }

        private static void Join(string path, TeamPeer peer)
        {
            if (!TeamSession.IsHost)
            {
                RequestScene(path);
                return;
            }
            wantScene = path;
            Notice = "Joining " + peer.Name + " in " + Path.GetFileNameWithoutExtension(path) + "...";
            SendOutbox();
            TeamSession.SendTo(peer, new TeamMessage { t = "sreq", f = path });
            TeamSession.Raise();
        }

        /// <summary>The Join button: open the scene a teammate is in and edit it with them.</summary>
        internal static void JoinPeer(TeamPeer peer)
        {
            if (peer == null || string.IsNullOrEmpty(peer.ScenePath) || !TeamSession.IsLinked)
                return;
            string path = peer.ScenePath;
            if (!TeamSession.IsHost && peer.IsHost)
            {
                RequestScene(path);
                return;
            }
            if (!IsLoaded(path))
            {
                if (!File.Exists(path))
                {
                    if (!TeamSession.IsHost)
                        RequestScene(path);
                    return;
                }
                if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                    return;
                EditorSceneManager.OpenScene(path, OpenSceneMode.Single);
            }
            if (!live.Contains(path))
                Join(path, peer);
        }

        /// <summary>
        /// Whether this teammate gets this scene's edits live (so a saved copy of it doesn't need sending to them).
        /// Teammates in other scenes get the saved file like any other.
        /// </summary>
        internal static bool SharedWith(string peerId, string path)
        {
            if (!live.Contains(path))
                return false;
            if (TeamSession.IsHost)
            {
                HashSet<string> set;
                return peerLive.TryGetValue(peerId ?? string.Empty, out set) && set.Contains(path);
            }
            return !liveViaGuest.Contains(path);
        }

        private static void ForgetScenes()
        {
            peerLive.Clear();
            live.Clear();
            idOf.Clear();
            objOf.Clear();
            lastSent.Clear();
            lastShape.Clear();
            deferred.Clear();
            knownComponents.Clear();
            held.Clear();
            snapshotQueue.Clear();
            dirtyCounts.Clear();
            shapes.Clear();
            poses.Clear();
            outbox.Clear();
            outboxSize = 0;
            glides.Clear();
            lastRemoteMove.Clear();
            liveViaGuest.Clear();
            lineCache.Clear();
        }

        /// <summary>The other editor was closed and opened again, so its scene ids are gone: start the scene over.</summary>
        private static void OnPeerRestarted()
        {
            if (TeamSession.IsHost)
            {
                // Only that guest starts over (it asks for the scene again); everyone else keeps going.
                if (TeamSession.Sender != null)
                    peerLive.Remove(TeamSession.Sender.Id);
                if (!TeamSession.Peers.Any(p => p.Link != null && p != TeamSession.Sender))
                    ForgetScenes();
                return;
            }
            string mine = TeamSession.ScenePath();
            bool mineShared = live.Contains(mine);
            ForgetScenes();
            Rejoin(mine, mineShared);
        }

        /// <summary>A shared scene was put back from the Change log: send the restored scene so both match again.</summary>
        private static void OnReverted(WPFMAChangeLog.Entry entry)
        {
            if (!entry.hasScene || !TeamSession.IsLinked || string.IsNullOrEmpty(entry.scenePath))
                return;
            if (!wasLive.Contains(entry.scenePath) && !live.Contains(entry.scenePath))
                return;
            if (!TeamSession.IsHost)
            {
                TeamSession.AddSystem("You put back " + Path.GetFileNameWithoutExtension(entry.scenePath) + ", but it is a shared scene and the host's " +
                                      "version is the reference, so it will be matched to the host's again. Ask the host to undo it instead.");
                return;
            }
            EditorApplication.delayCall += () =>
            {
                QueueSnapshot(entry.scenePath);
                TeamSession.AddSystem("Put back " + Path.GetFileNameWithoutExtension(entry.scenePath) + " from the Change log and sent it to " + TeamSession.RemoteName + ".");
            };
        }

        private const string PlayOrderKey = "WPFMA.Team.PlayOrder";

        /// <summary>
        /// Leaving Play mode can rebuild the scene's objects, which would leave the shared ids pointing at nothing.
        /// The order of the shared objects is remembered before Play mode and used to re-link them after.
        /// </summary>
        private static void RememberPlayOrder()
        {
            var lines = new List<string>();
            foreach (var path in live)
            {
                var scene = SceneManager.GetSceneByPath(path);
                if (!scene.IsValid() || !scene.isLoaded)
                    continue;
                lines.Add(path + "\t" + string.Join("\u0001", Walk(scene).Select(IdFor).ToArray()));
            }
            SessionState.SetString(PlayOrderKey, string.Join("\n", lines.ToArray()));
        }

        private static void RelinkAfterPlay()
        {
            string saved = SessionState.GetString(PlayOrderKey, string.Empty);
            SessionState.EraseString(PlayOrderKey);
            if (string.IsNullOrEmpty(saved))
                return;

            foreach (var line in saved.Split('\n'))
            {
                int tab = line.IndexOf('\t');
                if (tab <= 0)
                    continue;
                string path = line.Substring(0, tab);
                var ids = line.Substring(tab + 1).Split('\u0001');
                var scene = SceneManager.GetSceneByPath(path);
                if (!scene.IsValid() || !scene.isLoaded || !live.Contains(path))
                    continue;
                var objects = Walk(scene).ToList();
                if (objects.Count != ids.Length)
                {
                    if (!TeamSession.IsHost && TeamSession.IsLinked)
                        RequestScene(path);
                    continue;
                }
                for (int i = 0; i < objects.Count; i++)
                    Map(objects[i], ids[i]);
            }

            dirtyCounts.Clear();
            shapes.Clear();
            poses.Clear();
            knownComponents.Clear();
            sweepQueue.Clear();
            sweepIndex = 0;
        }

        /// <summary>The teammate's scene edits go into the Change log, one entry per couple of minutes of edits.</summary>
        private static void LogSceneEdit()
        {
            if (logEntry != null && !logEntry.reverted && TeamSession.Now - logEntryAt < 120)
            {
                logEntryAt = TeamSession.Now;
                return;
            }
            var active = SceneManager.GetActiveScene();
            if (!active.IsValid() || !live.Contains(active.path))
                return;

            copying++;
            TeamLocks.UnlockAll();
            try
            {
                logEntry = WPFMAChangeLog.Begin("Team", "Scene edits from " + TeamSession.RemoteName + " (" + DateTime.Now.ToString("HH:mm") + ")",
                    null, true, TeamSession.RemoteName + " edited " + active.name);
            }
            finally
            {
                copying--;
                TeamLocks.Refresh();
            }
            logEntryAt = TeamSession.Now;
        }

        // ---- Public helpers ---------------------------------------------------------------------------------------

        internal static bool IsLive(string scenePath)
        {
            return !string.IsNullOrEmpty(scenePath) && live.Contains(scenePath);
        }

        internal static bool IsLoaded(string path)
        {
            if (string.IsNullOrEmpty(path) || !path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase))
                return false;
            for (int i = 0; i < SceneManager.sceneCount; i++)
                if (SceneManager.GetSceneAt(i).path == path)
                    return true;
            return false;
        }

        internal static IEnumerable<string> LiveScenes
        {
            get { return live; }
        }

        internal static bool WaitingForScene
        {
            get { return !string.IsNullOrEmpty(wantScene); }
        }

        /// <summary>Id for a scene object (made from its place in the hierarchy if it does not have one yet).</summary>
        internal static string IdFor(GameObject go)
        {
            if (go == null)
                return string.Empty;
            string id;
            if (idOf.TryGetValue(go.GetInstanceID(), out id))
                return id;

            var parent = go.transform.parent;
            string prefix = parent != null ? IdFor(parent.gameObject) : "r:" + go.scene.path;
            id = prefix + "/" + go.transform.GetSiblingIndex() + ":" + go.name;
            if (objOf.ContainsKey(id))
                id += "~" + Guid.NewGuid().ToString("N").Substring(0, 6);
            Map(go, id);
            return id;
        }

        internal static GameObject Find(string id)
        {
            int instance;
            if (string.IsNullOrEmpty(id) || !objOf.TryGetValue(id, out instance))
                return null;
            var go = EditorUtility.InstanceIDToObject(instance) as GameObject;
            if (go == null)
            {
                objOf.Remove(id);
                idOf.Remove(instance);
            }
            return go;
        }

        /// <summary>True if this material was edited here in the last few seconds (its live edit may still be on the way).</summary>
        internal static bool RecentlyEdited(UnityEngine.Object asset, double seconds = 5.0)
        {
            double when;
            return asset != null && localMaterialEdit.TryGetValue(asset.GetInstanceID(), out when) && TeamSession.Now - when < seconds;
        }

        /// <summary>Sends this asset's current values again (after a file from the teammate reloaded it).</summary>
        internal static void ResendAsset(UnityEngine.Object asset)
        {
            if (asset == null)
                return;
            lastSent.Remove("m:" + AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(asset)));
            dirtyMaterials.Add(asset.GetInstanceID());
        }

        /// <summary>Seconds since anything was edited in this editor (scene or assets).</summary>
        internal static double SecondsSinceLocalEdit
        {
            get { return TeamSession.Now - lastLocalEdit; }
        }

        /// <summary>
        /// Assets edited live, value by value, like materials: materials and single-object assets such as VRChat
        /// expression menus and parameters. Assets with sub-objects (animator controllers, models) sync when saved.
        /// </summary>
        internal static bool LiveAsset(UnityEngine.Object asset)
        {
            if (asset == null || !EditorUtility.IsPersistent(asset) || AssetDatabase.IsSubAsset(asset))
                return false;
            if (asset is Material)
                return true;
            if (!(asset is ScriptableObject))
                return false;
            string path = AssetDatabase.GetAssetPath(asset);
            return path.EndsWith(".asset", StringComparison.OrdinalIgnoreCase) && AssetDatabase.LoadAllAssetsAtPath(path).Length == 1;
        }

        internal static void FilesArrived()
        {
            RetryDeferred(false);
            TeamProject.Recheck();
        }

        /// <summary>Ask the teammate for a copy of a scene they have open, open it here, and edit it together.</summary>
        internal static void RequestScene(string path)
        {
            if (!TeamSession.IsLinked)
                return;

            // The host opens its own copy and sends it; it only asks the guest for scenes the host does not have.
            if (TeamSession.IsHost && !string.IsNullOrEmpty(path) && File.Exists(path))
            {
                OpenAndShare(path);
                return;
            }

            wantScene = string.IsNullOrEmpty(path) ? "*" : path;
            var there = WhoIsIn(path);
            Notice = "Getting " + (string.IsNullOrEmpty(path) ? "the scene" : Path.GetFileNameWithoutExtension(path)) + " from " + (there != null ? there.Name : TeamSession.RemoteName) + "...";
            Direct(new TeamMessage { t = "sreq", f = path ?? string.Empty });
            TeamSession.Raise();
        }

        private static void OpenAndShare(string path)
        {
            if (!IsLoaded(path))
            {
                if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                    return;
                EditorSceneManager.OpenScene(path, OpenSceneMode.Single);
            }
            QueueSnapshot(path);
        }

        private static void Map(GameObject go, string id)
        {
            int instance = go.GetInstanceID();
            string old;
            if (idOf.TryGetValue(instance, out old))
                objOf.Remove(old);
            int other;
            if (objOf.TryGetValue(id, out other))
                idOf.Remove(other);
            idOf[instance] = id;
            objOf[id] = instance;
        }

        private static void Unmap(GameObject go)
        {
            string id;
            if (idOf.TryGetValue(go.GetInstanceID(), out id))
            {
                idOf.Remove(go.GetInstanceID());
                objOf.Remove(id);
            }
        }

        private static bool InLive(GameObject go)
        {
            return go != null && !EditorUtility.IsPersistent(go) && go.scene.IsValid() && live.Contains(go.scene.path) &&
                   !ToolOnly(go);
        }

        /// <summary>
        /// Objects tools make for themselves and hide from the Hierarchy (like NDMF's "nadena.dev.ndmf__Activator"),
        /// or never save. They aren't part of anyone's scene, so they're never synced (or deleted on the other side).
        /// </summary>
        internal static bool ToolOnly(GameObject go)
        {
            return (go.hideFlags & (HideFlags.DontSaveInEditor | HideFlags.HideInHierarchy)) != 0;
        }

        /// <summary>Scene edits need a shared scene; material edits only need the files to be in sync.</summary>
        private static bool CanSend
        {
            get
            {
                return TeamSession.IsLinked && !EditorApplication.isPlayingOrWillChangePlaymode &&
                       (live.Count > 0 || (dirtyMaterials.Count > 0 && TeamFiles.Phase == TeamSyncPhase.Live));
            }
        }

        // ---- Session events ---------------------------------------------------------------------------------------

        private static void OnLinkUp(bool resumed)
        {
            if (!resumed)
            {
                // A new session starts with nothing shared; a second guest joining doesn't change the first's scenes.
                if (!TeamSession.IsHost || !TeamSession.Peers.Any(p => p.Link != null && p != TeamSession.Sender))
                {
                    live.Clear();
                    peerLive.Clear();
                }
                if (TeamSession.Sender != null)
                    peerLive.Remove(TeamSession.Sender.Id);
                wantScene = null;
                Notice = null;
                if (!TeamSession.IsHost)
                    joinedOnce = false;
                return;
            }

            if (!string.IsNullOrEmpty(wantScene))
                RequestScene(wantScene == "*" ? null : wantScene);
            else if (TeamSession.IsHost)
                lastDigest = TeamSession.Now - DigestInterval + 3.0;
        }

        private static void OnEnded()
        {
            ClearDrift();
            GuestCheck.Clear();
            LastCheck = -1;
            CheckNote = null;
            live.Clear();
            idOf.Clear();
            objOf.Clear();
            dirty.Clear();
            dirtyMaterials.Clear();
            deferred.Clear();
            lastSent.Clear();
            lastShape.Clear();
            knownComponents.Clear();
            wantScene = null;
            Notice = null;
            RemoteActiveScene = null;
            followPending = false;
            peerLive.Clear();
            snapshotQueue.Clear();
            logEntry = null;
            wasLive.Clear();
            FinishGlides();
            outbox.Clear();
            outboxSize = 0;
            lastRemoteMove.Clear();
            liveViaGuest.Clear();
            lineCache.Clear();
            joinAt = 0;
            joinedOnce = false;
            SessionState.EraseString(SavedKey);
        }

        private static void Save()
        {
            var saved = new TeamSceneSaved
            {
                objects = idOf.Keys.ToArray(),
                ids = idOf.Values.ToArray(),
                live = live.ToArray(),
                want = wantScene
            };
            SessionState.SetString(SavedKey, JsonUtility.ToJson(saved));
        }

        private static void Restore()
        {
            string json = SessionState.GetString(SavedKey, string.Empty);
            if (string.IsNullOrEmpty(json))
                return;
            SessionState.EraseString(SavedKey);
            try
            {
                var saved = JsonUtility.FromJson<TeamSceneSaved>(json);
                for (int i = 0; i < saved.objects.Length; i++)
                {
                    idOf[saved.objects[i]] = saved.ids[i];
                    objOf[saved.ids[i]] = saved.objects[i];
                }
                foreach (var path in saved.live)
                    live.Add(path);
                wantScene = string.IsNullOrEmpty(saved.want) ? null : saved.want;
            }
            catch (Exception)
            {
            }
        }

        private static void OnSceneClosed(Scene scene)
        {
            // Opening the teammate's copy closes our own scene at the same path first: that is not leaving it.
            if (scene.path == opening)
                return;
            if (!live.Remove(scene.path))
                return;
            liveViaGuest.Remove(scene.path);
            wasLive.Add(scene.path);
            foreach (var pair in idOf.ToList())
            {
                var go = EditorUtility.InstanceIDToObject(pair.Key) as GameObject;
                if (go == null || go.scene == scene)
                {
                    idOf.Remove(pair.Key);
                    objOf.Remove(pair.Value);
                }
            }
            if (TeamSession.IsLinked)
                Direct(new TeamMessage { t = "sgone", f = scene.path });
            TeamSession.Raise();
        }

        private static void OnSceneSaved(Scene scene)
        {
            if (copying > 0)
                return;
            if (TeamSession.IsLinked && live.Contains(scene.path))
                Direct(new TeamMessage { t = "op", mt = "saved", f = scene.path, sc = scene.path });
        }

        // ---- Messages ---------------------------------------------------------------------------------------------

        private static void OnReceived(TeamMessage message, byte[] blob)
        {
            switch (message.t)
            {
                case "scene":
                {
                    bool changed = RemoteActiveScene != message.f;
                    RemoteActiveScene = message.f;
                    if (string.IsNullOrEmpty(message.f) || live.Contains(message.f) || WaitingForScene || message.o)
                        return;
                    if (followPending || (changed && FollowScenes && TeamFiles.Phase == TeamSyncPhase.Live))
                    {
                        followPending = false;
                        RequestScene(message.f);
                    }
                    return;
                }
                case "sreq":
                {
                    string path = message.f;
                    // Host: a scene only guests have open (they can work in a scene the host isn't in) is asked of them.
                    if (TeamSession.IsHost && !string.IsNullOrEmpty(path) && !IsLoaded(path))
                    {
                        var holder = TeamSession.Peers.FirstOrDefault(p => p != TeamSession.Sender && p.Link != null && p.ScenePath == path && !p.Playing);
                        if (holder != null && TeamSession.Sender != null)
                        {
                            TeamSession.Forward(holder, TeamSession.Sender, message);
                            return;
                        }
                    }
                    // Both of you opened it and asked each other at once: the host's copy is the one used.
                    if (!string.IsNullOrEmpty(path) && wantScene == path)
                    {
                        if (!TeamSession.IsHost)
                        {
                            Answer(TeamSession.Sender, new TeamMessage { t = "sfail", f = path, o = true });
                            return;
                        }
                        wantScene = null;
                        Notice = null;
                    }
                    QueueSnapshot(path, TeamSession.Sender);
                    return;
                }
                case "sfail":
                    if (message.o)
                    {
                        // Quiet: they are joining you instead.
                        if (wantScene == message.f)
                        {
                            wantScene = null;
                            Notice = null;
                            TeamSession.Raise();
                        }
                        return;
                    }
                    wantScene = null;
                    Notice = message.m;
                    TeamSession.AddSystem(message.m);
                    return;
                case "snap":
                    // The host only takes a scene it asked for: one it joined a guest in, or one it does not have.
                    if (TeamSession.IsHost && !(wantScene == message.f || (!string.IsNullOrEmpty(wantScene) && !File.Exists(message.f))))
                        return;
                    if (EditorApplication.isPlayingOrWillChangePlaymode)
                    {
                        Defer(message, blob);
                        return;
                    }
                    LoadSnapshot(message, blob);
                    return;
                case "slive":
                    if (IsLoaded(message.f))
                        live.Add(message.f);
                    if (TeamSession.IsHost)
                        LiveFor(TeamSession.Sender).Add(message.f);
                    TeamSession.Raise();
                    return;
                case "sgone":
                    if (TeamSession.IsHost)
                    {
                        // One guest left the scene: it stays shared while the host has it and anyone else does too.
                        LiveFor(TeamSession.Sender).Remove(message.f);
                        if (AnyGuestLive(message.f))
                            return;
                    }
                    if (live.Remove(message.f))
                    {
                        liveViaGuest.Remove(message.f);
                        wasLive.Add(message.f);
                        TeamSession.AddSystem(TeamSession.RemoteName + " closed " + Path.GetFileNameWithoutExtension(message.f) + ". Edits to it are no longer shared until you both open it again.");
                        TeamSession.Raise();
                    }
                    return;
                case "op":
                    // The out-of-sync check's own messages aren't edits.
                    if (IsCheckOp(message.mt))
                    {
                        ApplyCheckOp(message);
                        return;
                    }
                    // An edit to a scene that isn't shared here (a teammate working in another scene): not ours to apply.
                    if (!string.IsNullOrEmpty(message.sc) && !EditorApplication.isPlayingOrWillChangePlaymode && !live.Contains(message.sc) && wantScene != message.sc)
                        return;
                    lastActivity = TeamSession.Now;
                    if (message.mt != "mat" && message.mt != "saved" && !EditorApplication.isPlayingOrWillChangePlaymode)
                        LogSceneEdit();
                    if (EditorApplication.isPlayingOrWillChangePlaymode)
                    {
                        Defer(message, blob);
                        return;
                    }
                    if (!ApplyOp(message))
                        Defer(message, blob);
                    repaintSoon = true;
                    return;
            }
        }

        private static void Defer(TeamMessage message, byte[] blob)
        {
            deferred.Add(new Deferred { Message = message, Blob = blob, Since = TeamSession.Now });
        }

        private static void RetryDeferred(bool force)
        {
            if (deferred.Count == 0 || EditorApplication.isPlayingOrWillChangePlaymode)
                return;
            if (!force && TeamSession.Now - lastRetry < 0.5)
                return;
            lastRetry = TeamSession.Now;

            var waiting = deferred.ToList();
            deferred.Clear();
            foreach (var item in waiting)
            {
                if (item.Message.t == "snap")
                {
                    LoadSnapshot(item.Message, item.Blob);
                    continue;
                }
                if (item.Message.t == "op" && !ApplyOp(item.Message))
                {
                    if (TeamSession.Now - item.Since < (TeamFiles.Receiving ? 600 : 120))
                        deferred.Add(item);
                    else
                        Debug.LogWarning("[WPFMA Team] Skipped a change from " + TeamSession.RemoteName + " because it needs an asset this project does not have: " + item.Message.f);
                }
            }
        }

        // ---- Snapshots --------------------------------------------------------------------------------------------

        private sealed class QueuedSnapshot
        {
            public string Path;
            public TeamPeer Peer;
            public double At;
        }

        private static readonly List<QueuedSnapshot> snapshotQueue = new List<QueuedSnapshot>();

        /// <summary>
        /// Sends a copy of a scene (to whoever asked, or everyone) once they have every new asset (up to a minute),
        /// so the scene never opens on their side with missing references.
        /// </summary>
        private static void QueueSnapshot(string path, TeamPeer peer = null)
        {
            if (TeamFiles.AwaitingCountFor(peer) == 0)
            {
                SendSnapshot(path, peer);
                return;
            }
            snapshotQueue.RemoveAll(q => q.Peer == peer && q.Path == (path ?? string.Empty));
            snapshotQueue.Add(new QueuedSnapshot { Path = path ?? string.Empty, Peer = peer, At = TeamSession.Now });
        }

        private static void PumpSnapshot()
        {
            if (snapshotQueue.Count == 0)
                return;
            foreach (var queued in snapshotQueue.ToList())
            {
                if (TeamFiles.AwaitingCountFor(queued.Peer) > 0 && TeamSession.Now - queued.At < 60)
                    continue;
                snapshotQueue.Remove(queued);
                SendSnapshot(queued.Path, queued.Peer);
            }
        }

        private static void Answer(TeamPeer peer, TeamMessage message, byte[] blob = null)
        {
            SendOutbox();
            if (peer != null)
                TeamSession.SendTo(peer, message, blob);
            else
                TeamSession.Send(message, blob);
        }

        private static void SendSnapshot(string path, TeamPeer peer = null)
        {
            Scene scene = default(Scene);
            if (string.IsNullOrEmpty(path))
                scene = SceneManager.GetActiveScene();
            else
                for (int i = 0; i < SceneManager.sceneCount; i++)
                    if (SceneManager.GetSceneAt(i).path == path)
                        scene = SceneManager.GetSceneAt(i);

            string who = peer != null ? peer.Name : TeamSession.RemoteName;
            if (!scene.IsValid() || !scene.isLoaded)
            {
                Answer(peer, new TeamMessage { t = "sfail", m = TeamSession.DisplayName + " does not have that scene open any more." });
                return;
            }
            if (string.IsNullOrEmpty(scene.path))
            {
                Answer(peer, new TeamMessage { t = "sfail", m = TeamSession.DisplayName + " needs to save their scene once before it can be shared." });
                TeamSession.AddSystem(who + " wants to open your scene. Save it once (Ctrl+S) and they can try again.");
                return;
            }
            if (EditorApplication.isPlayingOrWillChangePlaymode)
            {
                Answer(peer, new TeamMessage { t = "sfail", m = TeamSession.DisplayName + " is in Play mode. Try again when they stop." });
                return;
            }

            FinishGlides();
            byte[] bytes = SceneBytes(scene);
            if (bytes == null)
            {
                Answer(peer, new TeamMessage { t = "sfail", m = "Could not copy the scene on " + TeamSession.DisplayName + "'s side." });
                return;
            }

            // A scene already shared with someone keeps its ids (the others are using them); the copy carries every
            // object's id so the newcomer matches exactly.
            string prefix = "s" + Guid.NewGuid().ToString("N").Substring(0, 6);
            if (!live.Contains(scene.path))
                AssignIds(scene, prefix);
            live.Add(scene.path);
            if (TeamSession.IsHost)
            {
                if (peer != null)
                    LiveFor(peer).Add(scene.path);
                else
                    foreach (var other in TeamSession.Peers.Where(p => p.Link != null))
                        LiveFor(other).Add(scene.path);
            }
            else if (peer != null && !peer.IsHost)
                liveViaGuest.Add(scene.path);
            var ids = Walk(scene).Select(IdFor).ToArray();
            string meta = File.Exists(scene.path + ".meta") ? File.ReadAllText(scene.path + ".meta") : null;
            Answer(peer, new TeamMessage { t = "snap", f = scene.path, s = prefix, d = meta, a = ids }, bytes);
            TeamSession.AddSystem("Sent " + scene.name + " to " + who + ". You are now editing it together.");
        }

        private static byte[] SceneBytes(Scene scene)
        {
            string folder = Path.Combine("Temp", "WPFMATeam");
            Directory.CreateDirectory(folder);
            string copy = Path.Combine(folder, "snapshot.unity").Replace('\\', '/');

            copying++;
            try
            {
                TeamLocks.UnlockAll();
                if (EditorSceneManager.SaveScene(scene, copy, true) && File.Exists(copy))
                    return File.ReadAllBytes(copy);
            }
            catch (Exception)
            {
            }
            finally
            {
                copying--;
                TeamLocks.Refresh();
            }

            try
            {
                if (scene.isDirty)
                    EditorSceneManager.SaveScene(scene);
                return File.ReadAllBytes(scene.path);
            }
            catch (Exception)
            {
                return null;
            }
        }

        private static void LoadSnapshot(TeamMessage message, byte[] blob)
        {
            string path = message.f;
            // Whoever sent it (null when it waited for Play mode to end).
            var provider = TeamSession.Sender;
            if (blob == null || string.IsNullOrEmpty(path) || !path.StartsWith("Assets/", StringComparison.Ordinal) ||
                !path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase) || path.Contains(".."))
                return;

            var others = new List<Scene>();
            for (int i = 0; i < SceneManager.sceneCount; i++)
            {
                var open = SceneManager.GetSceneAt(i);
                if (open.isDirty && open.path != path && !live.Contains(open.path) && !wasLive.Contains(open.path))
                    others.Add(open);
            }
            if (others.Count > 0 && !EditorSceneManager.SaveModifiedScenesIfUserWantsTo(others.ToArray()))
            {
                wantScene = null;
                Notice = "Did not open " + Path.GetFileNameWithoutExtension(path) + " because you chose not to save your open scene.";
                TeamSession.Raise();
                return;
            }

            live.Add(path);
            try
            {
                TeamLocks.UnlockAll();
                opening = path;
                // Unity does not reload a scene that is already open, so step out of it before replacing the file.
                if (IsLoaded(path))
                    EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);

                Directory.CreateDirectory(Path.GetDirectoryName(path));
                if (File.Exists(path))
                {
                    string backup = Path.Combine(Path.GetDirectoryName(Application.dataPath), "WPFMA-Snapshots", "Team", "scenes",
                        DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Path.GetFileName(path));
                    Directory.CreateDirectory(Path.GetDirectoryName(backup));
                    File.Copy(path, backup, true);
                }
                File.WriteAllBytes(path, blob);
                if (!string.IsNullOrEmpty(message.d) && message.d.Contains("guid:"))
                    File.WriteAllText(path + ".meta", message.d, new System.Text.UTF8Encoding(false));
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);

                Scene scene;
                try
                {
                    scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Single);
                }
                finally
                {
                    opening = null;
                }
                live.Add(path);
                if (message.a != null && message.a.Length > 0 && !MapIds(scene, message.a))
                    AssignIds(scene, message.s);
                else if (message.a == null || message.a.Length == 0)
                    AssignIds(scene, message.s);
                wantScene = null;
                Notice = null;
                digestMisses = 0;
                if (TeamSession.IsHost && provider != null)
                    LiveFor(provider).Add(path);
                else if (!TeamSession.IsHost && provider != null && !provider.IsHost)
                    liveViaGuest.Add(path);
                else
                    liveViaGuest.Remove(path);
                // Only the editor it came from is now editing it with you.
                if (provider != null)
                    Answer(provider, new TeamMessage { t = "slive", f = path });
                else
                    Direct(new TeamMessage { t = "slive", f = path });
                TeamSession.AddSystem("Opened " + scene.name + " from " + (provider != null ? provider.Name : TeamSession.RemoteName) + ". You are editing it together now.");
                TeamLocks.Refresh();
            }
            catch (Exception e)
            {
                opening = null;
                live.Remove(path);
                wantScene = null;
                Notice = "Could not open the scene: " + e.Message;
            }
            TeamSession.Raise();
        }

        private static IEnumerable<GameObject> Walk(Scene scene)
        {
            foreach (var root in scene.GetRootGameObjects())
                foreach (var go in Walk(root))
                    yield return go;
        }

        private static IEnumerable<GameObject> Walk(GameObject go)
        {
            if (ToolOnly(go))
                yield break;
            yield return go;
            foreach (Transform child in go.transform)
                foreach (var inner in Walk(child.gameObject))
                    yield return inner;
        }

        /// <summary>Gives every object the id the sender has for it (same order on both sides). False if the counts differ.</summary>
        private static bool MapIds(Scene scene, string[] ids)
        {
            var objects = Walk(scene).ToList();
            if (objects.Count != ids.Length)
                return false;
            foreach (var pair in idOf.ToList())
            {
                var existing = EditorUtility.InstanceIDToObject(pair.Key) as GameObject;
                if (existing == null || existing.scene == scene)
                {
                    idOf.Remove(pair.Key);
                    objOf.Remove(pair.Value);
                }
            }
            for (int i = 0; i < objects.Count; i++)
            {
                Map(objects[i], ids[i]);
                foreach (var component in objects[i].GetComponents<Component>())
                    if (component != null)
                        knownComponents.Add(component.GetInstanceID());
            }
            lastShape.Clear();
            lastSent.Clear();
            return true;
        }

        private static void AssignIds(Scene scene, string prefix)
        {
            foreach (var pair in idOf.ToList())
            {
                var existing = EditorUtility.InstanceIDToObject(pair.Key) as GameObject;
                if (existing == null || existing.scene == scene)
                {
                    idOf.Remove(pair.Key);
                    objOf.Remove(pair.Value);
                }
            }

            int index = 0;
            foreach (var go in Walk(scene))
            {
                Map(go, prefix + "." + index++);
                foreach (var component in go.GetComponents<Component>())
                    if (component != null)
                        knownComponents.Add(component.GetInstanceID());
            }
            lastShape.Clear();
            lastSent.Clear();
        }

        // ---- Local changes ----------------------------------------------------------------------------------------

        private static void OnChanges(ref ObjectChangeEventStream stream)
        {
            if (!TeamSession.IsLinked || EditorApplication.isPlayingOrWillChangePlaymode)
                return;
            if (stream.length > 0)
                lastLocalEdit = TeamSession.Now;

            for (int i = 0; i < stream.length; i++)
            {
                try
                {
                    HandleChange(ref stream, i);
                }
                catch (Exception e)
                {
                    Debug.LogWarning("[WPFMA Team] Could not share a change: " + e.Message);
                }
            }
            SendOutbox();
        }

        private static void HandleChange(ref ObjectChangeEventStream stream, int i)
        {
            switch (stream.GetEventType(i))
            {
                case ObjectChangeKind.ChangeGameObjectOrComponentProperties:
                {
                    ChangeGameObjectOrComponentPropertiesEventArgs e;
                    stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out e);
                    dirty.Add(e.instanceId);
                    break;
                }
                case ObjectChangeKind.CreateGameObjectHierarchy:
                {
                    CreateGameObjectHierarchyEventArgs e;
                    stream.GetCreateGameObjectHierarchyEvent(i, out e);
                    var go = EditorUtility.InstanceIDToObject(e.instanceId) as GameObject;
                    if (InLive(go))
                    {
                        foreach (var item in Walk(go))
                            if (!idOf.ContainsKey(item.GetInstanceID()))
                                Map(item, "n" + Guid.NewGuid().ToString("N").Substring(0, 12));
                        SendTree(go, false);
                    }
                    break;
                }
                case ObjectChangeKind.ChangeGameObjectStructureHierarchy:
                {
                    ChangeGameObjectStructureHierarchyEventArgs e;
                    stream.GetChangeGameObjectStructureHierarchyEvent(i, out e);
                    var go = EditorUtility.InstanceIDToObject(e.instanceId) as GameObject;
                    if (InLive(go))
                        SendTree(go, false);
                    break;
                }
                case ObjectChangeKind.ChangeGameObjectStructure:
                {
                    ChangeGameObjectStructureEventArgs e;
                    stream.GetChangeGameObjectStructureEvent(i, out e);
                    var go = EditorUtility.InstanceIDToObject(e.instanceId) as GameObject;
                    if (InLive(go))
                        SendTree(go, true);
                    break;
                }
                case ObjectChangeKind.ChangeGameObjectParent:
                {
                    ChangeGameObjectParentEventArgs e;
                    stream.GetChangeGameObjectParentEvent(i, out e);
                    var go = EditorUtility.InstanceIDToObject(e.instanceId) as GameObject;
                    if (InLive(go))
                        SendMove(go);
                    break;
                }
                case ObjectChangeKind.DestroyGameObjectHierarchy:
                {
                    DestroyGameObjectHierarchyEventArgs e;
                    stream.GetDestroyGameObjectHierarchyEvent(i, out e);
                    string id;
                    if (idOf.TryGetValue(e.instanceId, out id))
                    {
                        idOf.Remove(e.instanceId);
                        objOf.Remove(id);
                        if (live.Contains(e.scene.path))
                            Send(new TeamMessage { t = "op", mt = "del", f = id, sc = e.scene.path });
                    }
                    break;
                }
                case ObjectChangeKind.ChangeScene:
                {
                    ChangeSceneEventArgs e;
                    stream.GetChangeSceneEvent(i, out e);
                    if (e.scene.IsValid() && live.Contains(e.scene.path))
                        SendRootOrder(e.scene);
                    break;
                }
                case ObjectChangeKind.ChangeAssetObjectProperties:
                {
                    ChangeAssetObjectPropertiesEventArgs e;
                    stream.GetChangeAssetObjectPropertiesEvent(i, out e);
                    TeamFiles.AssetTouched(e.instanceId);
                    var asset = EditorUtility.InstanceIDToObject(e.instanceId);
                    if (LiveAsset(asset) && !TeamStandIns.IsStandIn(asset))
                    {
                        dirtyMaterials.Add(e.instanceId);
                        localMaterialEdit[e.instanceId] = TeamSession.Now;
                    }
                    break;
                }
            }
        }

        /// <summary>
        /// Sends a scene change, unless it uses an asset the teammate is still receiving. Then it (and everything
        /// after it, to keep the order) waits until they have the asset.
        /// </summary>
        private static void Send(TeamMessage message)
        {
            lastActivity = TeamSession.Now;
            if (held.Count > 0 || UsesAwaitingAsset(message))
            {
                held.Enqueue(message);
                if (!heldNotice)
                {
                    heldNotice = true;
                    TeamSession.AddSystem("That uses something " + TeamSession.RemoteName + " is still receiving. It shows up for them as soon as they have it.");
                }
                return;
            }
            Post(message);
        }

        /// <summary>Adds a scene edit to this frame's message (sent at the end of the frame, or when it gets big).</summary>
        private static void Post(TeamMessage message)
        {
            outbox.Add(message);
            outboxSize += 96 + (message.json != null ? message.json.Length : 0) + (message.a != null ? message.a.Length * 24 : 0);
            if (outbox.Count >= 256 || outboxSize > 192 * 1024)
                SendOutbox();
        }

        /// <summary>Sends the edits waiting in this frame's message: one on its own, several as one "ops" message.</summary>
        internal static void SendOutbox()
        {
            if (outbox.Count == 0)
                return;
            if (!TeamSession.IsLinked)
            {
                outbox.Clear();
                outboxSize = 0;
                return;
            }
            if (outbox.Count == 1)
                TeamSession.Send(outbox[0]);
            else
            {
                var text = new StringBuilder(outboxSize + 32);
                text.Append("{\"list\":[");
                for (int i = 0; i < outbox.Count; i++)
                {
                    if (i > 0)
                        text.Append(',');
                    text.Append(TeamPacket.EncodeText(outbox[i]));
                }
                text.Append("]}");
                TeamSession.Send(new TeamMessage { t = "ops", json = text.ToString() });
            }
            outbox.Clear();
            outboxSize = 0;
        }

        /// <summary>Sends a message right away, after the scene edits made before it (so the order stays the same).</summary>
        private static void Direct(TeamMessage message, byte[] blob = null)
        {
            SendOutbox();
            TeamSession.Send(message, blob);
        }

        private static void Reply(TeamMessage message)
        {
            SendOutbox();
            TeamSession.Reply(message);
        }

        internal static int HeldCount
        {
            get { return held.Count; }
        }

        private static bool UsesAwaitingAsset(TeamMessage message)
        {
            if (TeamFiles.AwaitingCount == 0)
                return false;
            if (message.mt == "mat" && TeamFiles.IsAwaitingGuid(message.f))
                return true;
            foreach (var text in new[] { message.json, message.f })
            {
                if (string.IsNullOrEmpty(text))
                    continue;
                foreach (Match match in AssetGuid.Matches(text))
                    if (TeamFiles.IsAwaitingGuid(match.Groups[1].Value))
                        return true;
            }
            return false;
        }

        private static void ReleaseHeld()
        {
            while (held.Count > 0 && !UsesAwaitingAsset(held.Peek()))
                Post(held.Dequeue());
            if (held.Count == 0)
                heldNotice = false;
        }

        private static void Flush()
        {
            if (TeamSession.Now - lastFlush < FlushInterval)
                return;
            lastFlush = TeamSession.Now;

            if (dirty.Count > 0 && live.Count == 0)
                dirty.Clear();
            if (dirty.Count > 0)
            {
                var ids = dirty.ToList();
                dirty.Clear();
                foreach (var instance in ids)
                {
                    var obj = EditorUtility.InstanceIDToObject(instance);
                    if (obj == null)
                        continue;

                    var go = obj as GameObject;
                    if (go != null)
                    {
                        if (!InLive(go))
                            continue;
                        var props = new TeamGo
                        {
                            name = go.name,
                            active = go.activeSelf,
                            layer = go.layer,
                            tag = go.tag,
                            flags = (int)GameObjectUtility.GetStaticEditorFlags(go)
                        };
                        SendIfChanged("g:" + IdFor(go), new TeamMessage { t = "op", mt = "g", f = IdFor(go), json = JsonUtility.ToJson(props), sc = go.scene.path });
                        continue;
                    }

                    var component = obj as Component;
                    if (component == null || !InLive(component.gameObject) || !Syncable(component))
                        continue;

                    var transform = component as Transform;
                    if (transform != null && !(transform is RectTransform))
                    {
                        // Gliding to a teammate's position: that's their move, not yours (unless you grabbed it).
                        Glide glide;
                        if (glides.TryGetValue(transform.gameObject.GetInstanceID(), out glide))
                        {
                            if (SamePose(transform, glide.LastSet))
                                continue;
                            glides.Remove(transform.gameObject.GetInstanceID());
                        }
                        SendIfChanged("t:" + IdFor(transform.gameObject), new TeamMessage
                        {
                            t = "op",
                            mt = "t",
                            f = IdFor(transform.gameObject),
                            p = TransformValues(transform),
                            sc = transform.gameObject.scene.path
                        });
                        continue;
                    }

                    string key = ComponentKey(component);
                    SendIfChanged("c:" + key, new TeamMessage { t = "op", mt = "c", f = key, json = Capture(component), sc = component.gameObject.scene.path });
                }
            }

            if (dirtyMaterials.Count > 0)
            {
                var ids = dirtyMaterials.ToList();
                dirtyMaterials.Clear();
                foreach (var instance in ids)
                {
                    var asset = EditorUtility.InstanceIDToObject(instance);
                    if (!LiveAsset(asset) || TeamStandIns.IsStandIn(asset))
                        continue;
                    string path = AssetDatabase.GetAssetPath(asset);
                    if (!TeamFiles.Shared(path))
                        continue;
                    string guid = AssetDatabase.AssetPathToGUID(path);
                    SendIfChanged("m:" + guid, new TeamMessage { t = "op", mt = "mat", f = guid, json = Capture(asset) });
                }
            }
        }

        private static void SendIfChanged(string key, TeamMessage message)
        {
            string payload = message.json ?? string.Join(",", (message.p ?? new float[0]).Select(v => v.ToString("R")).ToArray());
            string previous;
            if (lastSent.TryGetValue(key, out previous) && previous == payload)
                return;
            lastSent[key] = payload;
            Send(message);
        }

        private static float[] TransformValues(Transform t)
        {
            var p = t.localPosition;
            var r = t.localRotation;
            var s = t.localScale;
            return new[] { p.x, p.y, p.z, r.x, r.y, r.z, r.w, s.x, s.y, s.z };
        }

        private static void SendMove(GameObject go)
        {
            string parent = go.transform.parent != null ? IdFor(go.transform.parent.gameObject) : string.Empty;
            string shape = parent + "@" + go.transform.GetSiblingIndex();
            string id = IdFor(go);
            string previous;
            if (lastShape.TryGetValue("mv:" + id, out previous) && previous == shape)
                return;
            lastShape["mv:" + id] = shape;
            Send(new TeamMessage { t = "op", mt = "move", f = id, a = new[] { parent }, n = go.transform.GetSiblingIndex(), s = go.scene.path, p = TransformValues(go.transform), sc = go.scene.path });
        }

        private static void SendRootOrder(Scene scene)
        {
            var ids = scene.GetRootGameObjects().Where(InLive).Select(IdFor).ToArray();
            string shape = string.Join("|", ids);
            string previous;
            if (lastShape.TryGetValue("order:" + scene.path, out previous) && previous == shape)
                return;
            lastShape["order:" + scene.path] = shape;
            Send(new TeamMessage { t = "op", mt = "order", s = scene.path, a = ids, sc = scene.path });
        }

        private static string Shape(GameObject go, bool deep)
        {
            var text = new StringBuilder();
            foreach (var item in deep ? Walk(go) : new[] { go })
            {
                text.Append(IdFor(item)).Append('<').Append(item.transform.parent != null ? IdFor(item.transform.parent.gameObject) : "-")
                    .Append(PrefabUtility.IsOutermostPrefabInstanceRoot(item) ? "P[" : "[");
                foreach (var component in item.GetComponents<Component>())
                    text.Append(component != null ? component.GetType().Name : "?").Append(',');
                text.Append(']');
            }
            return text.ToString();
        }

        private static void SendTree(GameObject root, bool shallow)
        {
            string key = (shallow ? "s:" : "d:") + IdFor(root);
            string shape = Shape(root, !shallow);
            string previous;
            if (lastShape.TryGetValue(key, out previous) && previous == shape)
                return;

            var tree = BuildTree(root, shallow);
            lastShape[key] = shape;
            Send(new TeamMessage { t = "op", mt = "tree", json = JsonUtility.ToJson(tree), sc = root.scene.path });
        }

        private static TeamTree BuildTree(GameObject root, bool shallow)
        {
            var nodes = new List<TeamNode>();
            var owners = new Dictionary<GameObject, List<GameObject>>();

            foreach (var go in shallow ? new[] { root } : Walk(root))
            {
                if (!idOf.ContainsKey(go.GetInstanceID()))
                    Map(go, "n" + Guid.NewGuid().ToString("N").Substring(0, 12));

                var node = new TeamNode
                {
                    id = IdFor(go),
                    parent = go.transform.parent != null ? IdFor(go.transform.parent.gameObject) : string.Empty,
                    sibling = go.transform.GetSiblingIndex(),
                    name = go.name,
                    active = go.activeSelf,
                    layer = go.layer,
                    tag = go.tag,
                    flags = (int)GameObjectUtility.GetStaticEditorFlags(go),
                    tr = TransformValues(go.transform),
                    prefab = string.Empty,
                    owner = string.Empty
                };

                if (PrefabUtility.IsOutermostPrefabInstanceRoot(go))
                {
                    node.pk = true;
                    var source = PrefabUtility.GetCorrespondingObjectFromSource(go);
                    if (source != null)
                    {
                        node.prefab = GlobalObjectId.GetGlobalObjectIdSlow(source).ToString();
                        owners[go] = Walk(go).Where(g => !PrefabUtility.IsAddedGameObjectOverride(g)).ToList();
                    }
                }

                var owner = PrefabUtility.IsPartOfPrefabInstance(go) ? PrefabUtility.GetOutermostPrefabInstanceRoot(go) : null;
                if (owner != null)
                {
                    List<GameObject> members;
                    if (!owners.TryGetValue(owner, out members))
                    {
                        members = Walk(owner).Where(g => !PrefabUtility.IsAddedGameObjectOverride(g)).ToList();
                        owners[owner] = members;
                    }
                    int index = members.IndexOf(go);
                    if (index >= 0)
                    {
                        node.owner = IdFor(owner);
                        node.pi = index;
                    }
                }

                var types = new List<string>();
                var json = new List<string>();
                foreach (var component in go.GetComponents<Component>())
                {
                    if (component == null)
                    {
                        types.Add(MissingScript);
                        json.Add(string.Empty);
                        continue;
                    }
                    if (!Syncable(component))
                        continue;
                    types.Add(TypeName(component.GetType()));
                    bool fresh = knownComponents.Add(component.GetInstanceID());
                    bool plainTransform = component is Transform && !(component is RectTransform);
                    json.Add(fresh && !plainTransform ? Capture(component) : string.Empty);
                }
                node.types = types.ToArray();
                node.json = json.ToArray();
                nodes.Add(node);
            }

            return new TeamTree { scene = root.scene.path, shallow = shallow, nodes = nodes.ToArray() };
        }

        // ---- Applying changes from the teammate -------------------------------------------------------------------

        /// <summary>Returns false when the change needs an asset that has not arrived yet (it is retried later).</summary>
        private static bool ApplyOp(TeamMessage message)
        {
            try
            {
                switch (message.mt)
                {
                    case "g":
                        ApplyGameObject(message);
                        return true;
                    case "t":
                        ApplyTransform(message);
                        return true;
                    case "c":
                        return ApplyComponent(message);
                    case "tree":
                        FinishGlides();
                        return ApplyTree(JsonUtility.FromJson<TeamTree>(message.json));
                    case "del":
                        FinishGlides();
                        ApplyDelete(message.f);
                        return true;
                    case "move":
                        FinishGlides();
                        ApplyMove(message);
                        return true;
                    case "order":
                        ApplyOrder(message);
                        return true;
                    case "mat":
                        return ApplyMaterial(message);
                    case "saved":
                        ApplySaved(message.f);
                        return true;
                    case "dig":
                        ApplyCheckOp(message);
                        return true;
                    case "rs":
                        return ApplySceneSettings(message);
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA Team] Could not apply a change from " + TeamSession.RemoteName + ": " + e.Message);
            }
            return true;
        }

        private static void ApplyGameObject(TeamMessage message)
        {
            var go = Find(message.f);
            if (go == null || string.IsNullOrEmpty(message.json))
                return;
            var props = JsonUtility.FromJson<TeamGo>(message.json);
            SetGameObject(go, props.name, props.active, props.layer, props.tag, props.flags);
            lastSent["g:" + message.f] = JsonUtility.ToJson(new TeamGo
            {
                name = go.name,
                active = go.activeSelf,
                layer = go.layer,
                tag = go.tag,
                flags = (int)GameObjectUtility.GetStaticEditorFlags(go)
            });
            MarkDirty(go);
        }

        private static void SetGameObject(GameObject go, string name, bool active, int layer, string tag, int flags)
        {
            if (go.name != name)
                go.name = name;
            if (go.activeSelf != active)
                go.SetActive(active);
            if (go.layer != layer)
                go.layer = layer;
            if (!string.IsNullOrEmpty(tag) && go.tag != tag)
            {
                try
                {
                    go.tag = tag;
                }
                catch (UnityException)
                {
                }
            }
            if ((int)GameObjectUtility.GetStaticEditorFlags(go) != flags)
                GameObjectUtility.SetStaticEditorFlags(go, (StaticEditorFlags)flags);
            KeepAsOverride(go);
        }

        /// <summary>
        /// A value set on something inside a placed prefab is recorded as an override, the way an Inspector edit is.
        /// Otherwise Unity drops it the next time the prefab file changes.
        /// </summary>
        private static void KeepAsOverride(UnityEngine.Object target)
        {
            if (target != null && !EditorUtility.IsPersistent(target) && PrefabUtility.IsPartOfPrefabInstance(target))
                PrefabUtility.RecordPrefabInstancePropertyModifications(target);
        }

        private static void ApplyTransform(TeamMessage message)
        {
            var go = Find(message.f);
            if (go == null || message.p == null || message.p.Length != 10)
                return;
            int id = go.GetInstanceID();
            double previous;
            // One change lands straight away; a stream of them (a teammate dragging) glides from one to the next.
            bool streaming = lastRemoteMove.TryGetValue(id, out previous) && TeamSession.Now - previous < 0.3;
            lastRemoteMove[id] = TeamSession.Now;
            if (!streaming || go.transform is RectTransform)
            {
                glides.Remove(id);
                SetTransform(go.transform, message.p);
                lastSent["t:" + message.f] = string.Join(",", TransformValues(go.transform).Select(v => v.ToString("R")).ToArray());
                MarkDirty(go);
                return;
            }

            Glide glide;
            if (!glides.TryGetValue(id, out glide))
            {
                glide = new Glide { Id = message.f, T = go.transform };
                glides[id] = glide;
            }
            glide.From = TransformValues(go.transform);
            glide.To = message.p;
            glide.LastSet = glide.From;
            glide.Start = TeamSession.Now;
            lastSent["t:" + message.f] = string.Join(",", message.p.Select(v => v.ToString("R")).ToArray());
            MarkDirty(go);
        }

        private static bool SamePose(Transform t, float[] v)
        {
            if (v == null || v.Length != 10)
                return false;
            var p = t.localPosition;
            var r = t.localRotation;
            var s = t.localScale;
            return p.x == v[0] && p.y == v[1] && p.z == v[2] && r.x == v[3] && r.y == v[4] && r.z == v[5] && r.w == v[6] &&
                   s.x == v[7] && s.y == v[8] && s.z == v[9];
        }

        /// <summary>Moves gliding objects along (every frame while a teammate drags something).</summary>
        private static void StepGlides()
        {
            if (glides.Count == 0)
                return;
            glideDone.Clear();
            foreach (var pair in glides)
            {
                var g = pair.Value;
                if (g.T == null)
                {
                    glideDone.Add(pair.Key);
                    continue;
                }
                float k = (float)((TeamSession.Now - g.Start) / GlideTime);
                if (k >= 1f)
                {
                    glideDone.Add(pair.Key);
                    continue;
                }
                var f = g.From;
                var to = g.To;
                g.T.localPosition = Vector3.LerpUnclamped(new Vector3(f[0], f[1], f[2]), new Vector3(to[0], to[1], to[2]), k);
                g.T.localRotation = Quaternion.Slerp(new Quaternion(f[3], f[4], f[5], f[6]), new Quaternion(to[3], to[4], to[5], to[6]), k);
                g.T.localScale = Vector3.LerpUnclamped(new Vector3(f[7], f[8], f[9]), new Vector3(to[7], to[8], to[9]), k);
                g.LastSet = TransformValues(g.T);
            }
            foreach (var id in glideDone)
                EndGlide(id);
            repaintSoon = true;
        }

        private static void EndGlide(int id)
        {
            Glide g;
            if (!glides.TryGetValue(id, out g))
                return;
            glides.Remove(id);
            if (g.T == null)
                return;
            SetTransform(g.T, g.To);
            lastSent["t:" + g.Id] = string.Join(",", TransformValues(g.T).Select(v => v.ToString("R")).ToArray());
            float[] pose;
            if (poses.TryGetValue(id, out pose))
                ReadPose(g.T, pose);
        }

        /// <summary>Puts everything that's gliding where it's going (before a copy of the scene, a move, or Play mode).</summary>
        private static void FinishGlides()
        {
            if (glides.Count == 0)
                return;
            foreach (var id in glides.Keys.ToList())
                EndGlide(id);
        }

        private static void SetTransform(Transform t, float[] v)
        {
            if (v == null || v.Length != 10)
                return;
            t.localPosition = new Vector3(v[0], v[1], v[2]);
            t.localRotation = new Quaternion(v[3], v[4], v[5], v[6]);
            t.localScale = new Vector3(v[7], v[8], v[9]);
            KeepAsOverride(t);
        }

        private static bool ApplyComponent(TeamMessage message)
        {
            var component = ResolveComponent(message.f);
            if (component == null)
                return true;
            if (!Overwrite(component, message.json))
                return false;
            lastSent["c:" + message.f] = Capture(component);
            MarkDirty(component.gameObject);
            ChangedByTeammate(component);
            return true;
        }

        private static bool ApplyMaterial(TeamMessage message)
        {
            string path = AssetDatabase.GUIDToAssetPath(message.f);
            if (string.IsNullOrEmpty(path))
                return false;
            var asset = AssetDatabase.LoadMainAssetAtPath(path);
            if (asset == null)
                return false;
            if (!LiveAsset(asset))
                return true;
            if (!Overwrite(asset, message.json))
                return false;
            lastSent["m:" + message.f] = Capture(asset);
            // Saving these values later is not our edit: the teammate sends their own saved file.
            TeamFiles.ValuesFromTeammate(path, TeamSession.Sender);
            ChangedByTeammate(asset);
            return true;
        }

        private static bool Overwrite(UnityEngine.Object target, string capture)
        {
            if (string.IsNullOrEmpty(capture))
                return true;
            string json, refs;
            SplitCapture(capture, out json, out refs);

            bool missing;
            string local = Restore(json, out missing);
            if (missing || WaitingForAsset(json) || RefsMissing(refs))
                return false;
            EditorJsonUtility.FromJsonOverwrite(local, target);

            // Then every link, set through SerializedObject so links inside prefabs (bones...) are right too.
            if (refs.Length > 0)
            {
                var serialized = new SerializedObject(target);
                foreach (var entry in refs.Split(new[] { RefEnd }, StringSplitOptions.RemoveEmptyEntries))
                {
                    int sep = entry.IndexOf(RefSep);
                    if (sep <= 0)
                        continue;
                    var property = serialized.FindProperty(entry.Substring(0, sep));
                    if (property == null || property.propertyType != SerializedPropertyType.ObjectReference)
                        continue;
                    bool unused;
                    var value = ResolvePortable(entry.Substring(sep + 1), out unused);
                    if (property.objectReferenceValue != value)
                        property.objectReferenceValue = value;
                }
                serialized.ApplyModifiedPropertiesWithoutUndo();
            }
            KeepAsOverride(target);
            return true;
        }

        private static void ApplyDelete(string id)
        {
            var go = Find(id);
            if (go == null)
                return;
            foreach (var item in Walk(go).ToList())
                Unmap(item);
            var scene = go.scene;
            try
            {
                if (PrefabUtility.IsPartOfPrefabInstance(go) && !PrefabUtility.IsOutermostPrefabInstanceRoot(go) && !PrefabUtility.IsAddedGameObjectOverride(go))
                    go.SetActive(false);
                else
                    UnityEngine.Object.DestroyImmediate(go);
            }
            catch (Exception)
            {
            }
            if (scene.IsValid())
                EditorSceneManager.MarkSceneDirty(scene);
        }

        private static void ApplyMove(TeamMessage message)
        {
            var go = Find(message.f);
            if (go == null)
                return;
            string parentId = message.a != null && message.a.Length > 0 ? message.a[0] : string.Empty;
            var parent = string.IsNullOrEmpty(parentId) ? null : Find(parentId);
            Place(go, parent, message.n, message.s);
            SetTransform(go.transform, message.p);
            lastShape["mv:" + message.f] = parentId + "@" + go.transform.GetSiblingIndex();
            MarkDirty(go);
        }

        private static void Place(GameObject go, GameObject parent, int sibling, string scenePath)
        {
            bool fixedInPrefab = PrefabUtility.IsPartOfPrefabInstance(go) && !PrefabUtility.IsOutermostPrefabInstanceRoot(go) && !PrefabUtility.IsAddedGameObjectOverride(go);
            if (!fixedInPrefab)
            {
                var target = parent != null ? parent.transform : null;
                if (go.transform.parent != target)
                    go.transform.SetParent(target, false);
                if (target == null && !string.IsNullOrEmpty(scenePath) && go.scene.path != scenePath)
                {
                    var scene = SceneManager.GetSceneByPath(scenePath);
                    if (scene.IsValid() && scene.isLoaded)
                        SceneManager.MoveGameObjectToScene(go, scene);
                }
            }
            if (go.transform.GetSiblingIndex() != sibling)
                go.transform.SetSiblingIndex(sibling);
        }

        private static void ApplyOrder(TeamMessage message)
        {
            if (message.a == null)
                return;
            for (int i = 0; i < message.a.Length; i++)
            {
                var go = Find(message.a[i]);
                if (go != null && go.transform.parent == null && go.transform.GetSiblingIndex() != i)
                    go.transform.SetSiblingIndex(i);
            }
            var scene = SceneManager.GetSceneByPath(message.s);
            if (scene.IsValid())
            {
                lastShape["order:" + message.s] = string.Join("|", scene.GetRootGameObjects().Where(InLive).Select(IdFor).ToArray());
                EditorSceneManager.MarkSceneDirty(scene);
            }
        }

        private static void ApplySaved(string path)
        {
            var scene = SceneManager.GetSceneByPath(path);
            if (!scene.IsValid() || !scene.isLoaded || !scene.isDirty || !live.Contains(path))
                return;
            TeamLocks.UnlockAll();
            try
            {
                EditorSceneManager.SaveScene(scene);
            }
            finally
            {
                TeamLocks.Refresh();
            }
        }

        private static bool ApplyTree(TeamTree tree)
        {
            if (tree == null || tree.nodes == null || tree.nodes.Length == 0 || !live.Contains(tree.scene))
                return true;

            var scene = SceneManager.GetSceneByPath(tree.scene);
            if (!scene.IsValid() || !scene.isLoaded)
                return true;

            foreach (var node in tree.nodes)
                foreach (var capture in node.json ?? new string[0])
                {
                    if (string.IsNullOrEmpty(capture))
                        continue;
                    string json, refs;
                    SplitCapture(capture, out json, out refs);
                    if (MissingAsset(json) || RefsMissing(refs))
                        return false;
                }
            foreach (var node in tree.nodes)
                if (!string.IsNullOrEmpty(node.prefab) && Find(node.id) == null && ResolveAsset(node.prefab) == null)
                    return false;

            var ownerMembers = new Dictionary<string, List<GameObject>>();
            Func<string, List<GameObject>> members = ownerId =>
            {
                List<GameObject> list;
                if (ownerMembers.TryGetValue(ownerId, out list))
                    return list;
                var ownerGo = Find(ownerId);
                list = ownerGo != null ? Walk(ownerGo).Where(g => !PrefabUtility.IsAddedGameObjectOverride(g)).ToList() : null;
                if (list != null)
                    ownerMembers[ownerId] = list;
                return list;
            };

            // 1. Find or create every object.
            foreach (var node in tree.nodes)
            {
                if (Find(node.id) != null)
                    continue;

                GameObject go = null;
                if (!string.IsNullOrEmpty(node.prefab))
                {
                    var asset = ResolveAsset(node.prefab) as GameObject;
                    if (asset != null)
                    {
                        go = PrefabUtility.InstantiatePrefab(asset, scene) as GameObject;
                        if (go != null)
                            ownerMembers[node.id] = Walk(go).Where(g => !PrefabUtility.IsAddedGameObjectOverride(g)).ToList();
                    }
                }
                else if (!string.IsNullOrEmpty(node.owner) && node.pi >= 0)
                {
                    var list = members(node.owner);
                    if (list != null && node.pi < list.Count)
                        go = list[node.pi];
                }

                if (go == null)
                {
                    go = new GameObject(node.name);
                    SceneManager.MoveGameObjectToScene(go, scene);
                }

                Map(go, node.id);
                foreach (var component in go.GetComponents<Component>())
                    if (component != null)
                        knownComponents.Add(component.GetInstanceID());
            }

            // 2. Place, name and set up components.
            var matched = new Dictionary<TeamNode, Component[]>();
            foreach (var node in tree.nodes)
            {
                var go = Find(node.id);
                if (go == null)
                    continue;

                // Unpacked on the teammate's side: unpack here too (one level at a time, so nested prefabs match).
                if (!node.pk && PrefabUtility.IsOutermostPrefabInstanceRoot(go))
                {
                    PrefabUtility.UnpackPrefabInstance(go, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
                    ownerMembers.Clear();
                }

                Place(go, string.IsNullOrEmpty(node.parent) ? null : Find(node.parent), node.sibling, tree.scene);
                SetGameObject(go, node.name, node.active, node.layer, node.tag, node.flags);
                SetTransform(go.transform, node.tr);
                lastSent["t:" + node.id] = string.Join(",", TransformValues(go.transform).Select(v => v.ToString("R")).ToArray());
                matched[node] = MatchComponents(go, node.types ?? new string[0]);
            }

            // 3. Component values, now that everything they can point at exists.
            foreach (var node in tree.nodes)
            {
                Component[] components;
                if (!matched.TryGetValue(node, out components) || node.json == null)
                    continue;
                for (int i = 0; i < components.Length && i < node.json.Length; i++)
                {
                    if (components[i] == null || string.IsNullOrEmpty(node.json[i]))
                        continue;
                    Overwrite(components[i], node.json[i]);
                    lastSent["c:" + ComponentKey(components[i])] = Capture(components[i]);
                }
            }

            // 4. Remove children the teammate no longer has.
            if (!tree.shallow)
            {
                var keep = new HashSet<string>(tree.nodes.Select(n => n.id));
                foreach (var node in tree.nodes)
                {
                    var go = Find(node.id);
                    if (go == null)
                        continue;
                    foreach (Transform child in go.transform.Cast<Transform>().ToList())
                    {
                        if (ToolOnly(child.gameObject))
                            continue;
                        string childId;
                        if (idOf.TryGetValue(child.gameObject.GetInstanceID(), out childId) && keep.Contains(childId))
                            continue;
                        if (PrefabUtility.IsPartOfPrefabInstance(child.gameObject) && !PrefabUtility.IsAddedGameObjectOverride(child.gameObject) &&
                            !PrefabUtility.IsOutermostPrefabInstanceRoot(child.gameObject))
                            continue;
                        foreach (var item in Walk(child.gameObject).ToList())
                            Unmap(item);
                        UnityEngine.Object.DestroyImmediate(child.gameObject);
                    }
                }
            }

            var rootGo = Find(tree.nodes[0].id);
            if (rootGo != null)
            {
                lastShape[(tree.shallow ? "s:" : "d:") + tree.nodes[0].id] = Shape(rootGo, !tree.shallow);
                lastShape["s:" + tree.nodes[0].id] = Shape(rootGo, false);
                foreach (var item in tree.shallow ? new[] { rootGo } : Walk(rootGo))
                {
                    lastShape["mv:" + IdFor(item)] = (item.transform.parent != null ? IdFor(item.transform.parent.gameObject) : string.Empty) + "@" + item.transform.GetSiblingIndex();
                    lastShape["d:" + IdFor(item)] = Shape(item, true);
                    lastShape["s:" + IdFor(item)] = Shape(item, false);
                }
            }

            EditorSceneManager.MarkSceneDirty(scene);
            return true;
        }

        private const string MissingScript = "?";

        private static Component[] MatchComponents(GameObject go, string[] typeNames)
        {
            var local = go.GetComponents<Component>().Where(c => c != null && Syncable(c)).ToList();
            var used = new HashSet<Component>();
            var result = new Component[typeNames.Length];
            bool unknown = false;

            for (int i = 0; i < typeNames.Length; i++)
            {
                if (typeNames[i] == MissingScript)
                {
                    unknown = true;
                    continue;
                }

                var type = FindType(typeNames[i]);
                if (type == null)
                {
                    unknown = true;
                    TeamProject.NoteMissingScript(typeNames[i]);
                    continue;
                }

                var match = local.FirstOrDefault(c => c.GetType() == type && !used.Contains(c));
                if (match == null && type != typeof(Transform) && type != typeof(RectTransform))
                {
                    try
                    {
                        match = go.AddComponent(type);
                    }
                    catch (Exception)
                    {
                        match = null;
                    }
                    if (match != null)
                        knownComponents.Add(match.GetInstanceID());
                }
                if (match != null)
                    used.Add(match);
                result[i] = match;
            }

            // When the teammate has a script this editor lacks (or the other way round), removing "extra"
            // scripts could delete the wrong one, so only built-in components are removed then.
            foreach (var component in local)
            {
                if (used.Contains(component) || component is Transform)
                    continue;
                if (unknown && component is MonoBehaviour)
                    continue;
                try
                {
                    UnityEngine.Object.DestroyImmediate(component);
                }
                catch (Exception)
                {
                }
            }

            return result;
        }

        private static void MarkDirty(GameObject go)
        {
            if (go != null && go.scene.IsValid())
                EditorSceneManager.MarkSceneDirty(go.scene);
        }

        // ---- Keeping both scenes the same -------------------------------------------------------------------------

        /// <summary>Fingerprint of a shared scene's objects and components, or null if it is not open here.</summary>
        internal static string DigestOf(string path)
        {
            var scene = SceneManager.GetSceneByPath(path);
            return scene.IsValid() && scene.isLoaded ? Digest(scene) : null;
        }

        /// <summary>
        /// The meshes and materials a renderer uses, so a model that is invisible or unshaded on one side counts as
        /// a difference. Only shared files count (the guest may not have the host's paid, unshared assets) and empty
        /// references are skipped, so both sides agree whenever the shared parts match.
        /// </summary>
        private static void AppendAssets(StringBuilder text, Component component)
        {
            var renderer = component as Renderer;
            if (renderer != null)
            {
                foreach (var material in renderer.sharedMaterials)
                    AppendAsset(text, material);
                var skinned = renderer as SkinnedMeshRenderer;
                if (skinned != null)
                    AppendAsset(text, skinned.sharedMesh);
                return;
            }
            var filter = component as MeshFilter;
            if (filter != null)
                AppendAsset(text, filter.sharedMesh);
        }

        private static void AppendAsset(StringBuilder text, UnityEngine.Object asset)
        {
            if (asset == null)
                return;
            string path = AssetDatabase.GetAssetPath(asset);
            string guid;
            long file;
            if (string.IsNullOrEmpty(path) || !TeamFiles.Shared(path) || !AssetDatabase.TryGetGUIDAndLocalFileIdentifier(asset, out guid, out file))
                return;
            text.Append(guid).Append(':').Append(file).Append(';');
        }

        private static bool Quiet
        {
            get
            {
                return TeamSession.Now - lastActivity > 3.0 && dirty.Count == 0 && deferred.Count == 0 && held.Count == 0 && TeamSession.Backlog == 0 &&
                       !EditorApplication.isPlayingOrWillChangePlaymode && TeamFiles.SendingCount == 0;
            }
        }

        // ---- References -------------------------------------------------------------------------------------------

        private static bool Syncable(Component component)
        {
            // Never saved, or hidden by the tool that added it (like NDMF's AvatarActivator): not part of anyone's scene.
            if ((component.hideFlags & (HideFlags.DontSaveInEditor | HideFlags.HideInInspector)) != 0)
                return false;
            var type = component.GetType();
            bool ok;
            if (!typeCache.TryGetValue(type, out ok))
            {
                ok = !type.FullName.StartsWith("UnityEditor.", StringComparison.Ordinal);
                typeCache[type] = ok;
            }
            return ok;
        }

        private static string TypeName(Type type)
        {
            return type.FullName + ", " + type.Assembly.GetName().Name;
        }

        private static readonly Dictionary<string, Type> typeLookup = new Dictionary<string, Type>();

        private static Type FindType(string name)
        {
            Type type;
            if (typeLookup.TryGetValue(name, out type))
                return type;
            type = Type.GetType(name);
            if (type == null)
            {
                string fullName = name.Split(',')[0].Trim();
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    type = assembly.GetType(fullName);
                    if (type != null)
                        break;
                }
            }
            if (type != null && !typeof(Component).IsAssignableFrom(type))
                type = null;
            typeLookup[name] = type;
            return type;
        }

        private static string ComponentKey(Component component)
        {
            var type = component.GetType();
            int k = 0;
            foreach (var other in component.gameObject.GetComponents(type))
            {
                if (other == component)
                    break;
                if (other != null && other.GetType() == type)
                    k++;
            }
            return IdFor(component.gameObject) + "#" + TypeName(type) + "#" + k;
        }

        private static Component ResolveComponent(string key)
        {
            var parts = key.Split('#');
            if (parts.Length != 3)
                return null;
            var go = Find(parts[0]);
            var type = FindType(parts[1]);
            int k;
            if (go == null || type == null || !int.TryParse(parts[2], out k))
                return null;
            var list = go.GetComponents(type).Where(c => c != null && c.GetType() == type).ToList();
            return k < list.Count ? list[k] : null;
        }

        private static UnityEngine.Object ResolveAsset(string globalId)
        {
            GlobalObjectId id;
            if (!GlobalObjectId.TryParse(globalId, out id))
                return null;
            return GlobalObjectId.GlobalObjectIdentifierToObjectSlow(id);
        }

        /// <summary>EditorJsonUtility of an object with Unity instance ids swapped for ids both editors share.</summary>
        // Separates the values (JSON) from the links to other objects and assets in a captured component.
        private const char RefsMark = '\u0001';
        private const char RefSep = '\u0002';
        private const char RefEnd = '\u0003';

        /// <summary>
        /// A component's values, ready to send. Values come from Unity's JSON; links to other objects and assets are
        /// read separately through SerializedObject, because the JSON writes links between objects inside a placed
        /// prefab (bones, root bones...) as empty.
        /// </summary>
        private static string Capture(UnityEngine.Object target)
        {
            string json = EditorJsonUtility.ToJson(target);
            json = StripKeys(json);
            json = InstanceRef.Replace(json, match =>
            {
                int instance;
                int.TryParse(match.Groups[1].Value, out instance);
                return "{\"wref\":\"" + Portable(instance) + "\"}";
            });
            string refs = CaptureRefs(target);
            return refs.Length == 0 ? json : json + RefsMark + refs;
        }

        private static string CaptureRefs(UnityEngine.Object target)
        {
            var text = new StringBuilder();
            var property = new SerializedObject(target).GetIterator();
            bool enter = true;
            while (property.Next(enter))
            {
                enter = property.propertyType != SerializedPropertyType.String;
                if (property.propertyType != SerializedPropertyType.ObjectReference)
                    continue;
                string path = property.propertyPath;
                int dot = path.IndexOf('.');
                if (StrippedKeys.Contains(dot < 0 ? path : path.Substring(0, dot)))
                    continue;
                var value = property.objectReferenceValue;
                // A link to something missing on this side is left alone rather than sent as empty.
                if (value == null && property.objectReferenceInstanceIDValue != 0)
                    continue;
                text.Append(path).Append(RefSep).Append(value == null ? string.Empty : Portable(value.GetInstanceID())).Append(RefEnd);
            }
            return text.ToString();
        }

        private static void SplitCapture(string capture, out string json, out string refs)
        {
            int mark = capture.IndexOf(RefsMark);
            json = mark < 0 ? capture : capture.Substring(0, mark);
            refs = mark < 0 ? string.Empty : capture.Substring(mark + 1);
        }

        private static UnityEngine.Object ResolvePortable(string value, out bool missing)
        {
            missing = false;
            if (string.IsNullOrEmpty(value))
                return null;
            if (value.StartsWith("a:", StringComparison.Ordinal))
            {
                var asset = ResolveAsset(value.Substring(2));
                missing = asset == null;
                return asset;
            }
            if (value.StartsWith("g:", StringComparison.Ordinal))
                return Find(value.Substring(2));
            if (value.StartsWith("c:", StringComparison.Ordinal))
                return ResolveComponent(value.Substring(2));
            return null;
        }

        /// <summary>True if any linked asset in the captured links isn't in this project (yet).</summary>
        private static bool RefsMissing(string refs)
        {
            if (string.IsNullOrEmpty(refs))
                return false;
            foreach (var entry in refs.Split(new[] { RefEnd }, StringSplitOptions.RemoveEmptyEntries))
            {
                int sep = entry.IndexOf(RefSep);
                if (sep < 0)
                    continue;
                string value = entry.Substring(sep + 1);
                if (value.StartsWith("a:", StringComparison.Ordinal) && ResolveAsset(value.Substring(2)) == null)
                    return true;
            }
            return false;
        }

        private static string Portable(int instance)
        {
            if (instance == 0)
                return string.Empty;
            var obj = EditorUtility.InstanceIDToObject(instance);
            if (obj == null)
                return string.Empty;

            if (EditorUtility.IsPersistent(obj))
                return "a:" + GlobalObjectId.GetGlobalObjectIdSlow(obj);

            var go = obj as GameObject;
            if (go != null)
                return InLive(go) ? "g:" + IdFor(go) : string.Empty;

            var component = obj as Component;
            if (component != null && InLive(component.gameObject))
                return "c:" + ComponentKey(component);

            return string.Empty;
        }

        private static bool MissingAsset(string json)
        {
            foreach (Match match in PortableRef.Matches(json))
            {
                string value = match.Groups[1].Value;
                if (value.StartsWith("a:", StringComparison.Ordinal) && ResolveAsset(value.Substring(2)) == null)
                    return true;
            }
            return WaitingForAsset(json);
        }

        /// <summary>
        /// The change refers (Unity's own way, by asset id) to an asset this project doesn't have yet while files
        /// are still arriving: wait for it, rather than apply it with an empty reference that would stay empty.
        /// </summary>
        private static bool WaitingForAsset(string json)
        {
            if (string.IsNullOrEmpty(json) || !TeamFiles.Receiving)
                return false;
            foreach (Match match in AssetGuid.Matches(json))
            {
                string guid = match.Groups[1].Value;
                if (guid.StartsWith("0000000000000000", StringComparison.Ordinal))
                    continue;
                if (string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath(guid)))
                    return true;
            }
            return false;
        }

        private static string Restore(string json, out bool missing)
        {
            bool anyMissing = false;
            string result = PortableRef.Replace(json, match =>
            {
                string value = match.Groups[1].Value;
                UnityEngine.Object obj = null;
                if (value.StartsWith("a:", StringComparison.Ordinal))
                {
                    obj = ResolveAsset(value.Substring(2));
                    if (obj == null)
                        anyMissing = true;
                }
                else if (value.StartsWith("g:", StringComparison.Ordinal))
                    obj = Find(value.Substring(2));
                else if (value.StartsWith("c:", StringComparison.Ordinal))
                    obj = ResolveComponent(value.Substring(2));
                return "{\"instanceID\":" + (obj != null ? obj.GetInstanceID() : 0) + "}";
            });
            missing = anyMissing;
            return result;
        }

        /// <summary>Removes keys that tie an object to its place (parent, owner, prefab links) from EditorJsonUtility output.</summary>
        internal static string StripKeys(string json)
        {
            var output = new StringBuilder(json.Length);
            int depth = 0;
            int i = 0;
            while (i < json.Length)
            {
                char c = json[i];
                if (c == '"')
                {
                    int end = StringEnd(json, i);
                    int after = SkipSpace(json, end);
                    if (depth == 2 && after < json.Length && json[after] == ':' && StrippedKeys.Contains(json.Substring(i + 1, end - i - 2)))
                    {
                        int valueEnd = ValueEnd(json, SkipSpace(json, after + 1));
                        int next = SkipSpace(json, valueEnd);
                        if (next < json.Length && json[next] == ',')
                            i = next + 1;
                        else
                        {
                            int trim = output.Length - 1;
                            while (trim >= 0 && char.IsWhiteSpace(output[trim]))
                                trim--;
                            if (trim >= 0 && output[trim] == ',')
                                output.Length = trim;
                            i = next;
                        }
                        continue;
                    }
                    output.Append(json, i, end - i);
                    i = end;
                    continue;
                }
                if (c == '{' || c == '[')
                    depth++;
                else if (c == '}' || c == ']')
                    depth--;
                output.Append(c);
                i++;
            }
            return output.ToString();
        }

        private static int StringEnd(string json, int start)
        {
            int i = start + 1;
            while (i < json.Length)
            {
                if (json[i] == '\\')
                    i += 2;
                else if (json[i] == '"')
                    return i + 1;
                else
                    i++;
            }
            return json.Length;
        }

        private static int SkipSpace(string json, int i)
        {
            while (i < json.Length && char.IsWhiteSpace(json[i]))
                i++;
            return i;
        }

        private static int ValueEnd(string json, int i)
        {
            if (i >= json.Length)
                return i;
            if (json[i] == '"')
                return StringEnd(json, i);
            if (json[i] == '{' || json[i] == '[')
            {
                int depth = 0;
                while (i < json.Length)
                {
                    char c = json[i];
                    if (c == '"')
                    {
                        i = StringEnd(json, i);
                        continue;
                    }
                    if (c == '{' || c == '[')
                        depth++;
                    else if (c == '}' || c == ']')
                    {
                        depth--;
                        if (depth == 0)
                            return i + 1;
                    }
                    i++;
                }
                return i;
            }
            while (i < json.Length && json[i] != ',' && json[i] != '}' && json[i] != ']')
                i++;
            return i;
        }

        // ---- Catch-all for changes made without Undo -------------------------------------------------------------

        /// <summary>
        /// Many tools (and scripts) change objects without Undo, which sends no change event. Once a second this
        /// looks at every object in the shared scene for changed values, added or removed components and children,
        /// and new objects, and shares them like any other edit. It also shares the scene's lighting settings.
        /// </summary>
        private static readonly List<GameObject> sweepQueue = new List<GameObject>();
        private static int sweepIndex;
        private static readonly System.Diagnostics.Stopwatch sweepClock = new System.Diagnostics.Stopwatch();

        private static void Sweep()
        {
            if (live.Count == 0 || !TeamSession.IsLinked || EditorApplication.isPlayingOrWillChangePlaymode ||
                EditorApplication.isCompiling || EditorApplication.isUpdating || !string.IsNullOrEmpty(wantScene))
                return;

            // A pass over the whole shared scene is spread over frames (a few milliseconds each), so even very large
            // worlds don't stutter. It starts once a second while anyone is editing, less often when nobody is.
            bool focused = UnityEditorInternal.InternalEditorUtility.isApplicationActive;
            if (sweepIndex >= sweepQueue.Count)
            {
                bool busy = TeamSession.Now - lastLocalEdit < 20 || TeamSession.Now - lastActivity < 20;
                if (TeamSession.Now - lastSweep < (busy ? 1.0 : focused ? 2.0 : 4.0))
                    return;
                lastSweep = TeamSession.Now;
                sweepQueue.Clear();
                sweepIndex = 0;
                foreach (var path in live.ToList())
                {
                    var scene = SceneManager.GetSceneByPath(path);
                    if (!scene.IsValid() || !scene.isLoaded)
                        continue;
                    sweepQueue.AddRange(Walk(scene));
                    if (scene == SceneManager.GetActiveScene())
                        SendSceneSettings(scene);
                }
                if (sweepQueue.Count > 0 && shapes.Count > sweepQueue.Count * 2)
                    PruneSweepMemory();
            }

            sweepClock.Reset();
            sweepClock.Start();
            double budget = focused ? 4.0 : 2.0;
            while (sweepIndex < sweepQueue.Count && sweepClock.Elapsed.TotalMilliseconds < budget)
            {
                var go = sweepQueue[sweepIndex++];
                if (go != null)
                    SweepOne(go);
            }
        }

        private static void SweepOne(GameObject go)
        {
            if (!InLive(go))
                return;
            int id = go.GetInstanceID();
            var components = sweepComponents;
            go.GetComponents(components);
            int shape = (go.transform.childCount * 4096 + components.Count) * 2 + (PrefabUtility.IsOutermostPrefabInstanceRoot(go) ? 1 : 0);
            int known;
            bool seen = shapes.TryGetValue(id, out known);
            shapes[id] = shape;

            if (!idOf.ContainsKey(id))
            {
                // Made without Undo: give it the id both editors would derive, and share it.
                IdFor(go);
                if (seen || go.transform.parent == null || idOf.ContainsKey(go.transform.parent.gameObject.GetInstanceID()))
                    SendTree(go, false);
                Remember(go, components);
                return;
            }

            if (!seen)
            {
                Remember(go, components);
                return;
            }
            if (known != shape)
                SendTree(go, false);

            Check(id);
            float[] was;
            if (!poses.TryGetValue(id, out was))
                poses[id] = TransformValues(go.transform);
            else if (ReadPose(go.transform, was) && !glides.ContainsKey(id))
                dirty.Add(go.transform.GetInstanceID());
            foreach (var component in components)
                if (component != null)
                    Check(component.GetInstanceID());
        }

        private static readonly List<Component> sweepComponents = new List<Component>();

        /// <summary>Reads a transform into a kept array (no new memory each pass). True if it changed.</summary>
        private static bool ReadPose(Transform t, float[] into)
        {
            var p = t.localPosition;
            var r = t.localRotation;
            var s = t.localScale;
            bool changed = into[0] != p.x || into[1] != p.y || into[2] != p.z || into[3] != r.x || into[4] != r.y || into[5] != r.z ||
                           into[6] != r.w || into[7] != s.x || into[8] != s.y || into[9] != s.z;
            if (changed)
            {
                into[0] = p.x; into[1] = p.y; into[2] = p.z;
                into[3] = r.x; into[4] = r.y; into[5] = r.z; into[6] = r.w;
                into[7] = s.x; into[8] = s.y; into[9] = s.z;
            }
            return changed;
        }

        /// <summary>Forgets objects that no longer exist, so the sweep's memory doesn't grow forever.</summary>
        private static void PruneSweepMemory()
        {
            foreach (var key in shapes.Keys.ToList())
                if (EditorUtility.InstanceIDToObject(key) == null)
                {
                    shapes.Remove(key);
                    poses.Remove(key);
                }
            foreach (var key in dirtyCounts.Keys.ToList())
                if (EditorUtility.InstanceIDToObject(key) == null)
                    dirtyCounts.Remove(key);
        }

        private static void Remember(GameObject go, List<Component> components)
        {
            dirtyCounts[go.GetInstanceID()] = EditorUtility.GetDirtyCount(go.GetInstanceID());
            poses[go.GetInstanceID()] = TransformValues(go.transform);
            foreach (var component in components)
                if (component != null)
                    dirtyCounts[component.GetInstanceID()] = EditorUtility.GetDirtyCount(component.GetInstanceID());
        }

        private static void Check(int instanceId)
        {
            int count = EditorUtility.GetDirtyCount(instanceId);
            int was;
            if (dirtyCounts.TryGetValue(instanceId, out was) && was != count)
                dirty.Add(instanceId);
            dirtyCounts[instanceId] = count;
        }

        [Serializable]
        private sealed class TeamSceneSettings
        {
            public bool fog;
            public Color fogColor;
            public int fogMode;
            public float fogDensity;
            public float fogStart;
            public float fogEnd;
            public int ambientMode;
            public Color ambientSky;
            public Color ambientEquator;
            public Color ambientGround;
            public float ambientIntensity;
            public float reflectionIntensity;
            public int reflectionBounces;
            public int reflectionMode;
            public int reflectionResolution;
            public Color subtractiveShadow;
            public float haloStrength;
            public float flareStrength;
            public float flareFadeSpeed;
            public string skybox;
            public string sun;
            public string customReflection;
            public string lightingSettings;
        }

        private static TeamSceneSettings ReadSceneSettings()
        {
            return new TeamSceneSettings
            {
                fog = RenderSettings.fog,
                fogColor = RenderSettings.fogColor,
                fogMode = (int)RenderSettings.fogMode,
                fogDensity = RenderSettings.fogDensity,
                fogStart = RenderSettings.fogStartDistance,
                fogEnd = RenderSettings.fogEndDistance,
                ambientMode = (int)RenderSettings.ambientMode,
                ambientSky = RenderSettings.ambientSkyColor,
                ambientEquator = RenderSettings.ambientEquatorColor,
                ambientGround = RenderSettings.ambientGroundColor,
                ambientIntensity = RenderSettings.ambientIntensity,
                reflectionIntensity = RenderSettings.reflectionIntensity,
                reflectionBounces = RenderSettings.reflectionBounces,
                reflectionMode = (int)RenderSettings.defaultReflectionMode,
                reflectionResolution = RenderSettings.defaultReflectionResolution,
                subtractiveShadow = RenderSettings.subtractiveShadowColor,
                haloStrength = RenderSettings.haloStrength,
                flareStrength = RenderSettings.flareStrength,
                flareFadeSpeed = RenderSettings.flareFadeSpeed,
                skybox = RefOf(RenderSettings.skybox),
                sun = RefOf(RenderSettings.sun),
                customReflection = RefOf(RenderSettings.customReflectionTexture),
                lightingSettings = RefOf(GetLightingSettings())
            };
        }

        private static LightingSettings GetLightingSettings()
        {
            LightingSettings settings;
            return Lightmapping.TryGetLightingSettings(out settings) ? settings : null;
        }

        private static string RefOf(UnityEngine.Object obj)
        {
            return obj == null ? string.Empty : Portable(obj.GetInstanceID());
        }

        private static UnityEngine.Object FromRef(string value, out bool missing)
        {
            missing = false;
            if (string.IsNullOrEmpty(value))
                return null;
            if (value.StartsWith("a:", StringComparison.Ordinal))
            {
                var obj = ResolveAsset(value.Substring(2));
                missing = obj == null;
                return obj;
            }
            if (value.StartsWith("g:", StringComparison.Ordinal))
                return Find(value.Substring(2));
            if (value.StartsWith("c:", StringComparison.Ordinal))
                return ResolveComponent(value.Substring(2));
            return null;
        }

        private static void SendSceneSettings(Scene scene)
        {
            string key = "rs:" + scene.path;
            string json = JsonUtility.ToJson(ReadSceneSettings());
            // The first look only remembers the settings (both sides already have them from the shared scene); only
            // real changes are sent, so one side's unchanged settings never overwrite the other's new ones.
            if (!lastSent.ContainsKey(key))
            {
                lastSent[key] = json;
                return;
            }
            SendIfChanged(key, new TeamMessage { t = "op", mt = "rs", s = scene.path, json = json, sc = scene.path });
        }

        private static bool ApplySceneSettings(TeamMessage message)
        {
            if (SceneManager.GetActiveScene().path != message.s || string.IsNullOrEmpty(message.json))
                return true;
            var s = JsonUtility.FromJson<TeamSceneSettings>(message.json);
            // References that can't be found here yet (an asset still on its way) keep their current value for
            // now; everything else applies right away, and the whole change is retried until they arrive.
            bool skyMissing, reflectionMissing, lightingMissing, sunMissing;
            var skybox = FromRef(s.skybox, out skyMissing) as Material;
            var reflection = FromRef(s.customReflection, out reflectionMissing) as Texture;
            var lighting = FromRef(s.lightingSettings, out lightingMissing) as LightingSettings;
            var sun = FromRef(s.sun, out sunMissing) as Light;

            RenderSettings.fog = s.fog;
            RenderSettings.fogColor = s.fogColor;
            RenderSettings.fogMode = (FogMode)s.fogMode;
            RenderSettings.fogDensity = s.fogDensity;
            RenderSettings.fogStartDistance = s.fogStart;
            RenderSettings.fogEndDistance = s.fogEnd;
            RenderSettings.ambientMode = (UnityEngine.Rendering.AmbientMode)s.ambientMode;
            RenderSettings.ambientSkyColor = s.ambientSky;
            RenderSettings.ambientEquatorColor = s.ambientEquator;
            RenderSettings.ambientGroundColor = s.ambientGround;
            RenderSettings.ambientIntensity = s.ambientIntensity;
            RenderSettings.reflectionIntensity = s.reflectionIntensity;
            RenderSettings.reflectionBounces = s.reflectionBounces;
            RenderSettings.defaultReflectionMode = (UnityEngine.Rendering.DefaultReflectionMode)s.reflectionMode;
            RenderSettings.defaultReflectionResolution = s.reflectionResolution;
            RenderSettings.subtractiveShadowColor = s.subtractiveShadow;
            RenderSettings.haloStrength = s.haloStrength;
            RenderSettings.flareStrength = s.flareStrength;
            RenderSettings.flareFadeSpeed = s.flareFadeSpeed;
            if (!skyMissing)
                RenderSettings.skybox = skybox;
            if (!sunMissing)
                RenderSettings.sun = sun;
            if (!reflectionMissing)
                RenderSettings.customReflectionTexture = reflection;
            if (lighting != null)
                Lightmapping.lightingSettings = lighting;

            lastSent["rs:" + message.s] = JsonUtility.ToJson(ReadSceneSettings());
            EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());

            // Show it now: the sky's light in the ambient lighting, and every Scene view redrawn.
            DynamicGI.UpdateEnvironment();
            SceneView.RepaintAll();

            // A new skybox (or sun, reflection, lighting settings) whose file hasn't arrived yet: everything else is
            // applied already; try again until it has (it used to be skipped for good, so the sky never changed).
            return !(skyMissing || sunMissing || reflectionMissing || lightingMissing);
        }

        private static double lastError;

        /// <summary>Runs one periodic job; an error in one never stops the others.</summary>
        private static void Safely(Action job)
        {
            try
            {
                job();
            }
            catch (Exception e)
            {
                if (TeamSession.Now - lastError > 10)
                {
                    lastError = TeamSession.Now;
                    Debug.LogWarning("[WPFMA Team] " + e.GetType().Name + ": " + e.Message + "\n" + e.StackTrace);
                }
            }
        }

        // ---- Update -----------------------------------------------------------------------------------------------

        // Things a teammate just changed that may be open in an Inspector here.
        private static readonly HashSet<int> changedByTeammate = new HashSet<int>();
        private static double changedByTeammateAt;

        /// <summary>
        /// A teammate changed this. Inspectors (especially custom ones like shader GUIs) keep their own copy of what
        /// they show, so an Inspector showing it is rebuilt a moment later - what clicking off and back on did by hand.
        /// </summary>
        internal static void ChangedByTeammate(UnityEngine.Object target)
        {
            if (target == null)
                return;
            changedByTeammate.Add(target.GetInstanceID());
            changedByTeammateAt = TeamSession.Now;
        }

        private static void RefreshInspectors()
        {
            if (changedByTeammate.Count == 0)
                return;
            // Wait until their edits pause, and never while you are dragging a slider or have a field active.
            if (TeamSession.Now - changedByTeammateAt < 0.4 || GUIUtility.hotControl != 0 || EditorGUIUtility.editingTextField)
                return;
            foreach (var id in changedByTeammate)
            {
                double mine;
                if (localMaterialEdit.TryGetValue(id, out mine) && TeamSession.Now - mine < 1.0)
                    return;
            }

            var tracker = ActiveEditorTracker.sharedTracker;
            bool shown = tracker.activeEditors.Any(editor => editor != null && editor.targets.Any(t => t != null && changedByTeammate.Contains(t.GetInstanceID())));
            changedByTeammate.Clear();
            if (shown)
                tracker.ForceRebuild();
        }

        private static void Update()
        {
            if (!TeamSession.IsLinked)
                return;

            Safely(StepGlides);
            Safely(RefreshInspectors);
            Safely(ReleaseHeld);
            Safely(PumpSnapshot);
            if (CanSend)
                Safely(Flush);
            Safely(Sweep);
            Safely(() => RetryDeferred(false));
            Safely(SendOutbox);
            Safely(SendDigests);
            if (joinAt > 0 && TeamSession.Now >= joinAt)
                Safely(TryJoin);

            // Show a teammate's edits as they land: the Scene view and Hierarchy don't redraw by themselves for them.
            if (repaintSoon && TeamSession.Now - lastRepaintAt >= (glides.Count > 0 ? 0.016 : 0.04))
            {
                repaintSoon = false;
                lastRepaintAt = TeamSession.Now;
                SceneView.RepaintAll();
                EditorApplication.RepaintHierarchyWindow();
            }
        }
    }
}
#endif
