From 82e8d73199ee9f43a6c4bfa6d48e518f8074b086 Mon Sep 17 00:00:00 2001 From: Unity Technologies Date: Tue, 15 Jan 2019 18:45:50 +0000 Subject: [PATCH 01/26] Unity 2019.1.0a14 C# reference source code --- Editor/Mono/GUI/EditModeTools/EditModeTool.cs | 79 ++++++ Editor/Mono/GUI/Toolbar.cs | 2 +- Editor/Mono/GUI/Tools/EditorTool.cs | 15 +- Editor/Mono/GUI/Tools/EditorToolContext.cs | 245 +++++++++++++++--- Editor/Mono/GUI/Tools/EditorToolGUI.cs | 76 ++++-- Editor/Mono/GUI/Tools/EditorToolUtility.cs | 45 ++-- .../Inspector/CustomRenderTextureEditor.cs | 5 +- Editor/Mono/Inspector/EditMode.cs | 133 ++++++---- Editor/Mono/Inspector/LightEditor.cs | 4 +- .../Inspector/LightProbeGroupInspector.cs | 3 + Editor/Mono/Inspector/RenderTextureEditor.cs | 29 +-- Editor/Mono/Inspector/ShaderInspector.cs | 81 ++++++ Editor/Mono/Inspector/TextureInspector.cs | 22 +- Editor/Mono/PerformanceTools/FrameDebugger.cs | 5 +- .../StageManager/StageUtility.cs | 2 +- Editor/Mono/SceneView/SceneView.cs | 56 ++-- Editor/Mono/SceneView/SceneViewOverlay.cs | 14 +- Editor/Mono/Selection.bindings.cs | 4 + Editor/Mono/ShaderUtil.bindings.cs | 3 + .../ScriptBindings/AvatarBuilder.bindings.cs | 1 + Modules/IMGUI/GUIUtility.cs | 8 + Modules/UIElements/ScrollView.cs | 4 +- Modules/UIElements/VisualElement.cs | 15 +- Modules/XR/ScriptBindings/XRInput.bindings.cs | 10 +- Projects/CSharp/UnityEditor.csproj | 3 + README.md | 2 +- .../GraphicsFormatUtility.bindings.cs | 6 + Runtime/Export/Graphics/Texture.cs | 61 ++++- .../Export/SystemInfo/SystemInfo.bindings.cs | 3 + 29 files changed, 690 insertions(+), 246 deletions(-) create mode 100644 Editor/Mono/GUI/EditModeTools/EditModeTool.cs diff --git a/Editor/Mono/GUI/EditModeTools/EditModeTool.cs b/Editor/Mono/GUI/EditModeTools/EditModeTool.cs new file mode 100644 index 0000000000..ece234a1db --- /dev/null +++ b/Editor/Mono/GUI/EditModeTools/EditModeTool.cs @@ -0,0 +1,79 @@ +// Unity C# reference source +// Copyright (c) Unity Technologies. For terms of use, see +// https://unity3d.com/legal/licenses/Unity_Reference_Only_License + +using System; +using UnityEditor.EditorTools; +using UnityEditorInternal; +using UnityEngine; +using SceneViewEditMode = UnityEditorInternal.EditMode.SceneViewEditMode; + +namespace UnityEditor +{ + abstract class EditModeTool : EditorTool + { + GUIContent m_Content; + IToolModeOwner m_Owner; + bool m_CanEditMultipleObjects; + + protected EditModeTool() + { + m_CanEditMultipleObjects = editorType.GetCustomAttributes(typeof(CanEditMultipleObjects), false).Length > 0; + } + + public abstract SceneViewEditMode editMode { get; } + + public abstract Type editorType { get; } + + public override GUIContent toolbarIcon + { + get + { + if (m_Content == null) + { + var customEditorAttributes = editorType.GetCustomAttributes(typeof(CustomEditor), false); + + if (customEditorAttributes.Length > 0) + { + m_Content = new GUIContent( + AssetPreview.GetMiniTypeThumbnailFromType(((CustomEditor)customEditorAttributes[0]) + .m_InspectedType), + editorType.ToString()); + } + else + { + m_Content = new GUIContent(editorType.ToString(), editorType.ToString()); + } + } + + return m_Content; + } + } + + public IToolModeOwner owner + { + get { return m_Owner; } + internal set { m_Owner = value; } + } + + public sealed override void OnActivate() + { + if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying) + return; + EditMode.ChangeEditModeFromToolContext(owner, editMode); + } + + public sealed override void OnDeactivate() + { + if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying) + return; + + EditMode.ChangeEditModeFromToolContext(owner, SceneViewEditMode.None); + } + + public override bool IsAvailable() + { + return m_CanEditMultipleObjects || Selection.count == 1; + } + } +} diff --git a/Editor/Mono/GUI/Toolbar.cs b/Editor/Mono/GUI/Toolbar.cs index a114374de6..11ac78b13c 100644 --- a/Editor/Mono/GUI/Toolbar.cs +++ b/Editor/Mono/GUI/Toolbar.cs @@ -357,7 +357,7 @@ void DoToolButtons(Rect rect) || (evt.button == 0 && evt.modifiers == EventModifiers.Alt)) ) { - EditorToolGUI.DoToolHistoryContextMenu(); + EditorToolGUI.DoToolContextMenu(); } else { diff --git a/Editor/Mono/GUI/Tools/EditorTool.cs b/Editor/Mono/GUI/Tools/EditorTool.cs index 676167d245..986822effe 100644 --- a/Editor/Mono/GUI/Tools/EditorTool.cs +++ b/Editor/Mono/GUI/Tools/EditorTool.cs @@ -5,7 +5,7 @@ using System; using System.Collections.Generic; using UnityEngine; -using UObject = UnityEngine.Object; +using UnityObject = UnityEngine.Object; namespace UnityEditor.EditorTools { @@ -28,9 +28,13 @@ public abstract class EditorTool : ScriptableObject { [HideInInspector] [SerializeField] - internal UObject[] m_Targets; + internal UnityObject[] m_Targets; - public IEnumerable targets + [HideInInspector] + [SerializeField] + internal UnityObject m_Target; + + public IEnumerable targets { get { @@ -45,6 +49,11 @@ public IEnumerable targets } } + public UnityObject target + { + get { return m_Target == null ? Selection.activeObject : m_Target; } + } + public abstract GUIContent toolbarIcon { get; } public virtual void OnToolGUI(EditorWindow window) {} diff --git a/Editor/Mono/GUI/Tools/EditorToolContext.cs b/Editor/Mono/GUI/Tools/EditorToolContext.cs index dfca84ca13..f41c827779 100644 --- a/Editor/Mono/GUI/Tools/EditorToolContext.cs +++ b/Editor/Mono/GUI/Tools/EditorToolContext.cs @@ -7,7 +7,7 @@ using System.ComponentModel; using System.Linq; using UnityEngine; -using UObject = UnityEngine.Object; +using UnityObject = UnityEngine.Object; namespace UnityEditor.EditorTools { @@ -19,8 +19,17 @@ sealed class EditorToolContext : ScriptableSingleton [SerializeField] EditorTool m_ActiveTool; + static ActiveEditorTracker m_Tracker; + [SerializeField] + List m_ToolHistory = new List(); static bool s_ChangingActiveTool; + // EditorTools that are created as custom editor tools. This list represents only the shared tracker. + List m_CustomEditorTools = new List(); + // This list represents any custom editor tools created by locked inspectors. They are not shown in the scene + // or context menu. + List m_LockedCustomEditorTools = new List(); + internal static EditorTool activeTool { get @@ -31,7 +40,11 @@ internal static EditorTool activeTool set { if (s_ChangingActiveTool) + { + // pop the changing state so that we don't lock the active tool after an exception is thrown. + s_ChangingActiveTool = false; throw new InvalidOperationException("Attempting to set the active tool from EditorTool.OnActivate or EditorTool.OnDeactivate. This is not allowed."); + } var tool = value; @@ -54,6 +67,7 @@ internal static EditorTool activeTool instance.m_ActiveTool.OnDeactivate(); var previous = instance.m_ActiveTool; + instance.m_ActiveTool = tool; tool.OnActivate(); @@ -67,11 +81,15 @@ internal static EditorTool activeTool } } - [SerializeField] - List m_ToolHistory = new List(); - - // The currently available CustomEditor EditorTools. - HashSet m_CustomEditorTools = new HashSet(); + static ActiveEditorTracker tracker + { + get + { + if (m_Tracker == null) + m_Tracker = new ActiveEditorTracker(); + return m_Tracker; + } + } [Serializable] struct CustomEditorToolContext : ISerializationCallbackReceiver @@ -84,7 +102,9 @@ struct CustomEditorToolContext : ISerializationCallbackReceiver public Type editorToolType; - public UObject[] targetObjects; + public UnityObject targetObject; + + public UnityObject[] targetObjects; public string editorToolState { @@ -98,12 +118,14 @@ public CustomEditorToolContext(EditorTool tool) if (tool != null) { editorToolType = tool.GetType(); + targetObject = tool.target; targetObjects = tool.targets.ToArray(); m_EditorToolState = EditorJsonUtility.ToJson(tool); } else { editorToolType = null; + targetObject = null; targetObjects = null; m_EditorToolState = null; } @@ -203,7 +225,7 @@ void PlayModeStateChanged(PlayModeStateChange state) } // TrackerRebuilt is called during the ExitingEditMode phase, but the selection might not be valid yet. - if (m_PlayModeState == PlayModeStateChange.EnteredPlayMode) + if (m_PlayModeState == PlayModeStateChange.EnteredPlayMode || m_PlayModeState == PlayModeStateChange.EnteredEditMode) RebuildAvailableCustomEditorTools(); } @@ -225,7 +247,7 @@ void EnsureCurrentToolIsNotNull() void SelectedObjectWasDestroyed(int id) { - if (m_CustomEditorTools.Contains(m_ActiveTool) && + if (m_CustomEditorTools.Any(x => x == m_ActiveTool) && m_ActiveTool.m_Targets.Any(x => x == null || x.GetInstanceID() == id)) { m_PreviousCustomEditorToolContext = new CustomEditorToolContext(m_ActiveTool); @@ -242,6 +264,12 @@ void RestoreCustomEditorTool() { var restored = m_CustomEditorTools.FirstOrDefault(m_PreviousCustomEditorToolContext.IsEqual); + // Check for existence in locked inspectors too, but only if the locked inspector target is being inspected + if (restored == null + && m_PreviousCustomEditorToolContext.targetObject != null + && Selection.objects.Any(x => x.Equals(m_PreviousCustomEditorToolContext.targetObject))) + restored = m_LockedCustomEditorTools.FirstOrDefault(m_PreviousCustomEditorToolContext.IsEqual); + if (restored != null) { var targets = restored.targets.ToArray(); @@ -253,16 +281,22 @@ void RestoreCustomEditorTool() m_PreviousCustomEditorToolContext = CustomEditorToolContext.Empty; } + // destroy invalid custom editor tools void ClearCustomEditorTools() { - foreach (var tool in m_CustomEditorTools) + foreach (var customEditorTool in m_CustomEditorTools) { - if (tool != null && tool != m_ActiveTool) - { - DestroyImmediate(tool); - } + if (customEditorTool != null && customEditorTool != m_ActiveTool) + DestroyImmediate(customEditorTool); } + foreach (var customEditorTool in m_LockedCustomEditorTools) + { + if (customEditorTool != null && customEditorTool != m_ActiveTool) + DestroyImmediate(customEditorTool); + } + + m_LockedCustomEditorTools.Clear(); m_CustomEditorTools.Clear(); } @@ -355,13 +389,13 @@ internal static void OnToolGUI(EditorWindow window) } } - bool IsCustomEditorTool(EditorTool tool) + static bool IsCustomEditorTool(EditorTool tool) { - return tool != null - && tool.m_Targets != null - && tool.m_Targets.Length > 0; + return EditorToolUtility.IsCustomEditorTool(tool != null ? tool.GetType() : null); } + static List s_CustomEditorTools = new List(); + void RebuildAvailableCustomEditorTools() { // Do not rebuild the cache since objects are serialized, destroyed, deserialized during this phase @@ -369,66 +403,191 @@ void RebuildAvailableCustomEditorTools() m_PlayModeState == PlayModeStateChange.ExitingPlayMode) return; - var isCustomEditorTool = IsCustomEditorTool(m_ActiveTool); + var preservedActiveTool = false; ClearCustomEditorTools(); - foreach (var kvp in EditorToolUtility.FindActiveCustomEditorTools()) + var inspectors = InspectorWindow.GetInspectors(); + var collectedUnlockedInspector = false; + + foreach (var inspector in inspectors) + { + if (inspector.isLocked) + preservedActiveTool |= CollectCustomEditorToolsFromTracker(inspector.tracker, m_LockedCustomEditorTools); + else if (!collectedUnlockedInspector) + { + preservedActiveTool |= CollectCustomEditorToolsFromTracker(inspector.tracker, m_CustomEditorTools); + collectedUnlockedInspector = true; + } + } + + if (!collectedUnlockedInspector) + { + var shared = ActiveEditorTracker.sharedTracker; + preservedActiveTool |= CollectCustomEditorToolsFromTracker(shared.isLocked ? tracker : shared, m_CustomEditorTools); + } + + if (IsCustomEditorTool(m_ActiveTool) && !preservedActiveTool) + { + m_ActiveTool.OnDeactivate(); + m_PreviousCustomEditorToolContext = new CustomEditorToolContext(m_ActiveTool); + DestroyImmediate(m_ActiveTool); + RestorePreviousTool(); + } + } + + bool CollectCustomEditorToolsFromTracker(ActiveEditorTracker tracker, List list) + { + var activeIsCustomEditorTool = IsCustomEditorTool(m_ActiveTool); + var preservedActiveTool = false; + s_CustomEditorTools.Clear(); + + EditorToolUtility.GetEditorToolsForTracker(tracker, s_CustomEditorTools); + + foreach (var customEditorTool in s_CustomEditorTools) { - var toolType = kvp.Key; - var toolInfo = kvp.Value.ToArray(); + var toolType = customEditorTool.editorToolType; + var toolOwner = customEditorTool.owner; - if (isCustomEditorTool && m_ActiveTool.GetType() == toolType) + EditorTool customEditorToolInstance; + + // The only case where a custom editor tool is serialized is when it is the active tool. All other + // instances are discarded and rebuilt on any tracker rebuild. + if (activeIsCustomEditorTool && CustomEditorToolIsMatch(toolOwner, toolType, m_ActiveTool)) { - m_ActiveTool.m_Targets = toolInfo; - m_CustomEditorTools.Add(m_ActiveTool); + preservedActiveTool = true; + + m_ActiveTool.m_Targets = toolOwner.targets; + m_ActiveTool.m_Target = toolOwner.target; + + // domain reload - the owning editor was destroyed and therefore we need to reset the EditMode active + if (m_ActiveTool is EditModeTool && toolOwner.GetInstanceID() != UnityEditorInternal.EditMode.ownerID) + UnityEditorInternal.EditMode.ChangeEditModeFromToolContext(toolOwner, ((EditModeTool)m_ActiveTool).editMode); + + customEditorToolInstance = m_ActiveTool; } else { - var toolInstance = (EditorTool)CreateInstance(toolType, x => { ((EditorTool)x).m_Targets = toolInfo; }); - toolInstance.hideFlags = HideFlags.DontSave; - m_CustomEditorTools.Add(toolInstance); + customEditorToolInstance = (EditorTool)CreateInstance(toolType, x => + { + ((EditorTool)x).m_Targets = toolOwner.targets; + ((EditorTool)x).m_Target = toolOwner.target; + }); + + customEditorToolInstance.hideFlags = HideFlags.DontSave; } + + list.Add(customEditorToolInstance); + + var editModeTool = customEditorToolInstance as EditModeTool; + + if (editModeTool != null) + editModeTool.owner = toolOwner; } - if (isCustomEditorTool && !m_CustomEditorTools.Contains(m_ActiveTool)) + return preservedActiveTool; + } + + static bool CustomEditorToolIsMatch(Editor editor, Type toolType, EditorTool tool) + { + if (editor == null || toolType != tool.GetType()) + return false; + + // if it's an EditModeTool we need to be stricter about ownership for backwards compatibility. + var editModeTool = tool as EditModeTool; + + if (editModeTool != null) + return editModeTool.owner == (IToolModeOwner)editor || editModeTool.target == editor.target; + + // otherwise just check if it's a valid type + return true; + } + + internal static EditorTool GetCustomEditorToolOfType(Type type, bool searchLockedInspectors = true) + { + foreach (var customEditorTool in instance.m_CustomEditorTools) + if (customEditorTool != null && customEditorTool.GetType() == type) + return customEditorTool; + + if (searchLockedInspectors) { - m_PreviousCustomEditorToolContext = new CustomEditorToolContext(m_ActiveTool); - DestroyImmediate(m_ActiveTool); - RestorePreviousTool(); + foreach (var customEditorTool in instance.m_LockedCustomEditorTools) + if (customEditorTool != null && customEditorTool.GetType() == type) + return customEditorTool; } + + return null; } - internal static EditorTool GetCustomEditorToolOfType(Type type) + internal static EditorTool GetCustomEditorToolsForType(Type targetType, List list, bool searchLockedInspectors) { - foreach (var tool in instance.m_CustomEditorTools) - if (tool != null && tool.GetType() == type) - return tool; + foreach (var customEditorTool in instance.m_CustomEditorTools) + if (customEditorTool != null && + EditorToolUtility.GetCustomEditorToolTargetType(customEditorTool) == targetType) + list.Add(customEditorTool); + + + if (searchLockedInspectors) + { + foreach (var customEditorTool in instance.m_LockedCustomEditorTools) + if (customEditorTool != null && EditorToolUtility.GetCustomEditorToolTargetType(customEditorTool) == targetType) + list.Add(customEditorTool); + } + return null; } - internal static void GetCustomEditorTools(List list) + internal static void GetCustomEditorTools(List list, bool includeLockedInspectorTools) { list.Clear(); foreach (var customEditorTool in instance.m_CustomEditorTools) list.Add(customEditorTool); + + if (includeLockedInspectorTools) + { + foreach (var customEditorTool in instance.m_LockedCustomEditorTools) + list.Add(customEditorTool); + } } - internal static void GetCustomEditorTools(Type type, List list) + internal static void GetCustomEditorToolsForTarget(UnityObject target, List list, bool searchLockedInspectors) { - if (type == null) + s_CustomEditorTools.Clear(); + + if (target == null) return; - list.Clear(); + foreach (var tool in instance.m_CustomEditorTools) + { + if (tool.target == target) + list.Add(tool); + } - foreach (var customEditorTool in instance.m_CustomEditorTools) + if (searchLockedInspectors) { - if (EditorToolUtility.GetCustomEditorToolTargetType(customEditorTool) == type) - list.Add(customEditorTool); + foreach (var tool in instance.m_LockedCustomEditorTools) + { + if (tool.target == target) + list.Add(tool); + } } } + internal static EditorTool GetCustomEditorTool(Func predicate, bool searchLockedInspectors) + { + foreach (var tool in instance.m_CustomEditorTools) + if (predicate(tool)) + return tool; + + if (searchLockedInspectors) + foreach (var tool in instance.m_LockedCustomEditorTools) + if (predicate(tool)) + return tool; + + return null; + } + [EditorBrowsable(EditorBrowsableState.Never)] internal static ScriptableObject CreateInstance(Type type, Action initialize) { diff --git a/Editor/Mono/GUI/Tools/EditorToolGUI.cs b/Editor/Mono/GUI/Tools/EditorToolGUI.cs index edf91ed1c4..8961fb9cdf 100644 --- a/Editor/Mono/GUI/Tools/EditorToolGUI.cs +++ b/Editor/Mono/GUI/Tools/EditorToolGUI.cs @@ -23,9 +23,7 @@ public static void EditorToolbarForTarget(UObject target) if (target == null) throw new ArgumentNullException("target"); - var targetType = target.GetType(); - s_CustomEditorTools.Clear(); - EditorToolContext.GetCustomEditorTools(targetType, s_CustomEditorTools); + EditorToolContext.GetCustomEditorToolsForTarget(target, s_CustomEditorTools, true); EditorToolbar(s_CustomEditorTools); } @@ -75,13 +73,15 @@ public static void EditorToolbar(IList tools) where T : EditorTool static class EditorToolGUI { + const int k_MaxToolHistory = 6; + static class Styles { public static GUIContent selectionToolsWindowTitle = EditorGUIUtility.TrTextContent("Tools"); public static GUIContent recentTools = EditorGUIUtility.TrTextContent("Recent"); public static GUIContent selectionTools = EditorGUIUtility.TrTextContent("Selection"); public static GUIContent availableTools = EditorGUIUtility.TrTextContent("Available"); - public static GUIContent noToolsAvailable = EditorGUIUtility.TrTextContent("No tools for selected components."); + public static GUIContent noToolsAvailable = EditorGUIUtility.TrTextContent("No custom tools available"); } [EditorBrowsable(EditorBrowsableState.Never)] @@ -158,23 +158,22 @@ internal static void DoBuiltinToolSettings(Rect rect) public static void DrawSceneViewTools(SceneView sceneView) { - SceneViewOverlay.Window(Styles.selectionToolsWindowTitle, DoContextualToolbarOverlay, int.MaxValue, - SceneViewOverlay.WindowDisplayOption.OneWindowPerTitle); + SceneViewOverlay.Window(Styles.selectionToolsWindowTitle, DoContextualToolbarOverlay, int.MaxValue, null, + SceneViewOverlay.WindowDisplayOption.MultipleWindowsPerTarget, sceneView); } static void DoContextualToolbarOverlay(UnityEngine.Object target, SceneView sceneView) { GUILayout.BeginHorizontal(GUIStyle.none, GUILayout.MinWidth(210), GUILayout.Height(30)); - s_EditorToolModes.Clear(); - EditorToolContext.GetCustomEditorTools(s_EditorToolModes); + EditorToolContext.GetCustomEditorTools(s_EditorToolModes, false); if (s_EditorToolModes.Count > 0) { EditorGUI.BeginChangeCheck(); EditorGUILayout.EditorToolbar(s_EditorToolModes); if (EditorGUI.EndChangeCheck()) - foreach (var editor in sceneView.GetActiveEditors()) + foreach (var editor in sceneView.activeEditors) editor.Repaint(); } else @@ -187,42 +186,49 @@ static void DoContextualToolbarOverlay(UnityEngine.Object target, SceneView scen GUILayout.EndHorizontal(); } - internal static void DoToolHistoryContextMenu() + internal static void DoToolContextMenu() { var toolHistoryMenu = new GenericMenu() { allowDuplicateNames = true }; + var foundTool = false; + s_ToolList.Clear(); + EditorToolContext.GetToolHistory(s_ToolList, true); // recent history - if (EditorToolContext.GetLastTool() != null) + if (EditorToolContext.GetLastCustomTool() != null) { + foundTool = true; toolHistoryMenu.AddDisabledItem(Styles.recentTools); - for (var i = 0; i < s_ToolList.Count; i++) + for (var i = 0; i < Math.Min(k_MaxToolHistory, s_ToolList.Count); i++) { var tool = s_ToolList[i]; if (EditorToolUtility.IsCustomEditorTool(tool.GetType())) continue; - toolHistoryMenu.AddItem( - new GUIContent(EditorToolUtility.GetToolName(tool)), - false, - () => { EditorToolContext.activeTool = tool; }); + if (tool.IsAvailable()) + toolHistoryMenu.AddItem( + new GUIContent(EditorToolUtility.GetToolName(tool)), + false, + () => { EditorToolContext.activeTool = tool; }); + else + toolHistoryMenu.AddDisabledItem(new GUIContent(EditorToolUtility.GetToolName(tool))); } toolHistoryMenu.AddSeparator(""); } - s_ToolList.Clear(); - EditorToolContext.GetCustomEditorTools(s_ToolList); + EditorToolContext.GetCustomEditorTools(s_ToolList, false); if (s_ToolList.Any()) { + foundTool = true; toolHistoryMenu.AddDisabledItem(Styles.selectionTools); for (var i = 0; i < s_ToolList.Count; i++) @@ -232,23 +238,37 @@ internal static void DoToolHistoryContextMenu() if (!EditorToolUtility.IsCustomEditorTool(tool.GetType())) continue; - toolHistoryMenu.AddItem( - new GUIContent(EditorToolUtility.GetToolName(tool)), - false, - () => { EditorToolContext.activeTool = tool; }); + if (tool.IsAvailable()) + toolHistoryMenu.AddItem( + new GUIContent(EditorToolUtility.GetToolName(tool)), + false, + () => { EditorToolContext.activeTool = tool; }); + else + toolHistoryMenu.AddDisabledItem(new GUIContent(EditorToolUtility.GetToolName(tool))); } toolHistoryMenu.AddSeparator(""); } - toolHistoryMenu.AddDisabledItem(Styles.availableTools); + var global = EditorToolUtility.GetCustomEditorToolsForType(null); + + if (global.Any()) + { + foundTool = true; + toolHistoryMenu.AddDisabledItem(Styles.availableTools); + + foreach (var toolType in global) + { + toolHistoryMenu.AddItem( + new GUIContent(EditorToolUtility.GetToolName(toolType)), + false, + () => { EditorTools.EditorTools.SetActiveTool(toolType); }); + } + } - foreach (var toolType in EditorToolUtility.GetCustomEditorToolsForType(null)) + if (!foundTool) { - toolHistoryMenu.AddItem( - new GUIContent(EditorToolUtility.GetToolName(toolType)), - false, - () => { EditorTools.EditorTools.SetActiveTool(toolType); }); + toolHistoryMenu.AddDisabledItem(Styles.noToolsAvailable); } toolHistoryMenu.ShowAsContext(); diff --git a/Editor/Mono/GUI/Tools/EditorToolUtility.cs b/Editor/Mono/GUI/Tools/EditorToolUtility.cs index b5138be6ff..660325c704 100644 --- a/Editor/Mono/GUI/Tools/EditorToolUtility.cs +++ b/Editor/Mono/GUI/Tools/EditorToolUtility.cs @@ -5,11 +5,22 @@ using System; using System.Collections.Generic; using System.Linq; -using UnityEngine; using UObject = UnityEngine.Object; namespace UnityEditor.EditorTools { + struct CustomEditorTool + { + public Editor owner; + public Type editorToolType; + + public CustomEditorTool(Editor owner, Type tool) + { + this.owner = owner; + this.editorToolType = tool; + } + } + static class EditorToolUtility { struct CustomEditorToolAssociation @@ -123,33 +134,25 @@ internal static Type GetCustomEditorToolTargetType(EditorTool tool) return attr.targetType; } - internal static Dictionary> FindActiveCustomEditorTools() + internal static void GetEditorToolsForTracker(ActiveEditorTracker tracker, List tools) { - var selection = Selection.transforms; - var tools = new Dictionary>(); + var editors = tracker.activeEditors; - for (int i = 0, c = selection.Length; i < c; i++) + for (int i = 0, c = editors.Length; i < c; i++) { - foreach (var component in selection[i].GetComponents()) - { - if (component != null) - { - var eligibleToolTypes = GetCustomEditorToolsForType(component.GetType()); + var editor = editors[i]; - foreach (var type in eligibleToolTypes) - { - List targets; + if (editor == null || editor.target == null) + continue; - if (tools.TryGetValue(type, out targets)) - tools[type].Add(component); - else - tools.Add(type, new List() { component }); - } - } + var targetType = editor.target.GetType(); + var eligibleToolTypes = GetCustomEditorToolsForType(targetType); + + foreach (var type in eligibleToolTypes) + { + tools.Add(new CustomEditorTool(editor, type)); } } - - return tools; } internal static EditorTool GetEditorToolWithEnum(Tool type) diff --git a/Editor/Mono/Inspector/CustomRenderTextureEditor.cs b/Editor/Mono/Inspector/CustomRenderTextureEditor.cs index 1e480b89e4..11b8675cef 100644 --- a/Editor/Mono/Inspector/CustomRenderTextureEditor.cs +++ b/Editor/Mono/Inspector/CustomRenderTextureEditor.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.IO; using AnimatedBool = UnityEditor.AnimatedValues.AnimBool; +using UnityEngine.Experimental.Rendering; namespace UnityEditor { @@ -433,8 +434,8 @@ static void SaveToDisk(MenuCommand command) int depth = texture.volumeDepth; // This has its TextureFormat helper equivalent in C++ but since we are going to try to refactor TextureFormat/RenderTextureFormat into a single type so let's not bloat Scripting APIs with stuff that will get useless soon(tm). - bool isFormatHDR = IsHDRFormat(texture.format); - bool isFloatFormat = (texture.format == RenderTextureFormat.ARGBFloat || texture.format == RenderTextureFormat.RFloat); + bool isFormatHDR = GraphicsFormatUtility.IsIEEE754Format(texture.graphicsFormat); + bool isFloatFormat = GraphicsFormatUtility.IsFloatFormat(texture.graphicsFormat); TextureFormat format = isFormatHDR ? TextureFormat.RGBAFloat : TextureFormat.RGBA32; int finalWidth = width; diff --git a/Editor/Mono/Inspector/EditMode.cs b/Editor/Mono/Inspector/EditMode.cs index 094c848b55..0d3447fa5e 100644 --- a/Editor/Mono/Inspector/EditMode.cs +++ b/Editor/Mono/Inspector/EditMode.cs @@ -22,15 +22,13 @@ private static class Styles public static readonly GUIStyle singleButtonStyle = "EditModeSingleButton"; } - private const string kEditModeStringKey = "EditModeState"; - private const string kPrevToolStringKey = "EditModePrevTool"; - private const string kOwnerStringKey = "EditModeOwner"; - private static bool s_Debug = false; + const string kOwnerStringKey = "EditModeOwner"; + const string kEditModeStringKey = "EditModeState"; static EditMode() { ownerID = SessionState.GetInt(kOwnerStringKey, ownerID); - editMode = (SceneViewEditMode)SessionState.GetInt(kEditModeStringKey, (int)editMode); + s_EditMode = (SceneViewEditMode)SessionState.GetInt(kEditModeStringKey, (int)s_EditMode); Selection.selectionChanged += OnSelectionChange; } @@ -78,6 +76,24 @@ public enum SceneViewEditMode ParticleSystemShapeModuleScale } + static EditorTool GetTool(IToolModeOwner owner, SceneViewEditMode mode) + { + var editor = owner as Editor; + + if (editor == null) + return null; + + var editorType = editor.GetType(); + + return EditorToolContext.GetCustomEditorTool(x => + { + var tool = x as EditModeTool; + return tool != null + && tool.editorType == editorType + && tool.target == editor.target; + }, true); + } + public static bool IsOwner(Editor editor) { return IsOwner((IToolModeOwner)editor); @@ -88,7 +104,7 @@ internal static bool IsOwner(IToolModeOwner owner) return owner.GetInstanceID() == s_OwnerID; } - private static int ownerID + internal static int ownerID { get { @@ -98,36 +114,20 @@ private static int ownerID { s_OwnerID = value; SessionState.SetInt(kOwnerStringKey, s_OwnerID); - if (s_Debug) - Debug.Log("Set ownerID " + value); } } public static SceneViewEditMode editMode { - get - { - return s_EditMode; - } + get { return s_EditMode; } private set { - if (s_EditMode == SceneViewEditMode.None && value != SceneViewEditMode.None) - { - // EditorToolContext remembers the last persistent tool used - Tools.current = Tool.None; - } - else if (s_EditMode != SceneViewEditMode.None && value == SceneViewEditMode.None) - { - EditorToolContext.RestorePreviousTool(); - } s_EditMode = value; SessionState.SetInt(kEditModeStringKey, (int)s_EditMode); - if (s_Debug) - Debug.Log("Set editMode " + s_EditMode); } } - static void EndSceneViewEditing() + internal static void EndSceneViewEditing() { ChangeEditMode(SceneViewEditMode.None, new Bounds(Vector3.zero, Vector3.positiveInfinity), null); } @@ -142,12 +142,46 @@ public static void OnSelectionChange() public static void QuitEditMode() { - if (Tools.current == Tool.None && editMode != SceneViewEditMode.None) - EditorToolContext.RestorePreviousTool(); - EndSceneViewEditing(); } + internal static void ChangeEditModeFromToolContext(IToolModeOwner owner, SceneViewEditMode mode) + { + // In cases of domain reloads the EditorTool can be deserialized prior to the target Inspector being + // created. The EditMode tools do not expect an editModeStarted callback on reloads. + if (owner == null && mode != SceneViewEditMode.None) + { + editMode = mode; + return; + } + + IToolModeOwner oldOwner = InternalEditorUtility.GetObjectFromInstanceID(ownerID) as IToolModeOwner; + + editMode = mode; + + ownerID = mode != SceneViewEditMode.None ? owner.GetInstanceID() : 0; + + if (onEditModeEndDelegate != null && oldOwner is Editor) + onEditModeEndDelegate(oldOwner as Editor); + + if (editModeEnded != null) + editModeEnded(oldOwner); + + if (editMode != SceneViewEditMode.None) + { + if (onEditModeStartDelegate != null && owner is Editor) + onEditModeStartDelegate(owner as Editor, editMode); + if (editModeStarted != null) + editModeStarted(owner, editMode); + } + + EditModeChanged((mode != SceneViewEditMode.None && owner != null) + ? owner.GetWorldBoundsOfTargets() + : new Bounds(Vector3.zero, Vector3.positiveInfinity)); + + InspectorWindow.RepaintAllInspectors(); + } + [Obsolete("Obsolete msg (UnityUpgradable) -> UnityEditor.EditorTools.EditorTools.RestorePreviousTool()")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ResetToolToPrevious() @@ -155,12 +189,6 @@ public static void ResetToolToPrevious() EditorToolContext.RestorePreviousTool(); } - static void DetectMainToolChange() - { - if (Tools.current != Tool.None && editMode != SceneViewEditMode.None) - EndSceneViewEditing(); - } - [Obsolete("Use signature passing Func rather than Bounds.")] public static void DoEditModeInspectorModeButton(SceneViewEditMode mode, string label, GUIContent icon, Bounds bounds, Editor caller) { @@ -179,8 +207,6 @@ internal static void DoEditModeInspectorModeButton(SceneViewEditMode mode, strin private static void DoEditModeInspectorModeButton(SceneViewEditMode mode, string label, GUIContent icon, Func getBoundsOfTargets, IToolModeOwner owner) { - DetectMainToolChange(); - Rect rect = EditorGUILayout.GetControlRect(true, k_EditColliderbuttonHeight, Styles.singleButtonStyle); Rect buttonRect = new Rect(rect.xMin + EditorGUIUtility.labelWidth, rect.yMin, k_EditColliderbuttonWidth, k_EditColliderbuttonHeight); @@ -193,8 +219,7 @@ private static void DoEditModeInspectorModeButton(SceneViewEditMode mode, string labelSize.x, rect.height); - int callerID = owner.GetInstanceID(); - bool modeEnabled = editMode == mode && ownerID == callerID; + bool modeEnabled = IsOwner(owner); EditorGUI.BeginChangeCheck(); @@ -229,8 +254,6 @@ internal static void DoInspectorToolbar(SceneViewEditMode[] modes, GUIContent[] private static void DoInspectorToolbar(SceneViewEditMode[] modes, GUIContent[] guiContents, Func getBoundsOfTargets, IToolModeOwner owner) { - DetectMainToolChange(); - int callerID = owner.GetInstanceID(); int selectedIndex = ArrayUtility.IndexOf(modes, editMode); @@ -260,28 +283,26 @@ internal static void ChangeEditMode(SceneViewEditMode mode, IToolModeOwner owner internal static void ChangeEditMode(SceneViewEditMode mode, Bounds bounds, IToolModeOwner owner) { - IToolModeOwner oldOwner = InternalEditorUtility.GetObjectFromInstanceID(ownerID) as IToolModeOwner; - - editMode = mode; + if (mode == SceneViewEditMode.None) + { + if (s_EditMode != SceneViewEditMode.None && (EditorToolContext.activeTool is EditModeTool || EditorToolContext.activeTool is NoneTool)) + EditorTools.RestorePreviousTool(); - ownerID = mode != SceneViewEditMode.None ? owner.GetInstanceID() : 0; + return; + } - if (onEditModeEndDelegate != null && oldOwner is Editor) - onEditModeEndDelegate(oldOwner as Editor); - if (editModeEnded != null) - editModeEnded(oldOwner); + var tool = GetTool(owner, mode); - if (editMode != SceneViewEditMode.None) + if (tool != null) { - if (onEditModeStartDelegate != null && owner is Editor) - onEditModeStartDelegate(owner as Editor, editMode); - if (editModeStarted != null) - editModeStarted(owner, editMode); + EditorTools.SetActiveTool(tool); + } + else + { + // SceneViewEditModeTool doesn't exist, use old path + EditorTools.SetActiveTool(); + ChangeEditModeFromToolContext(owner, mode); } - - EditModeChanged(bounds); - - InspectorWindow.RepaintAllInspectors(); } // We make sure edited object is seen by the camera. We need object bounds to do that check. diff --git a/Editor/Mono/Inspector/LightEditor.cs b/Editor/Mono/Inspector/LightEditor.cs index b664f7afb2..55b7a05fbb 100644 --- a/Editor/Mono/Inspector/LightEditor.cs +++ b/Editor/Mono/Inspector/LightEditor.cs @@ -205,7 +205,9 @@ public void OnDestroy() static Texture2D CreateKelvinGradientTexture(string name, int width, int height, float minKelvin, float maxKelvin) { - var texture = new Texture2D(width, height, TextureFormat.ARGB32, false) + // The texture is draw with a simple internal-GUITexture shader that don't perform any gamma correction + // so we need to provide value for color temperature texture in gamma space and use a linear format for the texture + var texture = new Texture2D(width, height, TextureFormat.ARGB32, false, true) { name = name, hideFlags = HideFlags.HideAndDontSave diff --git a/Editor/Mono/Inspector/LightProbeGroupInspector.cs b/Editor/Mono/Inspector/LightProbeGroupInspector.cs index 2f562e22d2..d8fbafac9b 100644 --- a/Editor/Mono/Inspector/LightProbeGroupInspector.cs +++ b/Editor/Mono/Inspector/LightProbeGroupInspector.cs @@ -612,6 +612,9 @@ public void OnDisable() EndEditProbes(); Undo.undoRedoPerformed -= UndoRedoPerformed; SceneView.duringSceneGui -= OnSceneGUIDelegate; + EditMode.editModeStarted -= OnEditModeStarted; + EditMode.editModeEnded -= OnEditModeEnded; + if (target != null) { m_Editor.PushProbePositions(); diff --git a/Editor/Mono/Inspector/RenderTextureEditor.cs b/Editor/Mono/Inspector/RenderTextureEditor.cs index b20805e217..72673b5761 100644 --- a/Editor/Mono/Inspector/RenderTextureEditor.cs +++ b/Editor/Mono/Inspector/RenderTextureEditor.cs @@ -4,7 +4,7 @@ using UnityEngine; using System; - +using UnityEngine.Experimental.Rendering; namespace UnityEditor { @@ -19,6 +19,7 @@ private class Styles public readonly GUIContent antiAliasing = EditorGUIUtility.TrTextContent("Anti-Aliasing", "Number of anti-aliasing samples."); public readonly GUIContent colorFormat = EditorGUIUtility.TrTextContent("Color Format", "Format of the color buffer."); public readonly GUIContent depthBuffer = EditorGUIUtility.TrTextContent("Depth Buffer", "Format of the depth buffer."); + public readonly GUIContent enableCompatibleFormat = EditorGUIUtility.TrTextContent("Enable Compatible Color Format", "Lets the color format be changed to compatible and supported formats for the target platform automatically, if the target platform doesn't support the input format."); public readonly GUIContent dimension = EditorGUIUtility.TrTextContent("Dimension", "Is the texture 2D, Cube or 3D?"); public readonly GUIContent enableMipmaps = EditorGUIUtility.TrTextContent("Enable Mip Maps", "This render texture will have Mip Maps."); public readonly GUIContent bindMS = EditorGUIUtility.TrTextContent("Bind multisampled", "If enabled, the texture will not go through an AA resolve if bound to a shader."); @@ -58,6 +59,7 @@ protected enum GUIElements SerializedProperty m_Depth; SerializedProperty m_ColorFormat; SerializedProperty m_DepthFormat; + SerializedProperty m_EnableCompatibleFormat; SerializedProperty m_AntiAliasing; SerializedProperty m_EnableMipmaps; SerializedProperty m_AutoGeneratesMipmaps; @@ -74,6 +76,7 @@ protected override void OnEnable() m_AntiAliasing = serializedObject.FindProperty("m_AntiAliasing"); m_ColorFormat = serializedObject.FindProperty("m_ColorFormat"); m_DepthFormat = serializedObject.FindProperty("m_DepthFormat"); + m_EnableCompatibleFormat = serializedObject.FindProperty("m_EnableCompatibleFormat"); m_EnableMipmaps = serializedObject.FindProperty("m_MipMap"); m_AutoGeneratesMipmaps = serializedObject.FindProperty("m_GenerateMips"); m_Dimension = serializedObject.FindProperty("m_Dimension"); @@ -81,17 +84,6 @@ protected override void OnEnable() m_UseDynamicScale = serializedObject.FindProperty("m_UseDynamicScale"); } - public static bool IsHDRFormat(RenderTextureFormat format) - { - return format == RenderTextureFormat.ARGBHalf || - format == RenderTextureFormat.RGB111110Float || - format == RenderTextureFormat.RGFloat || - format == RenderTextureFormat.ARGBFloat || - format == RenderTextureFormat.RFloat || - format == RenderTextureFormat.RGHalf || - format == RenderTextureFormat.RHalf; - } - protected void OnRenderTextureGUI(GUIElements guiElements) { GUI.changed = false; @@ -115,15 +107,12 @@ protected void OnRenderTextureGUI(GUIElements guiElements) if ((guiElements & GUIElements.RenderTargetAAGUI) != 0) EditorGUILayout.IntPopup(m_AntiAliasing, styles.renderTextureAntiAliasing, styles.renderTextureAntiAliasingValues, styles.antiAliasing); + EditorGUILayout.PropertyField(m_EnableCompatibleFormat, styles.enableCompatibleFormat); EditorGUILayout.PropertyField(m_ColorFormat, styles.colorFormat); if ((guiElements & GUIElements.RenderTargetDepthGUI) != 0) EditorGUILayout.PropertyField(m_DepthFormat, styles.depthBuffer); - bool isHDRRenderTexture = IsHDRFormat((RenderTextureFormat)m_ColorFormat.intValue); - using (new EditorGUI.DisabledScope(isHDRRenderTexture)) - { - EditorGUILayout.PropertyField(m_sRGB, styles.sRGBTexture); - } + m_sRGB.boolValue = GraphicsFormatUtility.IsSRGBFormat((GraphicsFormat)m_ColorFormat.intValue); using (new EditorGUI.DisabledScope(isTexture3D)) { @@ -178,7 +167,7 @@ public override void OnInspectorGUI() private bool RenderTextureHasDepth() { - if (TextureUtil.IsDepthRTFormat((RenderTextureFormat)m_ColorFormat.enumValueIndex)) + if (GraphicsFormatUtility.IsDepthFormat((GraphicsFormat)m_ColorFormat.enumValueIndex)) return true; return m_DepthFormat.enumValueIndex != 0; @@ -197,12 +186,12 @@ override public string GetInfoString() if (QualitySettings.desiredColorSpace == ColorSpace.Linear) { - bool formatIsHDR = IsHDRFormat(t.format); + bool formatIsHDR = GraphicsFormatUtility.IsIEEE754Format(t.graphicsFormat); bool sRGB = t.sRGB && !formatIsHDR; info += " " + (sRGB ? "sRGB" : "Linear"); } - info += " " + t.format; + info += " " + t.graphicsFormat; info += " " + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySizeLong(t)); return info; diff --git a/Editor/Mono/Inspector/ShaderInspector.cs b/Editor/Mono/Inspector/ShaderInspector.cs index ff54acee0e..4052cf80d6 100644 --- a/Editor/Mono/Inspector/ShaderInspector.cs +++ b/Editor/Mono/Inspector/ShaderInspector.cs @@ -36,6 +36,9 @@ internal class ShaderInspector : Editor private const float kSpace = 5f; + const float kValueFieldWidth = 200.0f; + const float kArrayValuePopupBtnWidth = 25.0f; + internal class Styles { public static Texture2D errorIcon = EditorGUIUtility.LoadIcon("console.erroricon.sml"); @@ -50,6 +53,8 @@ internal class Styles public static GUIContent no = EditorGUIUtility.TrTextContent("no"); public static GUIContent builtinShader = EditorGUIUtility.TrTextContent("Built-in shader"); + + public static readonly GUIContent arrayValuePopupButton = EditorGUIUtility.TrTextContent("..."); } static readonly int kErrorViewHash = "ShaderErrorView".GetHashCode(); @@ -106,6 +111,7 @@ public override void OnInspectorGUI() break; } EditorGUILayout.LabelField("Disable batching", disableBatchingString); + ShowKeywords(s); // If any SRP is active, then display the SRP Batcher compatibility status if (RenderPipelineManager.currentPipeline != null) @@ -125,6 +131,27 @@ public override void OnInspectorGUI() } } + private void ShowKeywords(Shader s) + { + EditorGUILayout.BeginHorizontal(); + EditorGUILayout.PrefixLabel("Keywords", EditorStyles.miniButton); + + Rect buttonRect = GUILayoutUtility.GetRect(Styles.arrayValuePopupButton, GUI.skin.button, GUILayout.MinWidth(kValueFieldWidth)); + buttonRect.width = kArrayValuePopupBtnWidth; + if (GUI.Button(buttonRect, Styles.arrayValuePopupButton, EditorStyles.miniButton)) + { + var globalKeywords = ShaderUtil.GetShaderGlobalKeywords(s); + var localKeywords = ShaderUtil.GetShaderLocalKeywords(s); + + PopupWindowWithoutFocus.Show( + buttonRect, + new KeywordsPopup(globalKeywords, localKeywords, 150.0f), + new[] { PopupLocation.Left, PopupLocation.Below, PopupLocation.Right }); + } + + EditorGUILayout.EndHorizontal(); + } + private void ShowShaderCodeArea(Shader s) { ShowSurfaceShaderButton(s); @@ -385,6 +412,60 @@ private static void ShowFixedFunctionShaderButton(Shader s) } } + internal class KeywordsPopup : PopupWindowContent + { + private Vector2 m_ScrollPos = Vector2.zero; + private string[] m_GlobalKeywords; + private string[] m_LocalKeywords; + private bool m_GlobalKeywordsExpended; + private bool m_LocalKeywordsExpended; + private float m_WindowWidth; + + private static readonly GUIStyle m_Style = EditorStyles.miniLabel; + + public KeywordsPopup(string[] globalKeywords, string[] localKeywords, float windowWidth) + { + m_GlobalKeywords = globalKeywords; + m_LocalKeywords = localKeywords; + m_GlobalKeywordsExpended = true; + m_LocalKeywordsExpended = true; + m_WindowWidth = windowWidth; + } + + public override Vector2 GetWindowSize() + { + var numValues = m_GlobalKeywords.Length + m_LocalKeywords.Length + 2; + var lineHeight = m_Style.lineHeight + m_Style.padding.vertical + m_Style.margin.top; + return new Vector2(m_WindowWidth, Math.Min(lineHeight * numValues, 250.0f)); + } + + public override void OnGUI(Rect rect) + { + m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos); + + m_GlobalKeywordsExpended = KeywordsFoldout(m_GlobalKeywordsExpended, "Global Keywords", m_GlobalKeywords); + m_LocalKeywordsExpended = KeywordsFoldout(m_LocalKeywordsExpended, "Local Keywords", m_LocalKeywords); + + EditorGUILayout.EndScrollView(); + } + + private bool KeywordsFoldout(bool expended, string name, string[] values) + { + expended = EditorGUILayout.Foldout(expended, name, true, m_Style); + + if (expended) + { + EditorGUI.indentLevel++; + for (int i = 0; i < values.Length; ++i) + { + EditorGUILayout.LabelField(values[i], m_Style); + } + EditorGUI.indentLevel--; + } + + return expended; + } + } // Popup window to select which platforms to compile a shader for. internal class ShaderInspectorPlatformsPopup : PopupWindowContent diff --git a/Editor/Mono/Inspector/TextureInspector.cs b/Editor/Mono/Inspector/TextureInspector.cs index 228f419ef2..9544f149de 100644 --- a/Editor/Mono/Inspector/TextureInspector.cs +++ b/Editor/Mono/Inspector/TextureInspector.cs @@ -606,7 +606,7 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) RenderTexture rt = t as RenderTexture; if (rt != null) { - if (!SystemInfo.SupportsRenderTextureFormat(rt.format)) + if (!SystemInfo.IsFormatSupported(rt.graphicsFormat, FormatUsage.Render)) return; // can't do this RT format rt.Create(); } @@ -799,7 +799,7 @@ public override string GetInfoString() bool isNormalmap = IsNormalMap(t); bool stillNeedsCompression = TextureUtil.DoesTextureStillNeedToBeCompressed(AssetDatabase.GetAssetPath(t)); bool isNPOT = t2 != null && TextureUtil.IsNonPowerOfTwo(t2); - TextureFormat format = TextureUtil.GetTextureFormat(t); + GraphicsFormat format = t.graphicsFormat; showSize = !stillNeedsCompression; if (isNPOT) @@ -812,18 +812,22 @@ public override string GetInfoString() { switch (format) { - case TextureFormat.DXT5: + case GraphicsFormat.RGBA_DXT5_SRGB: + case GraphicsFormat.RGBA_DXT5_UNorm: info += " DXTnm"; break; - case TextureFormat.RGBA32: - case TextureFormat.ARGB32: + case GraphicsFormat.R8G8B8A8_SRGB: + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: info += " Nm 32 bit"; break; - case TextureFormat.ARGB4444: + case GraphicsFormat.R4G4B4A4_UNormPack16: + case GraphicsFormat.B4G4R4A4_UNormPack16: info += " Nm 16 bit"; break; default: - info += " " + TextureUtil.GetTextureFormatString(format); + info += " " + GraphicsFormatUtility.GetFormatString(format); break; } } @@ -834,10 +838,10 @@ public override string GetInfoString() int dummyComressionQuality; textureImporter.ReadTextureImportInstructions(EditorUserBuildSettings.activeBuildTarget, out desiredFormat, out dummyColorSpace, out dummyComressionQuality); - info += "\n " + TextureUtil.GetTextureFormatString(format) + "(Original) " + TextureUtil.GetTextureFormatString(desiredFormat) + "(Atlas)"; + info += "\n " + GraphicsFormatUtility.GetFormatString(format) + "(Original) " + TextureUtil.GetTextureFormatString(desiredFormat) + "(Atlas)"; } else - info += " " + TextureUtil.GetTextureFormatString(format); + info += " " + GraphicsFormatUtility.GetFormatString(format); } if (showSize) diff --git a/Editor/Mono/PerformanceTools/FrameDebugger.cs b/Editor/Mono/PerformanceTools/FrameDebugger.cs index 065b0483f2..058033396f 100644 --- a/Editor/Mono/PerformanceTools/FrameDebugger.cs +++ b/Editor/Mono/PerformanceTools/FrameDebugger.cs @@ -16,6 +16,7 @@ using UnityEngine.Experimental.Networking.PlayerConnection; using ConnectionUtility = UnityEditor.Experimental.Networking.PlayerConnection.EditorGUIUtility; using ConnectionGUILayout = UnityEditor.Experimental.Networking.PlayerConnection.EditorGUILayout; +using UnityEngine.Experimental.Rendering; namespace UnityEditorInternal { @@ -785,7 +786,7 @@ private void DrawRenderTargetControls() if (cur.rtWidth <= 0 || cur.rtHeight <= 0) return; - var isDepthOnlyRT = (cur.rtFormat == (int)RenderTextureFormat.Depth || cur.rtFormat == (int)RenderTextureFormat.Shadowmap); + var isDepthOnlyRT = GraphicsFormatUtility.IsDepthFormat((GraphicsFormat)cur.rtFormat); var hasShowableDepth = (cur.rtHasDepthTexture != 0); var showableRTCount = cur.rtCount; if (hasShowableDepth) @@ -853,7 +854,7 @@ private void DrawRenderTargetControls() GUILayout.Label(string.Format("{0}x{1} {2}", cur.rtWidth, cur.rtHeight, - (RenderTextureFormat)cur.rtFormat)); + (GraphicsFormat)cur.rtFormat)); if (cur.rtDim == (int)UnityEngine.Rendering.TextureDimension.Cube) GUILayout.Label("Rendering into cubemap"); } diff --git a/Editor/Mono/SceneManagement/StageManager/StageUtility.cs b/Editor/Mono/SceneManagement/StageManager/StageUtility.cs index a2c518362d..e24a62f8a8 100644 --- a/Editor/Mono/SceneManagement/StageManager/StageUtility.cs +++ b/Editor/Mono/SceneManagement/StageManager/StageUtility.cs @@ -13,7 +13,7 @@ namespace UnityEditor.SceneManagement { public static partial class StageUtility { - [Shortcut("Stage/Go Back", KeyCode.O)] + [Shortcut("Stage/Go Back", KeyCode.H)] static void GoBackShortcut() { StageUtility.GoBackToPreviousStage(); diff --git a/Editor/Mono/SceneView/SceneView.cs b/Editor/Mono/SceneView/SceneView.cs index 494a6d5dab..1e1bf2ba23 100644 --- a/Editor/Mono/SceneView/SceneView.cs +++ b/Editor/Mono/SceneView/SceneView.cs @@ -106,25 +106,12 @@ public static SceneView lastActiveSceneView [SerializeField] bool m_ShowContextualTools; - bool displayToolModes - { - get - { - return m_ShowContextualTools; - } - set - { - if (m_ShowContextualTools == value) - return; - - if (m_ShowContextualTools) - duringSceneGui -= EditorToolGUI.DrawSceneViewTools; - - m_ShowContextualTools = value; + static Editor[] s_ActiveEditors; - if (m_ShowContextualTools) - duringSceneGui += EditorToolGUI.DrawSceneViewTools; - } + internal bool displayToolModes + { + get { return m_ShowContextualTools; } + set { m_ShowContextualTools = value; } } [SerializeField] @@ -773,11 +760,19 @@ public static bool FrameLastActiveSceneViewWithLock() return lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent(EventCommandNames.FrameSelectedWithLock)); } - internal Editor[] GetActiveEditors() + internal IEnumerable activeEditors { - if (m_Tracker == null) - m_Tracker = ActiveEditorTracker.sharedTracker; - return m_Tracker.activeEditors; + get + { + if (s_ActiveEditors == null) + { + if (m_Tracker == null) + m_Tracker = ActiveEditorTracker.sharedTracker; + s_ActiveEditors = m_Tracker.activeEditors; + } + + return s_ActiveEditors; + } } private static List GetAllSceneCamerasAsList() @@ -876,6 +871,7 @@ public override void OnEnable() EditorApplication.modifierKeysChanged += RepaintAll; // Because we show handles on shift SceneVisibilityManager.hiddenContentChanged += HiddenContentChanged; SceneVisibilityManager.currentStageIsolated += CurrentStageIsolated; + ActiveEditorTracker.editorTrackerRebuilt += () => { s_ActiveEditors = null; }; m_DraggingLockedState = DraggingLockedState.NotDragging; @@ -887,9 +883,6 @@ public override void OnEnable() if (m_CameraMode.drawMode == DrawCameraMode.UserDefined && !s_UserDefinedModes.Contains(m_CameraMode)) AddCameraMode(m_CameraMode.name, m_CameraMode.section); - if (m_ShowContextualTools) - duringSceneGui += EditorToolGUI.DrawSceneViewTools; - base.OnEnable(); if (SupportsStageHandling()) @@ -2179,6 +2172,7 @@ protected virtual void OnGUI() s_CurrentDrawingSceneView = this; Event evt = Event.current; + if (evt.type == EventType.Repaint) { s_MouseRects.Clear(); @@ -2255,7 +2249,7 @@ protected virtual void OnGUI() //Ensure that the target texture is clamped [0-1] //This is needed because otherwise gizmo rendering gets all //messed up (think HDR target with value of 50 + alpha blend gizmo... gonna be white!) - if (!UseSceneFiltering() && evt.type == EventType.Repaint && RenderTextureEditor.IsHDRFormat(m_SceneTargetTexture.format)) + if (!UseSceneFiltering() && evt.type == EventType.Repaint && GraphicsFormatUtility.IsIEEE754Format(m_SceneTargetTexture.graphicsFormat)) { var currentDepthBuffer = Graphics.activeDepthBuffer; var rtDesc = m_SceneTargetTexture.descriptor; @@ -2280,7 +2274,6 @@ protected virtual void OnGUI() m_Camera.renderingPath = oldRenderingPath; - if (!UseSceneFiltering()) { if (evt.type == EventType.Repaint) @@ -2309,6 +2302,9 @@ protected virtual void OnGUI() GL.Clear(false, true, new Color(0, 0, 0, 0)); // Only clear color. Keep depth intact. } + if (displayToolModes) + EditorToolGUI.DrawSceneViewTools(this); + // Calling OnSceneGUI before DefaultHandles, so users can use events before the Default Handles HandleSelectionAndOnSceneGUI(); @@ -3102,7 +3098,7 @@ public virtual bool FrameSelected(bool lockView, bool instant) Bounds bounds = InternalEditorUtility.CalculateSelectionBounds(false, Tools.pivotMode == PivotMode.Pivot); // Check active editor for OnGetFrameBounds - foreach (Editor editor in GetActiveEditors()) + foreach (Editor editor in activeEditors) { MethodInfo hasBoundsMethod = editor.GetType().GetMethod("HasFrameBounds", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy); @@ -3183,7 +3179,7 @@ void CreateSceneCameraAndLights() void CallOnSceneGUI() { - foreach (Editor editor in GetActiveEditors()) + foreach (Editor editor in activeEditors) { if (!EditorGUIUtility.IsGizmosAllowedForObject(editor.target)) continue; @@ -3239,7 +3235,7 @@ void ResetOnSceneGUIState() void CallOnPreSceneGUI() { - foreach (Editor editor in GetActiveEditors()) + foreach (Editor editor in activeEditors) { // reset the handles matrix, OnPreSceneGUI calls may change it. Handles.ClearHandles(); diff --git a/Editor/Mono/SceneView/SceneViewOverlay.cs b/Editor/Mono/SceneView/SceneViewOverlay.cs index 2ddf43acfb..305bec7ece 100644 --- a/Editor/Mono/SceneView/SceneViewOverlay.cs +++ b/Editor/Mono/SceneView/SceneViewOverlay.cs @@ -42,6 +42,7 @@ private class OverlayWindow : IComparable public int m_PrimaryOrder; // lower order is below high order public int m_SecondaryOrder; // used for primary order that are equal (should be unique) public Object m_Target; + public EditorWindow m_EditorWindow; public int CompareTo(OverlayWindow other) { @@ -67,9 +68,6 @@ public SceneViewOverlay(SceneView sceneView) public void Begin() { - if (!m_SceneView.m_ShowSceneViewWindows) - return; - if (Event.current.type == EventType.Layout) m_Windows.Clear(); @@ -83,9 +81,6 @@ static class Styles public void End() { - if (!m_SceneView.m_ShowSceneViewWindows) - return; - m_Windows.Sort(); if (m_Windows.Count > 0) @@ -108,6 +103,9 @@ private void WindowTrampoline(int id) float paddingOffset = -k_WindowPadding; foreach (OverlayWindow win in m_Windows) { + if (!m_SceneView.m_ShowSceneViewWindows && win.m_EditorWindow != m_SceneView) + continue; + GUILayout.Space(k_WindowPadding + paddingOffset); paddingOffset = 0f; EditorGUIUtility.ResetGUIState(); @@ -162,7 +160,8 @@ public static void Window(GUIContent title, WindowFunction sceneViewFunc, int or Window(title, sceneViewFunc, order, null, option); } - public static void Window(GUIContent title, WindowFunction sceneViewFunc, int order, Object target, WindowDisplayOption option) + // pass window parameter to render in sceneviews that are not the active view. + public static void Window(GUIContent title, WindowFunction sceneViewFunc, int order, Object target, WindowDisplayOption option, EditorWindow window = null) { if (Event.current.type != EventType.Layout) return; @@ -182,6 +181,7 @@ public static void Window(GUIContent title, WindowFunction sceneViewFunc, int or newWindow.m_PrimaryOrder = order; newWindow.m_SecondaryOrder = m_Windows.Count; // just use a value that is unique across overlays newWindow.m_Target = target; + newWindow.m_EditorWindow = window; m_Windows.Add(newWindow); } diff --git a/Editor/Mono/Selection.bindings.cs b/Editor/Mono/Selection.bindings.cs index ef5daa3a2a..f266c13aed 100644 --- a/Editor/Mono/Selection.bindings.cs +++ b/Editor/Mono/Selection.bindings.cs @@ -125,5 +125,9 @@ extern public static string[] assetGUIDs [NativeMethod("GetSelectedAssetGUIDStrings")] get; } + + [StaticAccessor("Selection", StaticAccessorType.DoubleColon)] + [NativeName("SelectionCount")] + internal extern static int count { get; } } } diff --git a/Editor/Mono/ShaderUtil.bindings.cs b/Editor/Mono/ShaderUtil.bindings.cs index db83b07c49..b079936ea5 100644 --- a/Editor/Mono/ShaderUtil.bindings.cs +++ b/Editor/Mono/ShaderUtil.bindings.cs @@ -251,6 +251,9 @@ public static void UpdateShaderAsset(Shader shader, string source) extern internal static int GetCurrentShaderVariantCollectionVariantCount(); extern internal static bool AddNewShaderToCollection(Shader shader, ShaderVariantCollection collection); + extern internal static string[] GetAllGlobalKeywords(); + extern internal static string[] GetShaderGlobalKeywords([NotNull] Shader shader); + extern internal static string[] GetShaderLocalKeywords([NotNull] Shader shader); [FreeFunction] public static extern ShaderInfo[] GetAllShaderInfo(); diff --git a/Modules/Animation/ScriptBindings/AvatarBuilder.bindings.cs b/Modules/Animation/ScriptBindings/AvatarBuilder.bindings.cs index 78b386654b..5b6b14dbf7 100644 --- a/Modules/Animation/ScriptBindings/AvatarBuilder.bindings.cs +++ b/Modules/Animation/ScriptBindings/AvatarBuilder.bindings.cs @@ -88,6 +88,7 @@ public struct HumanDescription internal float m_ArmStretch; internal float m_LegStretch; internal float m_FeetSpacing; + internal float m_GlobalScale; internal string m_RootMotionBoneName; diff --git a/Modules/IMGUI/GUIUtility.cs b/Modules/IMGUI/GUIUtility.cs index c055e69b09..62439b35ca 100644 --- a/Modules/IMGUI/GUIUtility.cs +++ b/Modules/IMGUI/GUIUtility.cs @@ -264,6 +264,14 @@ internal static void CheckOnGUI() throw new ArgumentException("You can only call GUI functions from inside OnGUI."); } + [VisibleToOtherModules("UnityEngine.UIElementsModule")] + internal static float RoundToPixelGrid(float v) + { + // Using same rounding constant as GUITexture::AlignPointToDevice + const float kNearestRoundingOffset = 0.48f; + return Mathf.Floor((v * GUIUtility.pixelsPerPoint) + kNearestRoundingOffset) / GUIUtility.pixelsPerPoint; + } + // Convert a point from GUI position to screen space. public static Vector2 GUIToScreenPoint(Vector2 guiPoint) { diff --git a/Modules/UIElements/ScrollView.cs b/Modules/UIElements/ScrollView.cs index 24a8f21303..8a446b14c8 100644 --- a/Modules/UIElements/ScrollView.cs +++ b/Modules/UIElements/ScrollView.cs @@ -124,8 +124,8 @@ void UpdateContentViewTransform() var t = contentContainer.transform.position; var offset = scrollOffset; - t.x = -offset.x; - t.y = -offset.y; + t.x = GUIUtility.RoundToPixelGrid(-offset.x); + t.y = GUIUtility.RoundToPixelGrid(-offset.y); contentContainer.transform.position = t; this.IncrementVersion(VersionChangeType.Repaint); diff --git a/Modules/UIElements/VisualElement.cs b/Modules/UIElements/VisualElement.cs index b0809dd2f1..00d2aeda06 100644 --- a/Modules/UIElements/VisualElement.cs +++ b/Modules/UIElements/VisualElement.cs @@ -1161,7 +1161,13 @@ public void AddToClassList(string className) { return; } - m_ClassList.Capacity += 1; + + // Avoid list size doubling when list is full. + if (m_ClassList.Capacity == m_ClassList.Count) + { + m_ClassList.Capacity += 1; + } + m_ClassList.Add(className); } @@ -1272,7 +1278,12 @@ void SetPropertyInternal(PropertyName key, object value) return; } } - ++m_PropertyBag.Capacity; + + if (m_PropertyBag.Capacity == m_PropertyBag.Count) + { + m_PropertyBag.Capacity += 1; + } + m_PropertyBag.Add(kv); } } diff --git a/Modules/XR/ScriptBindings/XRInput.bindings.cs b/Modules/XR/ScriptBindings/XRInput.bindings.cs index 743002b5ce..efe8cf76f0 100644 --- a/Modules/XR/ScriptBindings/XRInput.bindings.cs +++ b/Modules/XR/ScriptBindings/XRInput.bindings.cs @@ -90,7 +90,7 @@ public enum InputDeviceRole : UInt32 }; [Flags] - public enum TrackingState : UInt32 + public enum InputTrackingState : UInt32 { None = 0, Position = 1 << 0, @@ -227,7 +227,7 @@ public static class CommonUsages public static InputFeatureUsage primary2DAxisTouch = new InputFeatureUsage("Primary2DAxisTouch"); public static InputFeatureUsage thumbrest = new InputFeatureUsage("Thumbrest"); - public static InputFeatureUsage trackingState = new InputFeatureUsage("TrackingState"); + public static InputFeatureUsage trackingState = new InputFeatureUsage("TrackingState"); public static InputFeatureUsage indexTouch = new InputFeatureUsage("IndexTouch"); public static InputFeatureUsage thumbTouch = new InputFeatureUsage("ThumbTouch"); @@ -314,15 +314,15 @@ public bool TryGetFeatureUsages(List featureUsages) public bool TryGetFeatureValue(InputFeatureUsage usage, out Bone value) { return InputDevices.TryGetFeatureValue_XRBone(m_DeviceId, usage.name, out value); } public bool TryGetFeatureValue(InputFeatureUsage usage, out Eyes value) { return InputDevices.TryGetFeatureValue_XREyes(m_DeviceId, usage.name, out value); } - public bool TryGetFeatureValue(InputFeatureUsage usage, out TrackingState value) + public bool TryGetFeatureValue(InputFeatureUsage usage, out InputTrackingState value) { uint intValue = 0; if (InputDevices.TryGetFeatureValue_UInt32(m_DeviceId, usage.name, out intValue)) { - value = (TrackingState)intValue; + value = (InputTrackingState)intValue; return true; } - value = TrackingState.None; + value = InputTrackingState.None; return false; } diff --git a/Projects/CSharp/UnityEditor.csproj b/Projects/CSharp/UnityEditor.csproj index 1106de9703..d3bd6ce23a 100644 --- a/Projects/CSharp/UnityEditor.csproj +++ b/Projects/CSharp/UnityEditor.csproj @@ -1525,6 +1525,9 @@ Editor\Mono\GUI\DragRect.cs + + Editor\Mono\GUI\EditModeTools\EditModeTool.cs + Editor\Mono\GUI\EditorApplicationLayout.cs diff --git a/README.md b/README.md index 68ace52273..7164458d0b 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Unity 2019.1.0a13 C# reference source code +## Unity 2019.1.0a14 C# reference source code The C# part of the Unity engine and editor source code. May be used for reference purposes only. diff --git a/Runtime/Export/Graphics/GraphicsFormatUtility.bindings.cs b/Runtime/Export/Graphics/GraphicsFormatUtility.bindings.cs index 946f52588e..dde53b6e5d 100644 --- a/Runtime/Export/Graphics/GraphicsFormatUtility.bindings.cs +++ b/Runtime/Export/Graphics/GraphicsFormatUtility.bindings.cs @@ -52,6 +52,9 @@ public static GraphicsFormat GetGraphicsFormat(RenderTextureFormat format, Rende [FreeFunction] extern public static bool IsSRGBFormat(GraphicsFormat format); + [FreeFunction] + extern public static bool IsSwizzleFormat(GraphicsFormat format); + [FreeFunction] extern public static GraphicsFormat GetSRGBFormat(GraphicsFormat format); @@ -91,6 +94,9 @@ public static GraphicsFormat GetGraphicsFormat(RenderTextureFormat format, Rende [FreeFunction] extern public static bool IsAlphaOnlyFormat(GraphicsFormat format); + [FreeFunction] + extern public static bool IsAlphaTestFormat(GraphicsFormat format); + [FreeFunction] extern public static bool HasAlphaChannel(GraphicsFormat format); diff --git a/Runtime/Export/Graphics/Texture.cs b/Runtime/Export/Graphics/Texture.cs index 477e184b8e..f6823ebd69 100644 --- a/Runtime/Export/Graphics/Texture.cs +++ b/Runtime/Export/Graphics/Texture.cs @@ -39,7 +39,7 @@ public GraphicsFormat graphicsFormat public RenderTextureFormat colorFormat { get { return GraphicsFormatUtility.GetRenderTextureFormat(graphicsFormat); } - set { graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(value, sRGB); } + set { graphicsFormat = SystemInfo.GetCompatibleFormat(GraphicsFormatUtility.GetGraphicsFormat(value, sRGB), FormatUsage.Render); } } private int _depthBufferBits; @@ -66,7 +66,7 @@ public int depthBufferBits public RenderTextureMemoryless memoryless { get; set; } public RenderTextureDescriptor(int width, int height) : this(width, height, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR), 0) {} public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat) : this(width, height, colorFormat, 0) {} - public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat, int depthBufferBits) : this(width, height, GraphicsFormatUtility.GetGraphicsFormat(colorFormat, false), depthBufferBits) {} + public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat, int depthBufferBits) : this(width, height, SystemInfo.GetCompatibleFormat(GraphicsFormatUtility.GetGraphicsFormat(colorFormat, false), FormatUsage.Render), depthBufferBits) {} public RenderTextureDescriptor(int width, int height, GraphicsFormat colorFormat, int depthBufferBits) : this() { this.width = width; @@ -138,7 +138,7 @@ internal bool createdFromScript set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.CreatedFromScript); } } - internal bool useDynamicScale + public bool useDynamicScale { get { return (_flags & RenderTextureCreationFlags.DynamicallyScalable) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.DynamicallyScalable); } @@ -211,6 +211,8 @@ public RenderTextureDescriptor descriptor private static void ValidateRenderTextureDesc(RenderTextureDescriptor desc) { + if (!SystemInfo.IsFormatSupported(desc.graphicsFormat, FormatUsage.Render)) + throw new ArgumentException("RenderTextureDesc graphicsFormat must be a supported GraphicsFormat. " + desc.graphicsFormat + " is not supported.", "desc.graphicsFormat"); if (desc.width <= 0) throw new ArgumentException("RenderTextureDesc width must be greater than zero.", "desc.width"); if (desc.height <= 0) @@ -226,6 +228,22 @@ private static void ValidateRenderTextureDesc(RenderTextureDescriptor desc) public partial class RenderTexture : Texture { + internal static GraphicsFormat GetCompatibleFormat(RenderTextureFormat renderTextureFormat, RenderTextureReadWrite readWrite) + { + GraphicsFormat requestedFormat = GraphicsFormatUtility.GetGraphicsFormat(renderTextureFormat, readWrite); + GraphicsFormat compatibleFormat = SystemInfo.GetCompatibleFormat(requestedFormat, FormatUsage.Render); + + if (requestedFormat == compatibleFormat) + { + return requestedFormat; + } + else + { + Debug.LogWarning(String.Format("'{0}' is not supported. RenderTexture::GetTemporary fallbacks to {1} format on this platform. Use 'SystemInfo.IsFormatSupported' C# API to check format support.", requestedFormat.ToString(), compatibleFormat.ToString())); + return compatibleFormat; + } + } + public static RenderTexture GetTemporary(RenderTextureDescriptor desc) { ValidateRenderTextureDesc(desc); desc.createdFromScript = true; @@ -300,43 +318,43 @@ public static RenderTexture GetTemporary(int width, int height, [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, RenderTextureMemoryless memorylessMode, VRTextureUsage vrUsage) { - return GetTemporaryImpl(width, height, depthBuffer, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), antiAliasing, memorylessMode, vrUsage); + return GetTemporaryImpl(width, height, depthBuffer, GetCompatibleFormat(format, readWrite), antiAliasing, memorylessMode, vrUsage); } [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, RenderTextureMemoryless memorylessMode) { - return GetTemporaryImpl(width, height, depthBuffer, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), antiAliasing, memorylessMode); + return GetTemporaryImpl(width, height, depthBuffer, GetCompatibleFormat(format, readWrite), antiAliasing, memorylessMode); } [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing) { - return GetTemporaryImpl(width, height, depthBuffer, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), antiAliasing); + return GetTemporaryImpl(width, height, depthBuffer, GetCompatibleFormat(format, readWrite), antiAliasing); } [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite) { - return GetTemporaryImpl(width, height, depthBuffer, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite)); + return GetTemporaryImpl(width, height, depthBuffer, GetCompatibleFormat(format, readWrite)); } [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format) { - return GetTemporaryImpl(width, height, depthBuffer, GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Default)); + return GetTemporaryImpl(width, height, depthBuffer, GetCompatibleFormat(format, RenderTextureReadWrite.Default)); } [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer) { - return GetTemporaryImpl(width, height, depthBuffer, GraphicsFormatUtility.GetGraphicsFormat(RenderTextureFormat.Default, RenderTextureReadWrite.Default)); + return GetTemporaryImpl(width, height, depthBuffer, GetCompatibleFormat(RenderTextureFormat.Default, RenderTextureReadWrite.Default)); } [uei.ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height) { - return GetTemporaryImpl(width, height, 0, GraphicsFormatUtility.GetGraphicsFormat(RenderTextureFormat.Default, RenderTextureReadWrite.Default)); + return GetTemporaryImpl(width, height, 0, GetCompatibleFormat(RenderTextureFormat.Default, RenderTextureReadWrite.Default)); } } @@ -344,12 +362,12 @@ public sealed partial class CustomRenderTexture : RenderTexture { // Be careful. We can't call base constructor here because it would create the native object twice. public CustomRenderTexture(int width, int height, RenderTextureFormat format, RenderTextureReadWrite readWrite) - : this(width, height, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite)) + : this(width, height, GetCompatibleFormat(format, readWrite)) { } public CustomRenderTexture(int width, int height, RenderTextureFormat format) - : this(width, height, GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Default)) + : this(width, height, GetCompatibleFormat(format, RenderTextureReadWrite.Default)) { } @@ -395,6 +413,24 @@ void EnableCubemapFace(CubemapFace face, bool value) public partial class Texture : Object { +/* + internal static GraphicsFormat GetCompatibleFormat(TextureFormat format, bool isSRGB) + { + GraphicsFormat requestedFormat = GraphicsFormatUtility.GetGraphicsFormat(format, isSRGB); + GraphicsFormat compatibleFormat = SystemInfo.GetCompatibleFormat(requestedFormat, FormatUsage.Sample); + + if (requestedFormat == compatibleFormat) + { + return requestedFormat; + } + else + { + Debug.LogWarning(String.Format("'{0}' is not supported. Texture fallbacks to {1} format on this platform. Use 'SystemInfo.IsFormatSupported' C# API to check format support.", requestedFormat.ToString(), compatibleFormat.ToString())); + return compatibleFormat; + } + } +*/ + internal bool ValidateFormat(RenderTextureFormat format) { if (SystemInfo.SupportsRenderTextureFormat(format)) @@ -715,6 +751,7 @@ internal Cubemap(int width, TextureFormat textureFormat, bool mipChain, IntPtr n flags |= TextureCreationFlags.MipChain; if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) flags |= TextureCreationFlags.Crunch; + Internal_Create(this, width, format, flags, nativeTex); } diff --git a/Runtime/Export/SystemInfo/SystemInfo.bindings.cs b/Runtime/Export/SystemInfo/SystemInfo.bindings.cs index c810cc51d0..5b1ae153fc 100644 --- a/Runtime/Export/SystemInfo/SystemInfo.bindings.cs +++ b/Runtime/Export/SystemInfo/SystemInfo.bindings.cs @@ -656,6 +656,9 @@ public static int graphicsPixelFillrate [FreeFunction("ScriptingGraphicsCaps::IsFormatSupported")] extern public static bool IsFormatSupported(GraphicsFormat format, FormatUsage usage); + [FreeFunction("ScriptingGraphicsCaps::GetCompatibleFormat")] + extern public static GraphicsFormat GetCompatibleFormat(GraphicsFormat format, FormatUsage usage); + [FreeFunction("ScriptingGraphicsCaps::GetGraphicsFormat")] extern public static GraphicsFormat GetGraphicsFormat(DefaultFormat format); } From c4c8bac93006571927190e0b458a72e21fb05cd0 Mon Sep 17 00:00:00 2001 From: Unity Technologies Date: Mon, 28 Jan 2019 15:21:41 +0000 Subject: [PATCH 02/26] Unity 2019.1.0b1 C# reference source code --- .../SpriteFrameModule/SpriteFrameModule.cs | 5 +- .../MinMaxCurveEditorWindow.cs | 3 ++ Editor/Mono/ConsoleWindow.cs | 2 +- Editor/Mono/EditorGUI.cs | 8 +-- Editor/Mono/GUI/AnimatedValues.cs | 2 + Editor/Mono/GUI/AppStatusBar.cs | 4 +- Editor/Mono/GameObjectUtility.bindings.cs | 6 +++ Editor/Mono/Inspector/Editor.cs | 3 +- Editor/Mono/Inspector/EditorDragging.cs | 47 +++++++++++++++-- Editor/Mono/Inspector/GameObjectInspector.cs | 6 +++ Editor/Mono/Inspector/InspectorWindow.cs | 25 ++------- .../Inspector/MinMaxCurvePropertyDrawer.cs | 11 ++-- .../ParticleSystemForceFieldInspector.cs | 30 ++++++----- Editor/Mono/Inspector/RendererEditorBase.cs | 2 +- Editor/Mono/PlayerSettingsSwitch.bindings.cs | 24 +++++++++ Editor/Mono/Prefabs/PrefabUtility.cs | 10 +++- Editor/Mono/SceneView/SceneView.cs | 4 ++ Editor/Mono/SceneView/SceneViewMotion.cs | 37 ++++++------- .../Scripting/Compilers/ScriptCompilerBase.cs | 2 +- .../ScriptCompilation/AssemblyBuilder.cs | 9 ++++ .../CSharpNamespaceParser.cs | 2 +- .../ScriptCompilation/EditorBuildRules.cs | 3 ++ .../ScriptCompilation/EditorCompilation.cs | 32 ++++++++++-- Editor/Mono/ShaderUtil.bindings.cs | 9 ++++ .../Mono/SpriteEditor/SpriteEditorWindow.cs | 14 ++--- .../UIElements/Controls/TextValueField.cs | 6 +-- .../SolutionSynchronizer.cs | 1 + Modules/Input/Private/Input.cs | 33 +++++++++--- .../Managed/ParticleSystemEnums.cs | 3 +- .../Managed/ParticleSystemStructs.cs | 24 ++++----- .../ScriptBindings/ParticleSystem.bindings.cs | 6 +-- .../CollisionModuleUI.cs | 4 +- .../ExternalForcesModuleUI.cs | 7 +-- .../ParticleSystemModules/RendererModuleUI.cs | 10 ++-- .../ParticleSystemModules/ShapeModuleUI.cs | 52 +++++++++++++------ .../ShortcutManagerEditor/BindingValidator.cs | 8 +++ .../DeleteShortcutProfileWindow.cs | 1 - .../ShortcutManagerEditor/KeyCombination.cs | 1 + Modules/ShortcutManagerEditor/PromptWindow.cs | 3 +- .../ShortcutManagerWindowView.cs | 30 ++++++++--- .../ShortcutManagerWindowViewController.cs | 11 ++-- .../Editor/Managed/Grid/GridPaintingState.cs | 18 +++++-- .../Editor/Managed/Grid/TileDragAndDrop.cs | 21 ++------ .../UIElements/Controls/KeyboardTextEditor.cs | 11 +++- Modules/UIElements/Controls/TextField.cs | 48 ++++++++++++++--- .../UIElements/Controls/TextInputFieldBase.cs | 50 +++++++++++++----- .../Events/CommandEventDispatchingStrategy.cs | 8 ++- Modules/UIElements/Events/EventBase.cs | 10 +++- .../Events/IEventDispatchingStrategy.cs | 15 +++--- .../KeyboardEventDispatchingStrategy.cs | 4 +- .../Events/MouseCaptureDispatchingStrategy.cs | 5 +- Modules/UIElements/IMGUIContainer.cs | 23 ++++++-- Modules/UIElements/ScrollView.cs | 2 +- .../ScriptBindings/MediaComponent.bindings.cs | 32 ++++++++++++ .../VideoEditor/Editor/VideoPlayerEditor.cs | 7 --- README.md | 2 +- 56 files changed, 527 insertions(+), 229 deletions(-) diff --git a/Editor/Mono/2D/SpriteEditorModule/SpriteFrameModule/SpriteFrameModule.cs b/Editor/Mono/2D/SpriteEditorModule/SpriteFrameModule/SpriteFrameModule.cs index bb333c5ce9..b288ecf72a 100644 --- a/Editor/Mono/2D/SpriteEditorModule/SpriteFrameModule/SpriteFrameModule.cs +++ b/Editor/Mono/2D/SpriteEditorModule/SpriteFrameModule/SpriteFrameModule.cs @@ -268,8 +268,6 @@ UnityTexture2D GetTextureToSlice() return readableTexture; // we want to slice based on the original texture slice. Upscale the imported texture var texture = UnityEditor.SpriteUtility.CreateTemporaryDuplicate(readableTexture, width, height); - if (texture != null) - texture.filterMode = texture.filterMode; return texture; } @@ -303,7 +301,7 @@ public void ScaleSpriteRect(Rect r) public void TrimAlpha() { - var texture = m_TextureDataProvider.GetReadableTexture2D(); + var texture = GetTextureToSlice(); if (texture == null) return; @@ -346,6 +344,7 @@ public void TrimAlpha() spriteEditor.SetDataModified(); selected.rect = rect; + PopulateSpriteFrameInspectorField(); } } diff --git a/Editor/Mono/Animation/AnimationWindow/MinMaxCurveEditorWindow.cs b/Editor/Mono/Animation/AnimationWindow/MinMaxCurveEditorWindow.cs index 73964221de..a4c7c7ac65 100644 --- a/Editor/Mono/Animation/AnimationWindow/MinMaxCurveEditorWindow.cs +++ b/Editor/Mono/Animation/AnimationWindow/MinMaxCurveEditorWindow.cs @@ -49,6 +49,8 @@ public static MinMaxCurveEditorWindow instance public AnimationCurve minCurve { get { return m_MinCurve; } } public AnimationCurve maxCurve { get { return m_MaxCurve; } } + public static string xAxisLabel { get; set; } = "time"; + public static bool visible { get { return s_SharedMinMaxCurveEditor != null; } @@ -68,6 +70,7 @@ void Init(CurveEditorSettings settings) m_CurveEditor.settings.rectangleToolFlags = CurveEditorSettings.RectangleToolFlags.MiniRectangleTool; m_CurveEditor.settings.undoRedoSelection = true; m_CurveEditor.settings.showWrapperPopups = true; + m_CurveEditor.settings.xAxisLabel = xAxisLabel; UpdateRegionDomain(); // For each of horizontal and vertical axis, if we have a finite range for that axis, use that range, diff --git a/Editor/Mono/ConsoleWindow.cs b/Editor/Mono/ConsoleWindow.cs index 232dc0085a..7373ceb417 100644 --- a/Editor/Mono/ConsoleWindow.cs +++ b/Editor/Mono/ConsoleWindow.cs @@ -807,7 +807,7 @@ private static string StacktraceWithHyperlinks(string stacktraceText) { StringBuilder textWithHyperlinks = new StringBuilder(); var lines = stacktraceText.Split(new string[] {"\n"}, StringSplitOptions.None); - for (int i = 0; i < lines[i].Length; ++i) + for (int i = 0; i < lines.Length; ++i) { string textBeforeFilePath = ") (at "; int filePathIndex = lines[i].IndexOf(textBeforeFilePath, StringComparison.Ordinal); diff --git a/Editor/Mono/EditorGUI.cs b/Editor/Mono/EditorGUI.cs index e1ff1b1ffd..3296bbe42d 100644 --- a/Editor/Mono/EditorGUI.cs +++ b/Editor/Mono/EditorGUI.cs @@ -4312,6 +4312,8 @@ public static Color ColorField(Rect position, GUIContent label, Color value, boo return DoColorField(PrefixLabel(position, id, label), id, value, showEyedropper, showAlpha, hdr); } + const float kEyedropperSize = 20f; + private static Color DoColorField(Rect position, int id, Color value, bool showEyedropper, bool showAlpha, bool hdr) { Event evt = Event.current; @@ -4319,13 +4321,14 @@ private static Color DoColorField(Rect position, int id, Color value, bool showE Color origColor = value; value = showMixedValue ? Color.white : value; bool hovered = position.Contains(evt.mousePosition); + bool hoveredEyedropper = new Rect(position.x + position.width - kEyedropperSize, position.y, kEyedropperSize, position.height).Contains(evt.mousePosition); switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (showEyedropper) { - position.width -= 20; + hovered ^= hoveredEyedropper; } if (hovered) @@ -4374,8 +4377,7 @@ private static Color DoColorField(Rect position, int id, Color value, bool showE if (showEyedropper) { - position.width += 20; - if (hovered) + if (hoveredEyedropper) { GUIUtility.keyboardControl = id; EyeDropper.Start(GUIView.current); diff --git a/Editor/Mono/GUI/AnimatedValues.cs b/Editor/Mono/GUI/AnimatedValues.cs index d938c4a44c..2811aa5c6c 100644 --- a/Editor/Mono/GUI/AnimatedValues.cs +++ b/Editor/Mono/GUI/AnimatedValues.cs @@ -11,6 +11,8 @@ namespace UnityEditor.AnimatedValues public abstract class BaseAnimValue { T m_Start; + + [SerializeField] T m_Target; double m_LastTime; diff --git a/Editor/Mono/GUI/AppStatusBar.cs b/Editor/Mono/GUI/AppStatusBar.cs index 9fa8036c83..f8ff66f043 100644 --- a/Editor/Mono/GUI/AppStatusBar.cs +++ b/Editor/Mono/GUI/AppStatusBar.cs @@ -60,7 +60,7 @@ protected override void OldOnGUI() const int statusWheelWidth = 24; const int progressBarStatusWheelSpacing = 3; const int progressBarWidth = 185; - const int lightingBakeModeBarWidth = 80; + const int lightingBakeModeBarWidth = 140; const int barHeight = 19; ConsoleWindow.LoadIcons(); @@ -177,7 +177,7 @@ private string GetBakeModeString() if (!showBakeMode) return ""; - return "Auto Bake " + (Lightmapping.giWorkflowMode == Lightmapping.GIWorkflowMode.Iterative ? "On" : "Off"); + return "Auto Generate Lighting " + (Lightmapping.giWorkflowMode == Lightmapping.GIWorkflowMode.Iterative ? "On" : "Off"); } } } //namespace diff --git a/Editor/Mono/GameObjectUtility.bindings.cs b/Editor/Mono/GameObjectUtility.bindings.cs index cea5470335..488a5471ad 100644 --- a/Editor/Mono/GameObjectUtility.bindings.cs +++ b/Editor/Mono/GameObjectUtility.bindings.cs @@ -96,6 +96,12 @@ private static void SetLayerRecursively(GameObject go, int layer) SetLayerRecursively(t.GetChild(i).gameObject, layer); } + [FreeFunction] + public static extern int GetMonoBehavioursWithMissingScriptCount(GameObject go); + + [FreeFunction] + public static extern int RemoveMonoBehavioursWithMissingScript(GameObject go); + [System.Obsolete("GetNavMeshArea instead.")] public static int GetNavMeshLayer(GameObject go) { diff --git a/Editor/Mono/Inspector/Editor.cs b/Editor/Mono/Inspector/Editor.cs index 510bdef1a3..0440473219 100644 --- a/Editor/Mono/Inspector/Editor.cs +++ b/Editor/Mono/Inspector/Editor.cs @@ -581,7 +581,8 @@ internal virtual void OnForceReloadInspector() // Need to make sure internal target list PPtr have been updated from a native memory // When assets are reloaded they are destroyed and recreated and the managed list does not get updated // The m_SerializedObject is a native object thus its targetObjects is a native memory PPtr list which have the new PPtr ids. - InternalSetTargets(m_SerializedObject.targetObjects); + if (m_SerializedObject.targetObjects != null && m_SerializedObject.targetObjects[0] != null) + InternalSetTargets(m_SerializedObject.targetObjects); } } diff --git a/Editor/Mono/Inspector/EditorDragging.cs b/Editor/Mono/Inspector/EditorDragging.cs index 2d7f10ee01..7bf97e9ff7 100644 --- a/Editor/Mono/Inspector/EditorDragging.cs +++ b/Editor/Mono/Inspector/EditorDragging.cs @@ -51,31 +51,62 @@ public void HandleDraggingToEditor(Editor[] editors, int editorIndex, Rect dragR HandleEditorDragging(editors, editorIndex, targetRect, markerY, false); } + int m_BottomAreaDropIndex = -1; + Rect m_BottomArea; + public void HandleDraggingInBottomArea(Editor[] editors, Rect bottomRect, Rect contentRect) { + HandleNativeDragDropInBottomArea(editors, bottomRect); + if (m_LastIndex >= 0 && m_LastIndex < editors.Length) { m_BottomArea = bottomRect; + m_BottomAreaDropIndex = m_LastIndex; HandleEditorDragging(editors, m_LastIndex, bottomRect, contentRect.yMax, true); } else { + m_BottomAreaDropIndex = -1; m_BottomArea = Rect.zero; } } - Rect m_BottomArea; - - internal void HandleDragPerformInBottomArea(Editor[] editors, Rect targetRect) + internal void HandleDragPerformInBottomArea(Editor[] editors, Rect bottomRect, Rect targetRect) { + HandleNativeDragDropInBottomArea(editors, bottomRect); + if (m_LastIndex >= 0 && m_LastIndex < editors.Length) { HandleEditorDragging(editors, m_LastIndex, GetTargetRect(targetRect), targetRect.yMax, true); } + m_BottomAreaDropIndex = -1; m_BottomArea = Rect.zero; } + void HandleNativeDragDropInBottomArea(Editor[] editors, Rect rect) + { + if (!DraggingOverRect(rect)) + { + return; + } + + Editor editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(editors); + if (editor == null) + { + return; + } + + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(editor.targets, Event.current.type == EventType.DragPerform); + + if (Event.current.type == EventType.DragPerform) + { + DragAndDrop.AcceptDrag(); + m_TargetIndex = -1; + GUIUtility.ExitGUI(); + } + } + void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, float markerY, bool bottomTarget) { var evt = Event.current; @@ -102,6 +133,7 @@ void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, fl DragAndDrop.SetGenericData(k_DraggingModeKey, draggingMode); } + if (draggingMode.Value != DraggingMode.NotApplicable) { if (bottomTarget) @@ -187,10 +219,10 @@ void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, fl break; case EventType.Repaint: - if (m_TargetIndex != -1 && + if (m_TargetIndex != -1 && editorIndex == m_TargetIndex && (targetRect.Contains(evt.mousePosition) || m_BottomArea.Contains(GUIClip.UnclipToWindow(evt.mousePosition)) && - editorIndex == editors.Length - 1)) + m_BottomAreaDropIndex == editors.Length - 1)) { Styles.insertionMarker.Draw(GetMarkerRect(targetRect, markerY, m_TargetAbove), false, false, false, false); } @@ -198,6 +230,11 @@ void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, fl } } + static bool DraggingOverRect(Rect rect) + { + return (Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) && rect.Contains(Event.current.mousePosition); + } + void HandleDragPerformEvent(Editor[] editors, Event evt, ref int targetIndex) { if (targetIndex != -1) diff --git a/Editor/Mono/Inspector/GameObjectInspector.cs b/Editor/Mono/Inspector/GameObjectInspector.cs index 5ec350061f..571f5da44e 100644 --- a/Editor/Mono/Inspector/GameObjectInspector.cs +++ b/Editor/Mono/Inspector/GameObjectInspector.cs @@ -196,6 +196,12 @@ void OnDisable() m_PreviewCache = null; } + internal override void OnForceReloadInspector() + { + base.OnForceReloadInspector(); + CalculatePrefabStatus(); + } + void ClearPreviewCache() { foreach (var texture in m_PreviewCache.Values) diff --git a/Editor/Mono/Inspector/InspectorWindow.cs b/Editor/Mono/Inspector/InspectorWindow.cs index b14830cf88..922932a75d 100644 --- a/Editor/Mono/Inspector/InspectorWindow.cs +++ b/Editor/Mono/Inspector/InspectorWindow.cs @@ -657,9 +657,9 @@ private Rect DropRectangle get { return new Rect( - rootVisualElement.rect.x, - rootVisualElement.rect.y + editorsElement.rect.height, - rootVisualElement.rect.width, + editorsElement.rect.x, + editorsElement.rect.y + editorsElement.rect.height, + editorsElement.rect.width, rootVisualElement.rect.height - editorsElement.rect.height); } } @@ -696,7 +696,7 @@ void DragPerformInBottomArea(DragPerformEvent dragPerformedEvent) return; } - editorDragging.HandleDragPerformInBottomArea(tracker.activeEditors, lastChild.layout); + editorDragging.HandleDragPerformInBottomArea(tracker.activeEditors, DropRectangle, lastChild.layout); } protected bool m_FirstInitialize; @@ -1692,10 +1692,6 @@ internal bool ShouldCullEditor(Editor[] editors, int editorIndex) Object currentTarget = editors[editorIndex].target; - // Objects that should always be hidden - if (currentTarget is ParticleSystemRenderer) - return true; - // Hide regular AssetImporters (but not inherited types) if (currentTarget != null && currentTarget.GetType() == typeof(AssetImporter)) return true; @@ -1743,19 +1739,6 @@ void DrawSelectionPickerList() EditorGUIUtility.SetIconSize(oldSize); } - void HandleLastInteractedEditor(Rect componentRect, Editor editor) - { - if (editor != m_LastInteractedEditor && - Event.current.type == EventType.MouseDown && componentRect.Contains(Event.current.mousePosition)) - { - // Don't use the event because the editor might want to use it. - // But don't move the check down below the editor either, - // because we want to set the last interacted editor simultaneously. - m_LastInteractedEditor = editor; - Repaint(); - } - } - private void AddComponentButton(Editor[] editors) { Editor editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(editors); diff --git a/Editor/Mono/Inspector/MinMaxCurvePropertyDrawer.cs b/Editor/Mono/Inspector/MinMaxCurvePropertyDrawer.cs index 2cf6d612fc..876d18461b 100644 --- a/Editor/Mono/Inspector/MinMaxCurvePropertyDrawer.cs +++ b/Editor/Mono/Inspector/MinMaxCurvePropertyDrawer.cs @@ -22,6 +22,7 @@ class PropertyData } internal bool isNativeProperty { get; set; } + internal string xAxisLabel { get; set; } = "time"; // Its possible that the PropertyDrawer may be used to draw more than one MinMaxCurve property(arrays, lists) Dictionary m_PropertyDataPerPropertyPath = new Dictionary(); @@ -125,11 +126,11 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten break; case MinMaxCurveState.k_Curve: - DoMinMaxCurvesField(fieldRect, m_Property.curveMax.GetHashCode(), m_Property.curveMax, null, m_Property.curveMultiplier, s_Styles.curveColor, s_Styles.curveBackgroundColor); + DoMinMaxCurvesField(fieldRect, m_Property.curveMax.GetHashCode(), m_Property.curveMax, null, m_Property.curveMultiplier, s_Styles.curveColor, s_Styles.curveBackgroundColor, xAxisLabel); break; case MinMaxCurveState.k_TwoCurves: - DoMinMaxCurvesField(fieldRect, m_Property.curveMin.GetHashCode(), m_Property.curveMax, m_Property.curveMin, m_Property.curveMultiplier, s_Styles.curveColor, s_Styles.curveBackgroundColor); + DoMinMaxCurvesField(fieldRect, m_Property.curveMin.GetHashCode(), m_Property.curveMax, m_Property.curveMin, m_Property.curveMultiplier, s_Styles.curveColor, s_Styles.curveBackgroundColor, xAxisLabel); break; case MinMaxCurveState.k_TwoScalars: @@ -148,7 +149,7 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten } } - static void DoMinMaxCurvesField(Rect position, int id, SerializedProperty propertyMax, SerializedProperty propertyMin, SerializedProperty scalar, Color color, Color backgroundColor) + static void DoMinMaxCurvesField(Rect position, int id, SerializedProperty propertyMax, SerializedProperty propertyMin, SerializedProperty scalar, Color color, Color backgroundColor, string xLabel) { var evt = Event.current; @@ -159,6 +160,7 @@ static void DoMinMaxCurvesField(Rect position, int id, SerializedProperty proper s_CurveId = id; if (MinMaxCurveEditorWindow.visible) { + MinMaxCurveEditorWindow.xAxisLabel = xLabel; MinMaxCurveEditorWindow.SetCurves(propertyMax, propertyMin, scalar, color); MinMaxCurveEditorWindow.ShowPopup(GUIView.current); } @@ -167,6 +169,7 @@ static void DoMinMaxCurvesField(Rect position, int id, SerializedProperty proper { if (MinMaxCurveEditorWindow.visible && Event.current.type == EventType.Repaint) { + MinMaxCurveEditorWindow.xAxisLabel = xLabel; MinMaxCurveEditorWindow.SetCurves(propertyMax, propertyMin, scalar, color); MinMaxCurveEditorWindow.instance.Repaint(); } @@ -180,6 +183,7 @@ static void DoMinMaxCurvesField(Rect position, int id, SerializedProperty proper { s_CurveId = id; GUIUtility.keyboardControl = id; + MinMaxCurveEditorWindow.xAxisLabel = xLabel; MinMaxCurveEditorWindow.SetCurves(propertyMax, propertyMin, scalar, color); MinMaxCurveEditorWindow.ShowPopup(GUIView.current); evt.Use(); @@ -217,6 +221,7 @@ static void DoMinMaxCurvesField(Rect position, int id, SerializedProperty proper if (evt.MainActionKeyForControl(id)) { s_CurveId = id; + MinMaxCurveEditorWindow.xAxisLabel = xLabel; MinMaxCurveEditorWindow.SetCurves(propertyMax, propertyMin, scalar, color); MinMaxCurveEditorWindow.ShowPopup(GUIView.current); evt.Use(); diff --git a/Editor/Mono/Inspector/ParticleSystemForceFieldInspector.cs b/Editor/Mono/Inspector/ParticleSystemForceFieldInspector.cs index 5a696abe39..94530057fd 100644 --- a/Editor/Mono/Inspector/ParticleSystemForceFieldInspector.cs +++ b/Editor/Mono/Inspector/ParticleSystemForceFieldInspector.cs @@ -35,6 +35,8 @@ internal class ParticleSystemForceFieldInspector : Editor private static PropertyInfo s_GravityFocusProperty = typeof(ParticleSystemForceField).GetProperty("gravityFocus"); private static PropertyInfo s_LengthProperty = typeof(ParticleSystemForceField).GetProperty("length"); + private static readonly string s_UndoString = L10n.Tr("Modify {0}"); + private SerializedProperty m_Shape; private SerializedProperty m_StartRange; private SerializedProperty m_EndRange; @@ -122,15 +124,15 @@ void OnEnable() m_VectorFieldSpeed = serializedObject.FindProperty("m_Parameters.m_VectorFieldSpeedCurve"); m_VectorFieldAttraction = serializedObject.FindProperty("m_Parameters.m_VectorFieldAttractionCurve"); - m_DirectionDrawerX = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_DirectionDrawerY = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_DirectionDrawerZ = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_GravityDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_RotationSpeedDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_RotationAttractionDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_DragDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_VectorFieldSpeedDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; - m_VectorFieldAttractionDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true }; + m_DirectionDrawerX = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_DirectionDrawerY = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_DirectionDrawerZ = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_GravityDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_RotationSpeedDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_RotationAttractionDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_DragDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_VectorFieldSpeedDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; + m_VectorFieldAttractionDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" }; } static void DrawMinMaxCurveField(SerializedProperty property, MinMaxCurvePropertyDrawer drawer, GUIContent label) @@ -273,7 +275,7 @@ private static void DrawSphere(PropertyInfo radiusProp, ParticleSystemForceField s_SphereBoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(target, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); + Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name))); radiusProp.SetValue(target, s_SphereBoundsHandle.radius / multiplyByRadius, null); } } @@ -286,7 +288,7 @@ private static void DrawHemisphere(PropertyInfo radiusProp, ParticleSystemForceF float newRadius = Handles.DoSimpleRadiusHandle(Quaternion.Euler(-90, 0, 0), Vector3.zero, oldRadius, true); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(target, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); + Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name))); radiusProp.SetValue(target, newRadius / multiplyByRadius, null); } } @@ -306,7 +308,7 @@ private static void DrawCylinder(PropertyInfo radiusProp, PropertyInfo lengthPro s_SphereBoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(target, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); + Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name))); radiusProp.SetValue(target, s_SphereBoundsHandle.radius / multiplyByRadius, null); } } @@ -317,7 +319,7 @@ private static void DrawCylinder(PropertyInfo radiusProp, PropertyInfo lengthPro lengthHalf = Handles.SizeSlider(Vector3.zero, -Vector3.up, lengthHalf); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(target, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); + Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name))); lengthProp.SetValue(target, Mathf.Max(0.0f, lengthHalf * 2.0f), null); } @@ -339,7 +341,7 @@ private static void DrawBox(PropertyInfo extentProp, ParticleSystemForceField ta s_BoxBoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(target, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); + Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name))); extentProp.SetValue(target, s_BoxBoundsHandle.radius / multiplyByRadius, null); } } diff --git a/Editor/Mono/Inspector/RendererEditorBase.cs b/Editor/Mono/Inspector/RendererEditorBase.cs index 24cefa167b..f567240b5d 100644 --- a/Editor/Mono/Inspector/RendererEditorBase.cs +++ b/Editor/Mono/Inspector/RendererEditorBase.cs @@ -328,7 +328,7 @@ private static string[] defaultRenderingLayerNames private SerializedProperty m_RendererPriority; static GUIContent m_RenderingLayerMaskStyle = EditorGUIUtility.TrTextContent("Rendering Layer Mask", "Mask that can be used with SRP DrawRenderers command to filter renderers outside of the normal layering system."); - static GUIContent m_RendererPriorityStyle = EditorGUIUtility.TrTextContent("Transparency Priority", "Priority used for sorting objects on top of material render queue."); + static GUIContent m_RendererPriorityStyle = EditorGUIUtility.TrTextContent("Renderer Priority", "Sets the priority value that Unity uses to sort objects on top of the Material render queue."); protected Probes m_Probes; diff --git a/Editor/Mono/PlayerSettingsSwitch.bindings.cs b/Editor/Mono/PlayerSettingsSwitch.bindings.cs index 5519a6553d..37613967b1 100644 --- a/Editor/Mono/PlayerSettingsSwitch.bindings.cs +++ b/Editor/Mono/PlayerSettingsSwitch.bindings.cs @@ -148,6 +148,12 @@ extern public static int queueCommandMemory set; } + [StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)] + extern public static int defaultSwitchQueueCommandMemory { get; } + + [StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)] + extern public static int minimumSwitchQueueCommandMemory { get; } + [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern public static int queueControlMemory { @@ -157,6 +163,24 @@ extern public static int queueControlMemory set; } + [StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)] + extern public static int defaultSwitchQueueControlMemory { get; } + + [StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)] + extern public static int minimumSwitchQueueControlMemory { get; } + + [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] + extern public static int queueComputeMemory + { + [NativeMethod("GetSwitchQueueComputeMemory")] + get; + [NativeMethod("SetSwitchQueueComputeMemory")] + set; + } + + [StaticAccessor("PlayerSettings", StaticAccessorType.DoubleColon)] + extern public static int defaultSwitchQueueComputeMemory { get; } + // GPU Pool information. [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] extern public static int NVNShaderPoolsGranularity diff --git a/Editor/Mono/Prefabs/PrefabUtility.cs b/Editor/Mono/Prefabs/PrefabUtility.cs index fba53d5971..c670ce24a8 100644 --- a/Editor/Mono/Prefabs/PrefabUtility.cs +++ b/Editor/Mono/Prefabs/PrefabUtility.cs @@ -324,12 +324,11 @@ public static void RevertPrefabInstance(GameObject instanceRoot, InteractionMode if (action == InteractionMode.UserAction) { + RegisterNewObjects(prefabInstanceRoot, hierarchy, actionName); if (isDisconnected) { Undo.RegisterCreatedObjectUndo(GetPrefabInstanceHandle(prefabInstanceRoot), actionName); } - - RegisterNewObjects(prefabInstanceRoot, hierarchy, actionName); } } @@ -340,6 +339,7 @@ public static void ApplyPrefabInstance(GameObject instanceRoot, InteractionMode ThrowExceptionIfNotValidNonPersistentPrefabInstanceObject(instanceRoot); GameObject prefabInstanceRoot = GetOutermostPrefabInstanceRoot(instanceRoot); + var isDisconnected = GetPrefabInstanceHandle(prefabInstanceRoot) == null; var actionName = "Apply instance to prefab"; Object correspondingSourceObject = GetCorrespondingObjectFromSource(prefabInstanceRoot); @@ -359,6 +359,12 @@ public static void ApplyPrefabInstance(GameObject instanceRoot, InteractionMode if (action == InteractionMode.UserAction) { RegisterNewObjects(correspondingSourceObject as GameObject, prefabHierarchy, actionName); // handles created objects + if (isDisconnected) + { + var prefabInstanceHandle = GetPrefabInstanceHandle(prefabInstanceRoot); + Assert.IsNotNull(prefabInstanceHandle); + Undo.RegisterCreatedObjectUndo(prefabInstanceHandle, actionName); + } } Analytics.SendApplyEvent( diff --git a/Editor/Mono/SceneView/SceneView.cs b/Editor/Mono/SceneView/SceneView.cs index 1e1bf2ba23..2a0ba82620 100644 --- a/Editor/Mono/SceneView/SceneView.cs +++ b/Editor/Mono/SceneView/SceneView.cs @@ -1637,6 +1637,9 @@ private void DoDrawCamera(Rect windowSpaceCameraRect, Rect groupSpaceCameraRect, if (!m_Camera.gameObject.activeInHierarchy) return; + bool oldAsync = ShaderUtil.allowAsyncCompilation; + ShaderUtil.allowAsyncCompilation = true; + DrawGridParameters gridParam = grid.PrepareGridRender(camera, pivot, m_Rotation.target, size, m_Ortho.target, drawGlobalGrid); Event evt = Event.current; @@ -1668,6 +1671,7 @@ private void DoDrawCamera(Rect windowSpaceCameraRect, Rect groupSpaceCameraRect, Handles.DrawCameraStep1(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode, gridParam, drawGizmos); DrawRenderModeOverlay(groupSpaceCameraRect); } + ShaderUtil.allowAsyncCompilation = oldAsync; } void RenderFilteredScene(Rect groupSpaceCameraRect) diff --git a/Editor/Mono/SceneView/SceneViewMotion.cs b/Editor/Mono/SceneView/SceneViewMotion.cs index fa96dc63b5..56cb4dd13b 100644 --- a/Editor/Mono/SceneView/SceneViewMotion.cs +++ b/Editor/Mono/SceneView/SceneViewMotion.cs @@ -17,6 +17,8 @@ internal static class SceneViewMotion static SceneView s_SceneView; static Vector3 s_Motion; static float k_FlySpeed = 9f; + static float s_FlySpeedTarget = 0f; + const float k_FlySpeedAcceleration = 1.8f; const float k_DefaultFpsEaseDuration = .4f; static float s_StartZoom = 0f, s_ZoomSpeed = 0f; static float s_TotalMotion = 0f; @@ -91,6 +93,9 @@ public static void DoViewTool(SceneView view) if (inputSamplingScope.currentlyMoving) view.viewIsLockedToObject = false; + if (inputSamplingScope.inputVectorChanged) + s_FlySpeedTarget = 0f; + s_Motion = inputSamplingScope.currentInputVector; } @@ -125,25 +130,23 @@ public static void DoViewTool(SceneView view) static Vector3 GetMovementDirection() { s_Moving = s_Motion.sqrMagnitude > 0f; - + var deltaTime = CameraFlyModeContext.deltaTime; var speedModifier = s_SceneView.sceneViewCameraSettings.speed; if (Event.current.shift) speedModifier *= 5f; - if (movementEasingEnabled) - { - s_FlySpeed.target = s_Moving ? s_Motion.normalized * k_FlySpeed * speedModifier : Vector3.zero; - } + if (s_Moving) + s_FlySpeedTarget = s_FlySpeedTarget < Mathf.Epsilon ? k_FlySpeed : s_FlySpeedTarget * Mathf.Pow(k_FlySpeedAcceleration, deltaTime); else - { - if (!s_Moving) - return s_FlySpeed.value = Vector3.zero; + s_FlySpeedTarget = 0f; - s_FlySpeed.value = s_Motion.normalized * speedModifier * k_FlySpeed; - } + if (movementEasingEnabled) + s_FlySpeed.target = s_Motion.normalized * s_FlySpeedTarget * speedModifier; + else + s_FlySpeed.value = s_Motion.normalized * speedModifier * s_FlySpeedTarget; - return s_FlySpeed.value * CameraFlyModeContext.deltaTime; + return s_FlySpeed.value * deltaTime; } private static void HandleMouseDown(SceneView view, int id, int button) @@ -420,13 +423,11 @@ private static void HandleScrollWheel(SceneView view, bool zoomTowardsCenter) else if (relativeDelta < 0 && relativeDelta > -deltaCutoff) relativeDelta = -deltaCutoff; - targetSize = movementEasingEnabled - ? view.targetSize + relativeDelta - : view.size + relativeDelta; + targetSize = view.size + relativeDelta; } else { - targetSize = Mathf.Abs(movementEasingEnabled ? view.targetSize : view.size) * (zoomDelta * .015f + 1.0f); + targetSize = Mathf.Abs(view.size) * (zoomDelta * .015f + 1.0f); } var initialDistance = view.cameraDistance; @@ -434,11 +435,7 @@ private static void HandleScrollWheel(SceneView view, bool zoomTowardsCenter) if (!(float.IsNaN(targetSize) || float.IsInfinity(targetSize))) { targetSize = Mathf.Min(SceneView.k_MaxSceneViewSize, targetSize); - - if (movementEasingEnabled) - view.targetSize = targetSize; - else - view.size = targetSize; + view.size = targetSize; } if (!zoomTowardsCenter && Mathf.Abs(view.cameraDistance) < 1.0e7f) diff --git a/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs b/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs index 4f8aefa6b6..e3c94662f2 100644 --- a/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs +++ b/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs @@ -426,7 +426,7 @@ public virtual CompilerMessage[] GetCompilerMessages() ).ToArray(); } - protected bool CompilationHadFailure() + internal bool CompilationHadFailure() { return (process.ExitCode != 0); } diff --git a/Editor/Mono/Scripting/ScriptCompilation/AssemblyBuilder.cs b/Editor/Mono/Scripting/ScriptCompilation/AssemblyBuilder.cs index d2273ecb81..060e9b77ea 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/AssemblyBuilder.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/AssemblyBuilder.cs @@ -23,6 +23,13 @@ public enum AssemblyBuilderFlags DevelopmentBuild = 2, }; + [Flags] + public enum ReferencesOptions + { + None = 0, + UseEngineModules = 1 + } + public class AssemblyBuilder { public event Action buildStarted; @@ -34,6 +41,7 @@ public class AssemblyBuilder public string[] additionalReferences { get; set; } public string[] excludeReferences { get; set; } public ScriptCompilerOptions compilerOptions { get; set; } + public ReferencesOptions referencesOptions { get; set; } public AssemblyBuilderFlags flags { get; set; } public BuildTargetGroup buildTargetGroup { get; set; } @@ -71,6 +79,7 @@ public AssemblyBuilder(string assemblyPath, params string[] scriptPaths) compilerOptions = new ScriptCompilerOptions(); flags = AssemblyBuilderFlags.None; + referencesOptions = ReferencesOptions.None; buildTargetGroup = EditorUserBuildSettings.activeBuildTargetGroup; buildTarget = EditorUserBuildSettings.activeBuildTarget; } diff --git a/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs b/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs index 408611723a..39cb9c96be 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs @@ -41,11 +41,11 @@ public static string GetNamespace(string sourceCode, string className, params st s_ClassName = className; sourceCode = k_NewlineRegex.Replace(sourceCode, "\n"); + sourceCode = k_SingleQuote.Replace(sourceCode, ""); sourceCode = k_Strings.Replace(sourceCode, ""); sourceCode = k_BlockComments.Replace(sourceCode, ""); sourceCode = k_LineComments.Replace(sourceCode, "\n"); sourceCode = k_VerbatimStrings.Replace(sourceCode, ""); - sourceCode = k_SingleQuote.Replace(sourceCode, ""); try { sourceCode = RemoveUnusedDefines(sourceCode, defines.ToList()); diff --git a/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs b/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs index 4a74a69a16..a45f08fe17 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs @@ -393,6 +393,9 @@ public static ScriptAssembly[] GenerateChangedScriptAssemblies(GenerateChangedSc assemblySourceFiles.Add(AssetPath.Combine(args.ProjectDirectory, dirtySourceFile)); + if (targetAssembly.Language == null && targetAssembly.Type == TargetAssemblyType.Custom) + targetAssembly.Language = scriptLanguage; + // If there are mixed languages in a custom script folder, mark the assembly to not be compiled. if (scriptLanguage != targetAssembly.Language) args.NotCompiledTargetAssemblies.Add(targetAssembly); diff --git a/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs b/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs index a7cf2b1d28..636ffc4140 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs @@ -300,6 +300,9 @@ public void DirtyRemovedScript(string path) else { dirtyTargetAssemblies.Add(targetAssembly); + + // Add to changedAssemblies in case we delete the last script of an assembly and then do not get OnCompilationFinished callback + changedAssemblies.Add(targetAssembly.Filename); } } @@ -1837,6 +1840,18 @@ static AssemblyFlags ToAssemblyFlags(Compilation.AssemblyBuilderFlags assemblyBu return assemblyFlags; } + static EditorBuildRules.UnityReferencesOptions ToUnityReferencesOptions(ReferencesOptions options) + { + var result = EditorBuildRules.UnityReferencesOptions.ExcludeModules; + + if ((options & ReferencesOptions.UseEngineModules) == ReferencesOptions.UseEngineModules) + { + result = EditorBuildRules.UnityReferencesOptions.None; + } + + return result; + } + ScriptAssembly InitializeScriptAssemblyWithoutReferencesAndDefines(Compilation.AssemblyBuilder assemblyBuilder) { var scriptFiles = assemblyBuilder.scriptPaths.Select(p => AssetPath.Combine(projectDirectory, p)).ToArray(); @@ -1861,8 +1876,9 @@ public ScriptAssembly CreateScriptAssembly(Compilation.AssemblyBuilder assemblyB var scriptAssembly = InitializeScriptAssemblyWithoutReferencesAndDefines(assemblyBuilder); var options = ToEditorScriptCompilationOptions(assemblyBuilder.flags); + var referencesOptions = ToUnityReferencesOptions(assemblyBuilder.referencesOptions); - var references = GetAssemblyBuilderDefaultReferences(scriptAssembly, options); + var references = GetAssemblyBuilderDefaultReferences(scriptAssembly, options, referencesOptions); if (assemblyBuilder.additionalReferences != null && assemblyBuilder.additionalReferences.Length > 0) references = references.Concat(assemblyBuilder.additionalReferences).ToArray(); @@ -1881,12 +1897,13 @@ public ScriptAssembly CreateScriptAssembly(Compilation.AssemblyBuilder assemblyB return scriptAssembly; } - string[] GetAssemblyBuilderDefaultReferences(ScriptAssembly scriptAssembly, EditorScriptCompilationOptions options) + string[] GetAssemblyBuilderDefaultReferences(ScriptAssembly scriptAssembly, EditorScriptCompilationOptions options, EditorBuildRules.UnityReferencesOptions unityReferencesOptions) { bool buildingForEditor = (scriptAssembly.Flags & AssemblyFlags.EditorOnly) == AssemblyFlags.EditorOnly; var monolithicEngineAssemblyPath = InternalEditorUtility.GetMonolithicEngineAssemblyPath(); - var unityReferences = EditorBuildRules.GetUnityReferences(scriptAssembly, unityAssemblies, options, EditorBuildRules.UnityReferencesOptions.ExcludeModules); + + var unityReferences = EditorBuildRules.GetUnityReferences(scriptAssembly, unityAssemblies, options, unityReferencesOptions); var customReferences = EditorBuildRules.GetCompiledCustomAssembliesReferences(scriptAssembly, customTargetAssemblies, GetCompileScriptsOutputDirectory()); var precompiledReferences = EditorBuildRules.GetPrecompiledReferences(scriptAssembly, EditorBuildRules.TargetAssemblyType.Custom, options, EditorBuildRules.EditorCompatibility.CompatibleWithEditor, precompiledAssemblies); @@ -1894,7 +1911,10 @@ string[] GetAssemblyBuilderDefaultReferences(ScriptAssembly scriptAssembly, Edit string[] editorReferences = buildingForEditor ? ModuleUtils.GetAdditionalReferencesForUserScripts() : new string[0]; var references = new List(); - references.Add(monolithicEngineAssemblyPath); + + if (unityReferencesOptions == EditorBuildRules.UnityReferencesOptions.ExcludeModules) + references.Add(monolithicEngineAssemblyPath); + references.AddRange(unityReferences.Concat(customReferences).Concat(precompiledReferences).Concat(editorReferences).Concat(additionalReferences)); return references.ToArray(); @@ -1904,8 +1924,10 @@ public string[] GetAssemblyBuilderDefaultReferences(AssemblyBuilder assemblyBuil { var scriptAssembly = InitializeScriptAssemblyWithoutReferencesAndDefines(assemblyBuilder); var options = ToEditorScriptCompilationOptions(assemblyBuilder.flags); + var referencesOptions = ToUnityReferencesOptions(assemblyBuilder.referencesOptions); + - var references = GetAssemblyBuilderDefaultReferences(scriptAssembly, options); + var references = GetAssemblyBuilderDefaultReferences(scriptAssembly, options, referencesOptions); return references; } diff --git a/Editor/Mono/ShaderUtil.bindings.cs b/Editor/Mono/ShaderUtil.bindings.cs index b079936ea5..9dd99f385d 100644 --- a/Editor/Mono/ShaderUtil.bindings.cs +++ b/Editor/Mono/ShaderUtil.bindings.cs @@ -7,6 +7,7 @@ using UnityEditor.Rendering; using UnityEngine; using UnityEngine.Bindings; +using UnityEngine.Rendering; using UnityEngine.Scripting; using ShaderPlatform = UnityEngine.Rendering.GraphicsDeviceType; using TextureDimension = UnityEngine.Rendering.TextureDimension; @@ -92,6 +93,7 @@ public override int GetHashCode() [NativeHeader("Editor/Mono/ShaderUtil.bindings.h")] [NativeHeader("Editor/Src/ShaderData.h")] [NativeHeader("Editor/Src/ShaderMenu.h")] + [NativeHeader("Runtime/Shaders/GpuPrograms/GpuProgramManager.h")] public partial class ShaderUtil { public enum ShaderPropertyType @@ -263,6 +265,13 @@ public static void UpdateShaderAsset(Shader shader, string source) [FreeFunction] extern internal static int GetShaderActiveSubshaderIndex([NotNull] Shader shader); [FreeFunction] extern internal static int GetShaderSubshaderCount([NotNull] Shader shader); [FreeFunction] extern internal static int GetShaderTotalPassCount([NotNull] Shader shader, int subShaderIndex); + + extern public static bool anythingCompiling { get; } + extern public static bool allowAsyncCompilation { get; set; } + extern public static void SetAsyncCompilation([NotNull] CommandBuffer cmd, bool allow); + extern public static void RestoreAsyncCompilation([NotNull] CommandBuffer cmd); + extern public static bool IsPassCompiled([NotNull] Material material, int pass); + extern public static void CompilePass([NotNull] Material material, int pass, bool forceSync = false); } } diff --git a/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs b/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs index a196a4f862..7c4e0c920d 100644 --- a/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs +++ b/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs @@ -47,7 +47,6 @@ private class SpriteEditorWindowStyles private const float k_WarningMessageHeight = 40f; private const float k_ModuleListWidth = 90f; - public static SpriteEditorWindow s_Instance; public bool m_ResetOnNextRepaint; private List m_RectsCache; @@ -236,7 +235,6 @@ void OnEnable() { minSize = new Vector2(360, 200); titleContent = SpriteEditorWindowStyles.spriteEditorWindowTitle; - s_Instance = this; m_UndoSystem.RegisterUndoCallback(UndoRedoPerformed); EditorApplication.modifierKeysChanged += ModifierKeysChanged; @@ -318,7 +316,6 @@ private void OnDisable() EditorApplication.modifierKeysChanged -= ModifierKeysChanged; EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; EditorApplication.quitting -= OnEditorApplicationQuit; - s_Instance = null; if (m_OutlineTexture != null) { @@ -706,9 +703,6 @@ public void DoTextureReimport(string path) internal void SetupModule(int newModuleIndex) { - if (s_Instance == null) - return; - m_ModuleViewElement.Clear(); if (m_RegisteredModules.Count > newModuleIndex) { @@ -975,10 +969,12 @@ public VisualElement GetMainVisualContainer() static internal void OnTextureReimport(string path) { - if (s_Instance != null && s_Instance.m_SelectedAssetPath == path) + UnityEngine.Object[] wins = Resources.FindObjectsOfTypeAll(typeof(SpriteEditorWindow)); + SpriteEditorWindow win = wins.Length > 0 ? (EditorWindow)(wins[0]) as SpriteEditorWindow : null; + if (win != null && win.m_SelectedAssetPath == path) { - s_Instance.m_ResetOnNextRepaint = true; - s_Instance.Repaint(); + win.m_ResetOnNextRepaint = true; + win.Repaint(); } } diff --git a/Editor/Mono/UIElements/Controls/TextValueField.cs b/Editor/Mono/UIElements/Controls/TextValueField.cs index c5f1ff9a98..8cbe415b03 100644 --- a/Editor/Mono/UIElements/Controls/TextValueField.cs +++ b/Editor/Mono/UIElements/Controls/TextValueField.cs @@ -109,7 +109,7 @@ void UpdateValueFromText() internal override bool AcceptCharacter(char c) { - return c != 0 && allowedCharacters.IndexOf(c) != -1; + return base.AcceptCharacter(c) && c != 0 && allowedCharacters.IndexOf(c) != -1; } protected abstract string allowedCharacters { get; } @@ -145,8 +145,8 @@ protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) { KeyDownEvent kde = evt as KeyDownEvent; - if ((kde?.keyCode == KeyCode.KeypadEnter) || - (kde?.keyCode == KeyCode.Return)) + if ((kde?.character == 3) || // KeyCode.KeypadEnter + (kde?.character == '\n')) // KeyCode.Return { // Here we should update the value, but it will be done when the blur event will be handled... parent.Focus(); diff --git a/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs index 4fd1e0527d..b9e3d64df0 100644 --- a/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs +++ b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs @@ -60,6 +60,7 @@ enum Mode {"hlsl", ScriptingLanguage.None}, {"glslinc", ScriptingLanguage.None}, {"template", ScriptingLanguage.None}, + {"raytrace", ScriptingLanguage.None}, }; private static readonly string[] reimportSyncExtensions = new[] { ".dll", ".asmdef" }; diff --git a/Modules/Input/Private/Input.cs b/Modules/Input/Private/Input.cs index 4568696ce0..a04fee8cbb 100644 --- a/Modules/Input/Private/Input.cs +++ b/Modules/Input/Private/Input.cs @@ -11,9 +11,10 @@ namespace UnityEngineInternal.Input { using NativeBeforeUpdateCallback = System.Action; - using NativeUpdateCallback = System.Action; using NativeDeviceDiscoveredCallback = System.Action; + public unsafe delegate void NativeUpdateCallback(NativeInputUpdateType updateType, NativeInputEventBuffer* buffer); + // C# doesn't support multi-character literals, so we do it by hand here... public enum NativeInputEventType { @@ -24,8 +25,19 @@ public enum NativeInputEventType State = 0x53544154, Delta = 0x444C5441, } + // We pass this as a struct to make it less painful to change the OnUpdate() API if need be. + [StructLayout(LayoutKind.Explicit, Size = 20, Pack = 1)] + public unsafe struct NativeInputEventBuffer + { + // NOTE: Keep this as the first field in the struct. This avoids alignment/packing issues - [StructLayout(LayoutKind.Explicit, Size = 20)] + // on the C++ side due to the compiler wanting to align the 64bit pointer. + [FieldOffset(0)] public void* eventBuffer; + [FieldOffset(8)] public int eventCount; + [FieldOffset(12)] public int sizeInBytes; + [FieldOffset(16)] public int capacityInBytes; + } + [StructLayout(LayoutKind.Explicit, Size = 20, Pack = 1)] public struct NativeInputEvent { [FieldOffset(0)] public NativeInputEventType type; @@ -55,7 +67,6 @@ public enum NativeInputUpdateType } - ////REVIEW: have a notification where a device can tell the HLAPI that its configuration has changed? (like e.g. the surface of a pointer has changed dimensions) public partial class NativeInputSystem { public static NativeUpdateCallback onUpdate; @@ -88,11 +99,21 @@ internal static void NotifyBeforeUpdate(NativeInputUpdateType updateType) } [RequiredByNativeCode] - internal static void NotifyUpdate(NativeInputUpdateType updateType, int eventCount, IntPtr eventData) + internal static unsafe void NotifyUpdate(NativeInputUpdateType updateType, IntPtr eventBuffer) { NativeUpdateCallback callback = onUpdate; - if (callback != null) - callback(updateType, eventCount, eventData); + + var eventBufferPtr = (NativeInputEventBuffer*)eventBuffer.ToPointer(); + if (callback == null) + { + eventBufferPtr->eventCount = 0; + + eventBufferPtr->sizeInBytes = 0; + } + else + { + callback(updateType, eventBufferPtr); + } } [RequiredByNativeCode] diff --git a/Modules/ParticleSystem/Managed/ParticleSystemEnums.cs b/Modules/ParticleSystem/Managed/ParticleSystemEnums.cs index 1c300061c7..085e6f84db 100644 --- a/Modules/ParticleSystem/Managed/ParticleSystemEnums.cs +++ b/Modules/ParticleSystem/Managed/ParticleSystemEnums.cs @@ -363,7 +363,8 @@ public enum ParticleSystemRingBufferMode public enum ParticleSystemGameObjectFilter { LayerMask = 0, - List = 1 + List = 1, + LayerMaskAndList = 2 } // Supported force field types diff --git a/Modules/ParticleSystem/Managed/ParticleSystemStructs.cs b/Modules/ParticleSystem/Managed/ParticleSystemStructs.cs index d7697fbbcf..b524bfc0ef 100644 --- a/Modules/ParticleSystem/Managed/ParticleSystemStructs.cs +++ b/Modules/ParticleSystem/Managed/ParticleSystemStructs.cs @@ -264,18 +264,18 @@ public partial struct EmitParams public void ResetStartLifetime() { m_StartLifetimeSet = false; } public void ResetMeshIndex() { m_MeshIndexSet = false; } - [NativeName(Name = "particle")] private Particle m_Particle; - [NativeName(Name = "positionSet")] private bool m_PositionSet; - [NativeName(Name = "velocitySet")] private bool m_VelocitySet; - [NativeName(Name = "axisOfRotationSet")] private bool m_AxisOfRotationSet; - [NativeName(Name = "rotationSet")] private bool m_RotationSet; - [NativeName(Name = "rotationalSpeedSet")] private bool m_AngularVelocitySet; - [NativeName(Name = "startSizeSet")] private bool m_StartSizeSet; - [NativeName(Name = "startColorSet")] private bool m_StartColorSet; - [NativeName(Name = "randomSeedSet")] private bool m_RandomSeedSet; - [NativeName(Name = "startLifetimeSet")] private bool m_StartLifetimeSet; - [NativeName(Name = "meshIndexSet")] private bool m_MeshIndexSet; - [NativeName(Name = "applyShapeToPosition")] private bool m_ApplyShapeToPosition; + [NativeName("particle")] private Particle m_Particle; + [NativeName("positionSet")] private bool m_PositionSet; + [NativeName("velocitySet")] private bool m_VelocitySet; + [NativeName("axisOfRotationSet")] private bool m_AxisOfRotationSet; + [NativeName("rotationSet")] private bool m_RotationSet; + [NativeName("rotationalSpeedSet")] private bool m_AngularVelocitySet; + [NativeName("startSizeSet")] private bool m_StartSizeSet; + [NativeName("startColorSet")] private bool m_StartColorSet; + [NativeName("randomSeedSet")] private bool m_RandomSeedSet; + [NativeName("startLifetimeSet")] private bool m_StartLifetimeSet; + [NativeName("meshIndexSet")] private bool m_MeshIndexSet; + [NativeName("applyShapeToPosition")] private bool m_ApplyShapeToPosition; } } diff --git a/Modules/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs b/Modules/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs index f21bd991b6..c48c6a1df9 100644 --- a/Modules/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs +++ b/Modules/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs @@ -135,13 +135,13 @@ extern public bool proceduralSimulationSupported // Emission [RequiredByNativeCode] public void Emit(int count) { Emit_Internal(count); } - [NativeName(Name = "SyncJobs()->Emit")] + [NativeName("SyncJobs()->Emit")] extern private void Emit_Internal(int count); - [NativeName(Name = "SyncJobs()->EmitParticlesExternal")] + [NativeName("SyncJobs()->EmitParticlesExternal")] extern public void Emit(EmitParams emitParams, int count); - [NativeName(Name = "SyncJobs()->EmitParticleExternal")] + [NativeName("SyncJobs()->EmitParticleExternal")] extern private void EmitOld_Internal(ref ParticleSystem.Particle particle); // Fire a sub-emitter diff --git a/Modules/ParticleSystemEditor/ParticleSystemModules/CollisionModuleUI.cs b/Modules/ParticleSystemEditor/ParticleSystemModules/CollisionModuleUI.cs index 35f5a6006f..b6480ba960 100644 --- a/Modules/ParticleSystemEditor/ParticleSystemModules/CollisionModuleUI.cs +++ b/Modules/ParticleSystemEditor/ParticleSystemModules/CollisionModuleUI.cs @@ -51,6 +51,8 @@ enum PlaneVizType { Grid, Solid }; EditMode.SceneViewEditMode.ParticleSystemCollisionModulePlanesRotate }; + static readonly string s_UndoCollisionPlaneString = L10n.Tr("Modified Collision Plane Transform"); + class Texts { public GUIContent lifetimeLoss = EditorGUIUtility.TrTextContent("Lifetime Loss", "When particle collides, it will lose this fraction of its Start Lifetime"); @@ -473,7 +475,7 @@ private void CollisionPlanesSceneGUI() } if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(transform, "Modified Collision Plane Transform"); + Undo.RecordObject(transform, s_UndoCollisionPlaneString); transform.position = newPosition; transform.rotation = newRotation; ParticleSystemEditorUtils.PerformCompleteResimulation(); diff --git a/Modules/ParticleSystemEditor/ParticleSystemModules/ExternalForcesModuleUI.cs b/Modules/ParticleSystemEditor/ParticleSystemModules/ExternalForcesModuleUI.cs index e4305466f8..230e10d7ce 100644 --- a/Modules/ParticleSystemEditor/ParticleSystemModules/ExternalForcesModuleUI.cs +++ b/Modules/ParticleSystemEditor/ParticleSystemModules/ExternalForcesModuleUI.cs @@ -26,7 +26,8 @@ class Texts public GUIContent[] influenceFilters = new GUIContent[] { EditorGUIUtility.TrTextContent("Layer Mask"), - EditorGUIUtility.TrTextContent("List") + EditorGUIUtility.TrTextContent("List"), + EditorGUIUtility.TrTextContent("Layer Mask and List") }; } static Texts s_Texts; @@ -67,9 +68,9 @@ override public void OnInspectorGUI(InitialModuleUI initial) } else { - if (filter == ParticleSystemGameObjectFilter.LayerMask) + if (filter != ParticleSystemGameObjectFilter.List) GUILayerMask(s_Texts.influenceMask, m_InfluenceMask); - else + if (filter != ParticleSystemGameObjectFilter.LayerMask) m_InfluenceListView.DoLayoutList(); } } diff --git a/Modules/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs b/Modules/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs index 66562bbaec..e11a88e08a 100644 --- a/Modules/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs +++ b/Modules/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs @@ -315,13 +315,13 @@ override public void OnInspectorGUI(InitialModuleUI initial) { GUIPopup(s_Texts.space, m_RenderAlignment, s_Texts.spaces); } - - if (renderMode == RenderMode.Billboard) - GUIVector3Field(s_Texts.flip, m_Flip); - else - GUIVector3Field(s_Texts.flipMeshes, m_Flip); } + if (renderMode == RenderMode.Mesh) + GUIVector3Field(s_Texts.flipMeshes, m_Flip); + else + GUIVector3Field(s_Texts.flip, m_Flip); + if (renderMode == RenderMode.Billboard) GUIToggle(s_Texts.allowRoll, m_AllowRoll); diff --git a/Modules/ParticleSystemEditor/ParticleSystemModules/ShapeModuleUI.cs b/Modules/ParticleSystemEditor/ParticleSystemModules/ShapeModuleUI.cs index f0c4bc3488..334f925c28 100644 --- a/Modules/ParticleSystemEditor/ParticleSystemModules/ShapeModuleUI.cs +++ b/Modules/ParticleSystemEditor/ParticleSystemModules/ShapeModuleUI.cs @@ -164,6 +164,24 @@ class Texts public GUIContent rotation = EditorGUIUtility.TrTextContent("Rotation", "Rotate the emission shape."); public GUIContent scale = EditorGUIUtility.TrTextContent("Scale", "Scale the emission shape."); + public readonly string undoSphereThickness = L10n.Tr("Sphere Thickness Handle Change"); + public readonly string undoSphere = L10n.Tr("Sphere Handle Change"); + public readonly string undoCircleThickness = L10n.Tr("Circle Thickness Handle Change"); + public readonly string undoCircle = L10n.Tr("Circle Handle Change"); + public readonly string undoHemisphereThickness = L10n.Tr("Hemisphere Thickness Handle Change"); + public readonly string undoHemisphere = L10n.Tr("Hemisphere Handle Change"); + public readonly string undoConeThickness = L10n.Tr("Cone Thickness Handle Change"); + public readonly string undoCone = L10n.Tr("Cone Handle Change"); + public readonly string undoConeVolumeThickness = L10n.Tr("Cone Volume Thickness Handle Change"); + public readonly string undoConeVolume = L10n.Tr("Cone Volume Handle Change"); + public readonly string undoBox = L10n.Tr("Box Handle Change"); + public readonly string undoDonut = L10n.Tr("Donut Handle Change"); + public readonly string undoDonutRadiusThickness = L10n.Tr("Donut Radius Thickness Handle Change"); + public readonly string undoDonutRadius = L10n.Tr("Donut Radius Handle Change"); + public readonly string undoEdge = L10n.Tr("Edge Handle Change"); + public readonly string undoRectangle = L10n.Tr("Rectangle Handle Change"); + public readonly string undoTransform = L10n.Tr("Shape Transform Change"); + public GUIContent[] shapeTypes = new GUIContent[] { EditorGUIUtility.TrTextContent("Sphere"), @@ -670,7 +688,7 @@ override public void OnSceneViewGUI() float radiusThickness = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, shapeModule.radius * (1.0f - shapeModule.radiusThickness), false, shapeModule.arc, allowGizmoEditing); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Sphere Thickness Handle Change"); + Undo.RecordObject(ps, s_Texts.undoSphereThickness); shapeModule.radiusThickness = 1.0f - (radiusThickness / shapeModule.radius); } @@ -680,7 +698,7 @@ override public void OnSceneViewGUI() float radius = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, shapeModule.radius, false, shapeModule.arc, allowGizmoEditing); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Sphere Handle Change"); + Undo.RecordObject(ps, s_Texts.undoSphere); shapeModule.radius = radius; } @@ -704,7 +722,7 @@ override public void OnSceneViewGUI() if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Circle Thickness Handle Change"); + Undo.RecordObject(ps, s_Texts.undoCircleThickness); shapeModule.radiusThickness = 1.0f - (m_ArcHandle.radius / shapeModule.radius); } @@ -721,7 +739,7 @@ override public void OnSceneViewGUI() if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Circle Handle Change"); + Undo.RecordObject(ps, s_Texts.undoCircle); shapeModule.radius = m_ArcHandle.radius; shapeModule.arc = m_ArcHandle.angle; } @@ -738,7 +756,7 @@ override public void OnSceneViewGUI() float radiusThickness = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, shapeModule.radius * (1.0f - shapeModule.radiusThickness), true, shapeModule.arc, allowGizmoEditing); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Hemisphere Thickness Handle Change"); + Undo.RecordObject(ps, s_Texts.undoHemisphereThickness); shapeModule.radiusThickness = 1.0f - (radiusThickness / shapeModule.radius); } @@ -748,7 +766,7 @@ override public void OnSceneViewGUI() float radius = Handles.DoSimpleRadiusHandle(Quaternion.identity, Vector3.zero, shapeModule.radius, true, shapeModule.arc, allowGizmoEditing); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Hemisphere Handle Change"); + Undo.RecordObject(ps, s_Texts.undoHemisphere); shapeModule.radius = radius; } @@ -768,7 +786,7 @@ override public void OnSceneViewGUI() radiusThicknessAngleRange = Handles.ConeFrustrumHandle(Quaternion.identity, Vector3.zero, radiusThicknessAngleRange, Handles.ConeHandles.Radius & coneHandlesMask); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Cone Thickness Handle Change"); + Undo.RecordObject(ps, s_Texts.undoConeThickness); shapeModule.radiusThickness = 1.0f - (radiusThicknessAngleRange.x / shapeModule.radius); } @@ -779,7 +797,7 @@ override public void OnSceneViewGUI() radiusAngleRange = Handles.ConeFrustrumHandle(Quaternion.identity, Vector3.zero, radiusAngleRange, coneHandlesMask); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Cone Handle Change"); + Undo.RecordObject(ps, s_Texts.undoCone); shapeModule.radius = radiusAngleRange.x; shapeModule.angle = radiusAngleRange.y; mainModule.startSpeedMultiplier = radiusAngleRange.z; @@ -801,7 +819,7 @@ override public void OnSceneViewGUI() radiusThicknessAngleLength = Handles.ConeFrustrumHandle(Quaternion.identity, Vector3.zero, radiusThicknessAngleLength, Handles.ConeHandles.Radius & coneHandlesMask); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Cone Volume Thickness Handle Change"); + Undo.RecordObject(ps, s_Texts.undoConeVolumeThickness); shapeModule.radiusThickness = 1.0f - (radiusThicknessAngleLength.x / shapeModule.radius); } @@ -812,7 +830,7 @@ override public void OnSceneViewGUI() radiusAngleLength = Handles.ConeFrustrumHandle(Quaternion.identity, Vector3.zero, radiusAngleLength, coneHandlesMask); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Cone Volume Handle Change"); + Undo.RecordObject(ps, s_Texts.undoConeVolume); shapeModule.radius = radiusAngleLength.x; shapeModule.angle = radiusAngleLength.y; shapeModule.length = radiusAngleLength.z; @@ -833,7 +851,7 @@ override public void OnSceneViewGUI() if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Box Handle Change"); + Undo.RecordObject(ps, s_Texts.undoBox); shapeModule.scale = m_BoxBoundsHandle.size; } @@ -855,7 +873,7 @@ override public void OnSceneViewGUI() if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Donut Handle Change"); + Undo.RecordObject(ps, s_Texts.undoDonut); shapeModule.radius = m_ArcHandle.radius; shapeModule.arc = m_ArcHandle.angle; } @@ -897,7 +915,7 @@ override public void OnSceneViewGUI() m_SphereBoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Donut Radius Thickness Handle Change"); + Undo.RecordObject(ps, s_Texts.undoDonutRadiusThickness); shapeModule.radiusThickness = 1.0f - (m_SphereBoundsHandle.radius / shapeModule.donutRadius); } } @@ -914,7 +932,7 @@ override public void OnSceneViewGUI() m_SphereBoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Donut Radius Handle Change"); + Undo.RecordObject(ps, s_Texts.undoDonutRadius); shapeModule.donutRadius = m_SphereBoundsHandle.radius; } } @@ -929,7 +947,7 @@ override public void OnSceneViewGUI() float radius = Handles.DoSimpleEdgeHandle(Quaternion.identity, Vector3.zero, shapeModule.radius, allowGizmoEditing); if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Edge Handle Change"); + Undo.RecordObject(ps, s_Texts.undoEdge); shapeModule.radius = radius; } } @@ -958,7 +976,7 @@ override public void OnSceneViewGUI() if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Rectangle Handle Change"); + Undo.RecordObject(ps, s_Texts.undoRectangle); shapeModule.scale = new Vector3(m_BoxBoundsHandle.size.x, m_BoxBoundsHandle.size.y, 0.0f); } @@ -1011,7 +1029,7 @@ override public void OnSceneViewGUI() if (EditorGUI.EndChangeCheck()) { - Undo.RecordObject(ps, "Shape Transform Change"); + Undo.RecordObject(ps, s_Texts.undoTransform); shapeModule.position = position; shapeModule.rotation = rotation.eulerAngles; diff --git a/Modules/ShortcutManagerEditor/BindingValidator.cs b/Modules/ShortcutManagerEditor/BindingValidator.cs index 8758e9c39c..08e3cac47d 100644 --- a/Modules/ShortcutManagerEditor/BindingValidator.cs +++ b/Modules/ShortcutManagerEditor/BindingValidator.cs @@ -21,6 +21,14 @@ class BindingValidator : IBindingValidator KeyCode.Escape, KeyCode.Return, KeyCode.CapsLock, + KeyCode.RightShift, + KeyCode.LeftShift, + KeyCode.RightAlt, + KeyCode.LeftAlt, + KeyCode.RightControl, + KeyCode.LeftControl, + KeyCode.RightCommand, + KeyCode.LeftCommand, }; public bool IsBindingValid(IEnumerable keyCombinations, out string invalidBindingMessage) diff --git a/Modules/ShortcutManagerEditor/DeleteShortcutProfileWindow.cs b/Modules/ShortcutManagerEditor/DeleteShortcutProfileWindow.cs index 7295cbb4c4..57d3ea7a1d 100644 --- a/Modules/ShortcutManagerEditor/DeleteShortcutProfileWindow.cs +++ b/Modules/ShortcutManagerEditor/DeleteShortcutProfileWindow.cs @@ -41,7 +41,6 @@ void OnEnable() // Load styles if (EditorGUIUtility.isProSkin) root.AddToClassList("isProSkin"); - root.AddStyleSheetPath("StyleSheets/ShortcutManager/Common.uss"); root.AddStyleSheetPath("StyleSheets/ShortcutManager/PromptWindow.uss"); // Find elements diff --git a/Modules/ShortcutManagerEditor/KeyCombination.cs b/Modules/ShortcutManagerEditor/KeyCombination.cs index ffad535df2..96d3a37e45 100644 --- a/Modules/ShortcutManagerEditor/KeyCombination.cs +++ b/Modules/ShortcutManagerEditor/KeyCombination.cs @@ -35,6 +35,7 @@ public struct KeyCombination : IEquatable { KeyCode.Delete, "DEL" }, { KeyCode.End, "END" }, { KeyCode.Tab, "TAB" }, + { KeyCode.Space, "SPACE"}, { KeyCode.F1, "F1" }, { KeyCode.F2, "F2" }, diff --git a/Modules/ShortcutManagerEditor/PromptWindow.cs b/Modules/ShortcutManagerEditor/PromptWindow.cs index 7d486f06fe..4024b12293 100644 --- a/Modules/ShortcutManagerEditor/PromptWindow.cs +++ b/Modules/ShortcutManagerEditor/PromptWindow.cs @@ -27,7 +27,7 @@ public static void Show(string title, string headerText, string messageText, str var promptWindow = GetWindow(true, title, true); // TODO: Ideally the window size should be fixed according to its contents - promptWindow.minSize = new Vector2(354, 157); + promptWindow.minSize = new Vector2(360, 180); promptWindow.m_HeaderTextElement.text = headerText; promptWindow.m_MessageTextElement.text = messageText; @@ -56,7 +56,6 @@ void OnEnable() // Load styles if (EditorGUIUtility.isProSkin) root.AddToClassList("isProSkin"); - root.AddStyleSheetPath("StyleSheets/ShortcutManager/Common.uss"); root.AddStyleSheetPath("StyleSheets/ShortcutManager/PromptWindow.uss"); // Find elements diff --git a/Modules/ShortcutManagerEditor/ShortcutManagerWindowView.cs b/Modules/ShortcutManagerEditor/ShortcutManagerWindowView.cs index 3aaf285858..d527890227 100644 --- a/Modules/ShortcutManagerEditor/ShortcutManagerWindowView.cs +++ b/Modules/ShortcutManagerEditor/ShortcutManagerWindowView.cs @@ -247,6 +247,8 @@ void CategorySelectionChanged(List selection) { Assert.AreEqual(1, selection.Count); + m_ShortcutsTable.selectedIndex = -1; + if (selection.Count == 0) m_ViewController.SetCategorySelected(null); else @@ -290,14 +292,14 @@ public void RefreshProfiles() void BuildProfileManagementRow(VisualElement header) { - m_ActiveProfileDropdownButton = header.Q("activeProfileDropdownButton"); + m_ActiveProfileDropdownButton = header.Q("activeProfileDropdownButtonText"); m_ActiveProfileDropdownButton.text = m_ViewController.activeProfile; - m_ActiveProfileDropdownButton.RegisterCallback(OnProfileContextMenuMouseDown); + m_ActiveProfileDropdownButton.AddToClassList(PopupField.textUssClassName); // Style active profile dropdown button as a popup field var activeProfileDropdownButton = header.Q("activeProfileDropdownButton"); - activeProfileDropdownButton.AddToClassList(PopupField.textUssClassName); activeProfileDropdownButton.AddToClassList(BasePopupField.inputUssClassName); + activeProfileDropdownButton.RegisterCallback(OnProfileContextMenuMouseDown); } void OnCreateProfileClicked() @@ -452,7 +454,8 @@ void BuildVisualElementHierarchyRoot() m_ShortcutsTable.Q().showVertical = true; m_ShortcutsTable.onSelectionChanged += ShortcutSelectionChanged; m_ShortcutsTable.onItemChosen += ShortcutTableEntryChosen; - m_ShortcutsTable.RegisterCallback(ShortcutTableRightClick); + m_ShortcutsTable.RegisterCallback(ShortcutTableRightClickDown); + m_ShortcutsTable.RegisterCallback(ShortcutTableRightClickUp); m_ShortcutsTable.RegisterCallback(ShortcutTableGeometryChanged); m_Root.AddToClassList("ShortcutManagerView"); @@ -560,7 +563,7 @@ void StartRebind(ShortcutEntry entry, VisualElement row) static void FocusElementDelayed(GeometryChangedEvent evt) { var element = (VisualElement)evt.target; - element.Focus(); + element.Q("unity-text-input").Focus(); element.UnregisterCallback(FocusElementDelayed); } @@ -667,7 +670,21 @@ void ShortcutSelectionChanged(List selection) } } - void ShortcutTableRightClick(MouseUpEvent evt) + void ShortcutTableRightClickDown(MouseDownEvent evt) + { + var slider = m_ShortcutsTable.Q(className: Scroller.verticalVariantUssClassName); + var clickedIndex = (int)((evt.localMousePosition.y + slider.value) / m_ShortcutsTable.itemHeight); + + if (evt.button != (int)MouseButton.RightMouse) + return; + + if (clickedIndex > m_ShortcutsTable.itemsSource.Count - 1) + return; + + m_ShortcutsTable.selectedIndex = clickedIndex; + } + + void ShortcutTableRightClickUp(MouseUpEvent evt) { if (evt.button != 1 || m_ViewController.selectedEntry == null) return; @@ -697,7 +714,6 @@ void OnMouseDownCategoryTable(MouseDownEvent evt) m_StartedDrag = false; var visualElement = ((VisualElement)evt.currentTarget); - visualElement.RegisterCallback(OnMouseMoveCategoryTable); visualElement.RegisterCallback(OnMouseLeaveWhileButtonDownCategoryTable); } diff --git a/Modules/ShortcutManagerEditor/ShortcutManagerWindowViewController.cs b/Modules/ShortcutManagerEditor/ShortcutManagerWindowViewController.cs index c626f70ccd..128129ccd9 100644 --- a/Modules/ShortcutManagerEditor/ShortcutManagerWindowViewController.cs +++ b/Modules/ShortcutManagerEditor/ShortcutManagerWindowViewController.cs @@ -543,6 +543,11 @@ void RebindEntry(ShortcutEntry entry, List keyCombination) public bool CanEntryBeAssignedToKey(KeyCode keyCode, EventModifiers eventModifier, ShortcutEntry entry) { + if (!m_BindingValidator.IsBindingValid(keyCode)) + { + return false; + } + var keycombination = KeyCombination.FromKeyboardInput(keyCode, eventModifier); List entries; if (m_KeyBindingRootToBoundEntries.TryGetValue(keycombination, out entries)) @@ -743,17 +748,17 @@ public static bool IsModifier(KeyCode code) bool IKeyBindingStateProvider.IsModifier(KeyCode code) { - return ShortcutManagerWindowViewController.IsModifier(code); + return IsModifier(code); } public bool IsReservedKey(KeyCode code) { - return !m_BindingValidator.IsBindingValid(code); + return !IsModifier(code) && !m_BindingValidator.IsBindingValid(code); } EventModifiers IKeyBindingStateProvider.ModifierFromKeyCode(KeyCode k) { - return ShortcutManagerWindowViewController.ModifierFromKeyCode(k); + return ModifierFromKeyCode(k); } public static EventModifiers ModifierFromKeyCode(KeyCode k) diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs index 94d11d0f1e..6d24927021 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs @@ -138,7 +138,7 @@ void OnDisable() private void OnSelectionChange() { - if (hasInterestedPainters && validTargets == null && ValidatePaintTarget(Selection.activeGameObject)) + if (hasInterestedPainters && ValidatePaintTarget(Selection.activeGameObject)) { scenePaintTarget = Selection.activeGameObject; } @@ -149,8 +149,18 @@ private void HierarchyChanged() if (hasInterestedPainters) { m_FlushPaintTargetCache = true; - if (validTargets == null || !validTargets.Contains(scenePaintTarget)) - AutoSelectPaintTarget(); + if (validTargets == null || validTargets.Length == 0 || !validTargets.Contains(scenePaintTarget)) + { + // case 1102618: Try to use current Selection as scene paint target if possible + if (Selection.activeGameObject != null && hasInterestedPainters && ValidatePaintTarget(Selection.activeGameObject)) + { + scenePaintTarget = Selection.activeGameObject; + } + else + { + AutoSelectPaintTarget(); + } + } } } @@ -280,7 +290,7 @@ public static bool ValidatePaintTarget(GameObject candidate) if (candidate == null || candidate.GetComponentInParent() == null && candidate.GetComponent() == null) return false; - if (validTargets != null && !validTargets.Contains(candidate)) + if (validTargets != null && validTargets.Length > 0 && !validTargets.Contains(candidate)) return false; return true; diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/TileDragAndDrop.cs b/Modules/TilemapEditor/Editor/Managed/Grid/TileDragAndDrop.cs index 3dd99fb13b..086ff9c75e 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/TileDragAndDrop.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/TileDragAndDrop.cs @@ -319,23 +319,10 @@ public static Vector2Int EstimateGridPixelSize(List sprites) if (sprites.Count == 1) return Vector2Int.FloorToInt(sprites[0].rect.size); - Vector2 min1 = GetMin(sprites, new Vector2(float.MinValue, float.MinValue)); - Vector2 min2 = GetMin(sprites, min1); - - Vector2Int result = Vector2Int.FloorToInt(min2 - min1); - result.x = Math.Max(Mathf.FloorToInt(sprites[0].rect.width), result.x); - result.y = Math.Max(Mathf.FloorToInt(sprites[0].rect.height), result.y); - - return result; - } - - static Vector2 GetMin(List sprites, Vector2 biggerThan) - { - var xSprites = sprites.FindAll(sprite => sprite.rect.xMin > biggerThan.x); - var ySprites = sprites.FindAll(sprite => sprite.texture.height - sprite.rect.yMax > biggerThan.y); - var xMin = xSprites.Count > 0 ? xSprites.Min(s => s.rect.xMin) : 0f; - var yMin = ySprites.Count > 0 ? ySprites.Min(s => s.texture.height - s.rect.yMax) : 0f; - return new Vector2(xMin, yMin); + return new Vector2Int( + Mathf.FloorToInt(sprites.Min(s => s.rect.width)), + Mathf.FloorToInt(sprites.Min(s => s.rect.height)) + ); } // Turn texture pixel position into integer grid position based on cell size diff --git a/Modules/UIElements/Controls/KeyboardTextEditor.cs b/Modules/UIElements/Controls/KeyboardTextEditor.cs index e3e1319f31..836c486457 100644 --- a/Modules/UIElements/Controls/KeyboardTextEditor.cs +++ b/Modules/UIElements/Controls/KeyboardTextEditor.cs @@ -217,7 +217,7 @@ void OnKeyDown(KeyDownEvent evt) else { // Ignore tab & shift-tab in text fields - if (evt.keyCode == KeyCode.Tab || evt.character == '\t') + if (!editorEngine.multiline && (evt.keyCode == KeyCode.Tab || evt.character == '\t')) return; evt.StopPropagation(); @@ -229,6 +229,13 @@ void OnKeyDown(KeyDownEvent evt) return; } + // When the newline character is sent, we have to check if the shift key is down also... + // In the multiline case, this is like a return on a single line + if (c == '\n' && editorEngine.multiline && evt.shiftKey) + { + return; + } + if (!textInputField.AcceptCharacter(c)) { return; @@ -236,7 +243,7 @@ void OnKeyDown(KeyDownEvent evt) // Simplest test: only allow the character if the display font supports it. Font font = editorEngine.style.font; - if (font != null && font.HasCharacter(c) || c == '\n') + if (font != null && font.HasCharacter(c) || c == '\n' || c == '\t') { // Input event editorEngine.Insert(c); diff --git a/Modules/UIElements/Controls/TextField.cs b/Modules/UIElements/Controls/TextField.cs index a2bb6a4dca..551a7cc9cd 100644 --- a/Modules/UIElements/Controls/TextField.cs +++ b/Modules/UIElements/Controls/TextField.cs @@ -14,8 +14,11 @@ public class TextField : TextInputBaseField // This property to alleviate the fact we have to cast all the time TextInput textInput => (TextInput)textInputBase; + // This is to save the value of the tabindex of the visual input to achieve the IMGUI behaviour of tabbing on multiline TextField. + int m_VisualInputTabIndex; + public new class UxmlFactory : UxmlFactory {} - public new class UxmlTraits : BaseFieldTraits + public new class UxmlTraits : TextInputBaseField.UxmlTraits { UxmlBoolAttributeDescription m_Multiline = new UxmlBoolAttributeDescription { name = "multiline" }; @@ -50,7 +53,7 @@ public TextField(int maxLength, bool multiline, bool isPasswordField, char maskC : this(null, maxLength, multiline, isPasswordField, maskChar) {} public TextField(string label) - : this(label, kMaxLengthNone, false, false, char.MinValue) {} + : this(label, kMaxLengthNone, false, false, kMaskCharDefault) {} public TextField(string label, int maxLength, bool multiline, bool isPasswordField, char maskChar) : base(label, maxLength, maskChar, new TextInput()) @@ -93,6 +96,32 @@ internal override void OnViewDataReady() text = rawValue; } + protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) + { + base.ExecuteDefaultActionAtTarget(evt); + + // The following code is to help achieve the following behaviour: + // On IMGUI, a TextArea "in edit mode" is accepting TAB, doing a Shift+Return will get out of the Edit mode + // and a TAB will allow the user to get to the next control... + // To mimic that behaviour in UIE, when in focused-non-edit-mode, we have to make sure the input is not "tabbable". + // So, each time, either the main TextField or the Label is receiving the focus, we remove the tabIndex on + // the input, and we put it back when the BlurEvent is received. + if (multiline) + { + if ((evt?.eventTypeId == FocusInEvent.TypeId() && evt?.leafTarget == this) || + (evt?.eventTypeId == FocusInEvent.TypeId() && evt?.leafTarget == labelElement)) + { + m_VisualInputTabIndex = visualInput.tabIndex; + visualInput.tabIndex = -1; + } + else if ((evt?.eventTypeId == BlurEvent.TypeId() && evt?.leafTarget == this) || + (evt?.eventTypeId == BlurEvent.TypeId() && evt?.leafTarget == labelElement)) + { + visualInput.tabIndex = m_VisualInputTabIndex; + } + } + } + class TextInput : TextInputBase { TextField parentTextField => (TextField)parent; @@ -178,7 +207,6 @@ internal override void DoRepaint(IStylePainter painter) protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) { base.ExecuteDefaultActionAtTarget(evt); - if (evt == null) { return; @@ -188,20 +216,26 @@ protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) { KeyDownEvent kde = evt as KeyDownEvent; - if (!parentTextField.isDelayed || (kde?.keyCode == KeyCode.KeypadEnter) || (kde?.keyCode == KeyCode.Return)) + if (!parentTextField.isDelayed || (!multiline && ((kde?.keyCode == KeyCode.KeypadEnter) || (kde?.keyCode == KeyCode.Return)))) { parentTextField.value = text; } if (multiline) { - if (((kde?.keyCode == KeyCode.KeypadEnter) && (kde?.shiftKey == true)) || - ((kde?.keyCode == KeyCode.Return) && (kde?.shiftKey == true))) + if (kde?.character == '\t') + { + kde?.StopPropagation(); + kde?.PreventDefault(); + } + else if (((kde?.character == 3) && (kde?.shiftKey == true)) || // KeyCode.KeypadEnter + ((kde?.character == '\n') && (kde?.shiftKey == true))) // KeyCode.Return { parent.Focus(); } } - else if ((kde?.keyCode == KeyCode.KeypadEnter) || (kde?.keyCode == KeyCode.Return)) + else if ((kde?.character == 3) || // KeyCode.KeypadEnter + (kde?.character == '\n')) // KeyCode.Return { parent.Focus(); } diff --git a/Modules/UIElements/Controls/TextInputFieldBase.cs b/Modules/UIElements/Controls/TextInputFieldBase.cs index 66f64d2298..dab8c36613 100644 --- a/Modules/UIElements/Controls/TextInputFieldBase.cs +++ b/Modules/UIElements/Controls/TextInputFieldBase.cs @@ -26,12 +26,13 @@ public abstract class TextInputBaseField : BaseField static CustomStyleProperty s_SelectionColorProperty = new CustomStyleProperty("--unity-selection-color"); static CustomStyleProperty s_CursorColorProperty = new CustomStyleProperty("--unity-cursor-color"); - public new class UxmlTraits : BaseField.UxmlTraits + public new class UxmlTraits : BaseFieldTraits { UxmlIntAttributeDescription m_MaxLength = new UxmlIntAttributeDescription { name = "max-length", obsoleteNames = new[] { "maxLength" }, defaultValue = kMaxLengthNone }; UxmlBoolAttributeDescription m_Password = new UxmlBoolAttributeDescription { name = "password" }; - UxmlStringAttributeDescription m_MaskCharacter = new UxmlStringAttributeDescription { name = "mask-character", obsoleteNames = new[] { "maskCharacter" }, defaultValue = "*" }; + UxmlStringAttributeDescription m_MaskCharacter = new UxmlStringAttributeDescription { name = "mask-character", obsoleteNames = new[] { "maskCharacter" }, defaultValue = kMaskCharDefault.ToString()}; UxmlStringAttributeDescription m_Text = new UxmlStringAttributeDescription { name = "text" }; + UxmlBoolAttributeDescription m_IsReadOnly = new UxmlBoolAttributeDescription { name = "readonly" }; public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { @@ -40,12 +41,13 @@ public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext var field = ((TextInputBaseField)ve); field.maxLength = m_MaxLength.GetValueFromBag(bag, cc); field.isPasswordField = m_Password.GetValueFromBag(bag, cc); + field.isReadOnly = m_IsReadOnly.GetValueFromBag(bag, cc); string maskCharacter = m_MaskCharacter.GetValueFromBag(bag, cc); if (maskCharacter != null && maskCharacter.Length > 0) { field.maskChar = maskCharacter[0]; } - ((ITextElement)field).text = m_Text.GetValueFromBag(bag, cc); + field.text = m_Text.GetValueFromBag(bag, cc); } } @@ -53,6 +55,7 @@ public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext protected TextInputBase textInputBase => m_TextInputBase; internal const int kMaxLengthNone = -1; + internal const char kMaskCharDefault = '*'; public new static readonly string ussClassName = "unity-base-text-field"; public new static readonly string labelUssClassName = ussClassName + "__label"; @@ -69,6 +72,12 @@ protected set } } + public bool isReadOnly + { + get { return m_TextInputBase.isReadOnly; } + set { m_TextInputBase.isReadOnly = value; } + } + // Password field (indirectly lossy behaviour when activated via multiline) public bool isPasswordField { @@ -161,8 +170,10 @@ protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) { KeyDownEvent keyDownEvt = evt as KeyDownEvent; - if ((keyDownEvt?.keyCode == KeyCode.KeypadEnter) || - (keyDownEvt?.keyCode == KeyCode.Return)) + // We must handle the ETX (char 3) or the \n instead of the KeypadEnter or Return because the focus will + // have the drawback of having the second event to be handled by the focused field. + if ((keyDownEvt?.character == 3) || // KeyCode.KeypadEnter + (keyDownEvt?.character == '\n')) // KeyCode.Return { visualInput?.Focus(); } @@ -218,6 +229,7 @@ public int selectIndex get { return editorEngine.selectIndex; } } + public bool isReadOnly { get; set; } public int maxLength { get; set; } public char maskChar { get; set; } @@ -271,6 +283,7 @@ public string text internal TextInputBase() { + isReadOnly = false; focusable = true; AddToClassList(inputUssClassName); @@ -416,8 +429,7 @@ internal void DrawWithTextSelectionAndCursor(IStylePainterInternal painter, stri int cursorIndex = editorEngine.cursorIndex; int selectIndex = editorEngine.selectIndex; Rect localPosition = editorEngine.localPosition; - Vector2 scrollOffset = editorEngine.scrollOffset; - + var scrollOffset = editorEngine.scrollOffset; float textScaling = TextNative.ComputeTextScaling(worldTransform, GUIUtility.pixelsPerPoint); @@ -428,9 +440,17 @@ internal void DrawWithTextSelectionAndCursor(IStylePainterInternal painter, stri var textNativeSettings = textParams.GetTextNativeSettings(textScaling); float lineHeight = TextNative.ComputeTextHeight(textNativeSettings); - float wordWrapWidth = editorEngine.multiline - ? contentRect.width - : 0.0f; + + float wordWrapWidth = 0.0f; + + // Make sure to take into account the word wrap style... + if (editorEngine.multiline && (resolvedStyle.whiteSpace == WhiteSpace.Normal)) + { + wordWrapWidth = contentRect.width; + // Since the wrapping is enabled, there is no need to offset the text... It will always fit the space on screen ! + scrollOffset = Vector2.zero; + } + Input.compositionCursorPos = editorEngine.graphicalCursorPos - scrollOffset + new Vector2(localPosition.x, localPosition.y + lineHeight); @@ -480,14 +500,14 @@ internal void DrawWithTextSelectionAndCursor(IStylePainterInternal painter, stri if (inbetweenHeight > 0f) { // Draw all lines in-between - painterParams.rect = new Rect(contentRect.x, minPos.y + lineHeight, wordWrapWidth, inbetweenHeight); + painterParams.rect = new Rect(contentRect.xMin, minPos.y + lineHeight, contentRect.width, inbetweenHeight); painter.DrawRect(painterParams); } // Draw last line if not empty if (maxPos.x != contentRect.x) { - painterParams.rect = new Rect(contentRect.x, maxPos.y, maxPos.x, lineHeight); + painterParams.rect = new Rect(contentRect.xMin, maxPos.y, maxPos.x, lineHeight); painter.DrawRect(painterParams); } } @@ -499,11 +519,12 @@ internal void DrawWithTextSelectionAndCursor(IStylePainterInternal painter, stri textParams = TextStylePainterParameters.GetDefault(this, text); textParams.rect = new Rect(contentRect.x - scrollOffset.x, contentRect.y - scrollOffset.y, contentRect.width + scrollOffset.x, contentRect.height + scrollOffset.y); textParams.text = editorEngine.text; + painter.DrawText(textParams); } // Draw the cursor - if (!isDragging) + if (!isReadOnly && !isDragging) { if (cursorIndex == selectionEndIndex && computedStyle.unityFont.value != null) { @@ -549,7 +570,8 @@ internal void DrawWithTextSelectionAndCursor(IStylePainterInternal painter, stri internal virtual bool AcceptCharacter(char c) { - return true; + // when readonly, we do not accept any character + return !isReadOnly; } protected virtual void BuildContextualMenu(ContextualMenuPopulateEvent evt) diff --git a/Modules/UIElements/Events/CommandEventDispatchingStrategy.cs b/Modules/UIElements/Events/CommandEventDispatchingStrategy.cs index 4c7335b3fc..2e3408786a 100644 --- a/Modules/UIElements/Events/CommandEventDispatchingStrategy.cs +++ b/Modules/UIElements/Events/CommandEventDispatchingStrategy.cs @@ -19,11 +19,17 @@ public void DispatchEvent(EventBase evt, IPanel panel) if (imguiContainer != null) { - if (imguiContainer != evt.skipElement && imguiContainer.HandleIMGUIEvent(evt.imguiEvent)) + if (!evt.Skip(imguiContainer) && imguiContainer.HandleIMGUIEvent(evt.imguiEvent)) { evt.StopPropagation(); evt.PreventDefault(); } + + if (!evt.isPropagationStopped && evt.propagateToIMGUI) + { + evt.skipElements.Add(imguiContainer); + EventDispatchUtilities.PropagateToIMGUIContainer(panel.visualTree, evt); + } } else if (panel.focusController.GetLeafFocusedElement() != null) { diff --git a/Modules/UIElements/Events/EventBase.cs b/Modules/UIElements/Events/EventBase.cs index c048442467..5875ebd6c4 100644 --- a/Modules/UIElements/Events/EventBase.cs +++ b/Modules/UIElements/Events/EventBase.cs @@ -3,6 +3,7 @@ // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; +using System.Collections.Generic; namespace UnityEngine.UIElements { @@ -92,7 +93,12 @@ public IEventHandler target } } - internal IEventHandler skipElement { get; set; } + internal List skipElements { get; } = new List(); + + internal bool Skip(IEventHandler h) + { + return skipElements.Contains(h); + } public bool isPropagationStopped { @@ -314,7 +320,7 @@ void LocalInit() leafTarget = null; target = null; - skipElement = null; + skipElements.Clear(); isPropagationStopped = false; isImmediatePropagationStopped = false; diff --git a/Modules/UIElements/Events/IEventDispatchingStrategy.cs b/Modules/UIElements/Events/IEventDispatchingStrategy.cs index cc7d1281c7..70b2549246 100644 --- a/Modules/UIElements/Events/IEventDispatchingStrategy.cs +++ b/Modules/UIElements/Events/IEventDispatchingStrategy.cs @@ -2,8 +2,6 @@ // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License -using System; - namespace UnityEngine.UIElements { // determines in which event phase an event handler wants to handle events @@ -51,7 +49,7 @@ public static void PropagateEvent(EventBase evt) if (evt.isPropagationStopped) break; - if (evt.path.trickleDownPath[i] == evt.skipElement) + if (evt.Skip(evt.path.trickleDownPath[i])) { continue; } @@ -63,7 +61,7 @@ public static void PropagateEvent(EventBase evt) // Phase 2: Target // Call HandleEvent() even if propagation is stopped, for the default actions at target. - if (evt.target != null && evt.target != evt.skipElement) + if (evt.target != null && !evt.Skip(evt.target)) { evt.propagationPhase = PropagationPhase.AtTarget; evt.currentTarget = evt.target; @@ -76,7 +74,7 @@ public static void PropagateEvent(EventBase evt) { foreach (var element in evt.path.targetAndBubblePath) { - if (element.m_VisualElement == evt.skipElement) + if (evt.Skip(element.m_VisualElement)) { continue; } @@ -115,8 +113,13 @@ internal static void PropagateToIMGUIContainer(VisualElement root, EventBase evt // If e.type != EventType.Used, avoid resending the event to the capture as it already had the chance to handle it. var imContainer = root as IMGUIContainer; - if (imContainer != null && (evt.imguiEvent.type == EventType.Used || root != evt.skipElement)) + if (imContainer != null && (evt.imguiEvent.type == EventType.Used || !evt.Skip(root))) { + if (evt.Skip(imContainer)) + { + return; + } + if (imContainer.HandleIMGUIEvent(evt.imguiEvent)) { evt.StopPropagation(); diff --git a/Modules/UIElements/Events/KeyboardEventDispatchingStrategy.cs b/Modules/UIElements/Events/KeyboardEventDispatchingStrategy.cs index 5645ae2f85..4cd3236c37 100644 --- a/Modules/UIElements/Events/KeyboardEventDispatchingStrategy.cs +++ b/Modules/UIElements/Events/KeyboardEventDispatchingStrategy.cs @@ -21,8 +21,8 @@ public void DispatchEvent(EventBase evt, IPanel panel) if (imguiContainer != null) { - // THINK ABOUT THIS PF: shoudln't we allow for the trickleDown dispatch phase? - if (imguiContainer != evt.skipElement && imguiContainer.HandleIMGUIEvent(evt.imguiEvent)) + // THINK ABOUT THIS PF: shouldn't we allow for the trickleDown dispatch phase? + if (!evt.Skip(imguiContainer) && imguiContainer.HandleIMGUIEvent(evt.imguiEvent)) { evt.StopPropagation(); evt.PreventDefault(); diff --git a/Modules/UIElements/Events/MouseCaptureDispatchingStrategy.cs b/Modules/UIElements/Events/MouseCaptureDispatchingStrategy.cs index 1a2669a942..f8bcb93766 100644 --- a/Modules/UIElements/Events/MouseCaptureDispatchingStrategy.cs +++ b/Modules/UIElements/Events/MouseCaptureDispatchingStrategy.cs @@ -69,9 +69,6 @@ public void DispatchEvent(EventBase evt, IPanel panel) captureBehavior = EventBehavior.None; } - // FIXME ugly - evt.skipElement = null; - if ((captureBehavior & EventBehavior.IsCapturable) == EventBehavior.IsCapturable) { BaseVisualElementPanel basePanel = panel as BaseVisualElementPanel; @@ -103,7 +100,7 @@ public void DispatchEvent(EventBase evt, IPanel panel) evt.dispatch = false; // Do not call HandleEvent again for this element. - evt.skipElement = originalCaptureElement; + evt.skipElements.Add(originalCaptureElement); evt.stopDispatch = (captureBehavior & EventBehavior.IsSentExclusivelyToCapturingElement) == EventBehavior.IsSentExclusivelyToCapturingElement; evt.propagateToIMGUI = false; diff --git a/Modules/UIElements/IMGUIContainer.cs b/Modules/UIElements/IMGUIContainer.cs index ae3e88e7a7..3d88084070 100644 --- a/Modules/UIElements/IMGUIContainer.cs +++ b/Modules/UIElements/IMGUIContainer.cs @@ -26,7 +26,20 @@ public override IEnumerable uxmlChildElementsDescri } // Set this delegate to have your IMGUI code execute inside the container - private readonly Action m_OnGUIHandler; + private Action m_OnGUIHandler; + public Action onGUIHandler + { + get { return m_OnGUIHandler; } + set + { + if (m_OnGUIHandler != value) + { + m_OnGUIHandler = value; + IncrementVersion(VersionChangeType.Layout); + IncrementVersion(VersionChangeType.Repaint); + } + } + } // If needed, an IMGUIContainer will allocate native state via this utility object to store control IDs ObjectGUIState m_ObjectGUIState; @@ -106,7 +119,7 @@ public IMGUIContainer(Action onGUIHandler) AddToClassList(ussClassName); - m_OnGUIHandler = onGUIHandler; + this.onGUIHandler = onGUIHandler; contextType = ContextType.Editor; focusable = true; @@ -176,7 +189,7 @@ private void DoOnGUI(Event evt, Matrix4x4 parentTransform, Rect clippingRect, bo // Extra checks are needed here because client code might have changed the IMGUIContainer // since we enter HandleIMGUIEvent() - if (m_OnGUIHandler == null + if (onGUIHandler == null || panel == null) { return; @@ -263,7 +276,7 @@ private void DoOnGUI(Event evt, Matrix4x4 parentTransform, Rect clippingRect, bo { using (new GUIClip.ParentClipScope(parentTransform, clippingRect)) { - m_OnGUIHandler(); + onGUIHandler(); } } catch (Exception exception) @@ -454,7 +467,7 @@ internal bool HandleIMGUIEvent(Event e) internal bool HandleIMGUIEvent(Event e, Matrix4x4 worldTransform, Rect clippingRect) { - if (e == null || m_OnGUIHandler == null || elementPanel == null || elementPanel.IMGUIEventInterests.WantsEvent(e.type) == false) + if (e == null || onGUIHandler == null || elementPanel == null || elementPanel.IMGUIEventInterests.WantsEvent(e.type) == false) { return false; } diff --git a/Modules/UIElements/ScrollView.cs b/Modules/UIElements/ScrollView.cs index 8a446b14c8..c99b599256 100644 --- a/Modules/UIElements/ScrollView.cs +++ b/Modules/UIElements/ScrollView.cs @@ -35,7 +35,7 @@ namespace UnityEngine.UIElements // This type is more tricky, it requires the content-viewport and content-container to have a different flex-direction. // "flex-grow:1" is to make elements stretch horizontally. // "align-self:flex-start" prevent the content-container from shrinking below the content size vertically. - // "overflow:scroll" on the content-viewport is to not restrict measured elements horizontally. + // "overflow:scroll" on the content-viewport and content-container is to not restrict measured elements in any direction. public enum ScrollViewMode { Vertical, diff --git a/Modules/Video/Public/ScriptBindings/MediaComponent.bindings.cs b/Modules/Video/Public/ScriptBindings/MediaComponent.bindings.cs index 3900d8259a..1d68d2bf62 100644 --- a/Modules/Video/Public/ScriptBindings/MediaComponent.bindings.cs +++ b/Modules/Video/Public/ScriptBindings/MediaComponent.bindings.cs @@ -7,6 +7,7 @@ using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; +using UnityEngine.Experimental.Audio; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("VideoTesting")] @@ -78,6 +79,37 @@ internal class VideoPlayback extern public bool GetLoop(); extern public void SetLoop(bool value); + [NativeHeader("Modules/Audio/Public/AudioSource.h")] + extern public UInt16 GetAudioTrackCount(); + extern public UInt16 GetAudioChannelCount(UInt16 trackIdx); + extern public UInt32 GetAudioSampleRate(UInt16 trackIdx); + extern public void SetAudioTarget(UInt16 trackIdx, bool enabled, bool softwareOutput, AudioSource audioSource); + extern private UInt32 GetAudioSampleProviderId(UInt16 trackIndex); + public AudioSampleProvider GetAudioSampleProvider(ushort trackIndex) + { + if (trackIndex >= GetAudioTrackCount()) + throw new ArgumentOutOfRangeException( + "trackIndex", trackIndex, + "VideoPlayback has " + GetAudioTrackCount() + " tracks."); + + var provider = AudioSampleProvider.Lookup(GetAudioSampleProviderId(trackIndex), null, trackIndex); + + if (provider == null) + throw new InvalidOperationException( + "VideoPlayback.GetAudioSampleProvider got null provider."); + + if (provider.owner != null) + throw new InvalidOperationException( + "Internal error: VideoPlayback.GetAudioSampleProvider got unexpected non-null provider owner."); + + if (provider.trackIndex != trackIndex) + throw new InvalidOperationException( + "Internal error: VideoPlayback.GetAudioSampleProvider got provider for track " + + provider.trackIndex + " instead of " + trackIndex); + + return provider; + } + extern static internal bool PlatformSupportsH265(); } } diff --git a/Modules/VideoEditor/Editor/VideoPlayerEditor.cs b/Modules/VideoEditor/Editor/VideoPlayerEditor.cs index 12ff8c81d9..89fa5cc45c 100644 --- a/Modules/VideoEditor/Editor/VideoPlayerEditor.cs +++ b/Modules/VideoEditor/Editor/VideoPlayerEditor.cs @@ -98,7 +98,6 @@ class Styles "Audio controls not editable when using muliple selection."; public readonly string enableDecodingTooltip = "Enable decoding for this track. Only effective when not playing. When playing from a URL, track details are shown only while playing back."; - public readonly string vulkanSupportHelp = "The Unity VideoPlayer does not support the Vulkan Graphics API.\nPlease go to PlayerSettings and remove 'Vulkan' from the list of Graphics APIs."; public static readonly int ObjectFieldControlID = "VideoPlayerAudioSourceObjectFieldHash".GetHashCode(); } @@ -255,12 +254,6 @@ public override void OnInspectorGUI() HandleAudio(); serializedObject.ApplyModifiedProperties(); - - if (EditorUserBuildSettings.selectedBuildTargetGroup == BuildTargetGroup.Android && - PlayerSettings.GetGraphicsAPIs(BuildTarget.Android).Contains(UnityEngine.Rendering.GraphicsDeviceType.Vulkan)) - { - EditorGUILayout.HelpBox(s_Styles.vulkanSupportHelp, MessageType.Warning); - } } private void HandleDataSourceField() diff --git a/README.md b/README.md index 7164458d0b..8baa1743eb 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Unity 2019.1.0a14 C# reference source code +## Unity 2019.1.0b1 C# reference source code The C# part of the Unity engine and editor source code. May be used for reference purposes only. From ab41f4991a2f81e41a0fd501ccb6284e107362a7 Mon Sep 17 00:00:00 2001 From: Unity Technologies Date: Mon, 4 Feb 2019 13:55:05 +0000 Subject: [PATCH 03/26] Unity 2019.1.0b2 C# reference source code --- Editor/Mono/Inspector/EditMode.cs | 38 +- Editor/Mono/Inspector/Editor.cs | 24 +- Editor/Mono/Inspector/EditorDragging.cs | 2 +- Editor/Mono/Inspector/EditorElement.cs | 353 +++++++++++++++ Editor/Mono/Inspector/GenericInspector.cs | 8 +- Editor/Mono/Inspector/InspectorElement.cs | 119 +++-- Editor/Mono/Inspector/InspectorWindow.cs | 423 ++++++------------ Editor/Mono/Inspector/RenderTextureEditor.cs | 24 +- Editor/Mono/Inspector/TextureInspector.cs | 3 - Editor/Mono/ObjectListArea.cs | 1 - Editor/Mono/SceneHierarchy.cs | 5 +- Editor/Mono/SceneView/SceneView.cs | 15 +- Editor/Mono/SceneVisibilityManager.cs | 2 +- Editor/Mono/SyncRiderProject.cs | 13 +- .../SolutionSynchronizer.cs | 2 +- Modules/IMGUI/GUI.cs | 13 +- .../Editor/Managed/Requests/ListRequest.cs | 5 +- .../Editor/Managed/Requests/Request.cs | 2 + .../Editor/Managed/Requests/SearchRequest.cs | 5 +- Modules/Terrain/Public/PaintContext.cs | 233 ++++------ Modules/Terrain/Public/Terrain.bindings.cs | 20 +- Modules/Terrain/Public/TerrainCallbacks.cs | 37 ++ Modules/Terrain/Public/TerrainData.GPUCopy.cs | 182 ++++++++ .../Terrain/Public/TerrainData.bindings.cs | 45 +- Modules/Terrain/Public/TerrainPaintUtility.cs | 57 ++- .../PaintTools/CreateTerrainTool.cs | 7 +- .../PaintTools/PaintTreesTool.cs | 3 +- Modules/TerrainEditor/TerrainInspector.cs | 10 +- .../TerrainEditor/Utilities/TerrainMenus.cs | 5 +- .../Utilities/TerrainPaintUtilityEditor.cs | 2 +- Modules/UIElements/Renderer/UIRUtility.cs | 22 +- .../Renderer/UIRenderer/UIRenderDevice.cs | 18 +- Modules/UnityWebRequestWWW/Public/WWW.cs | 8 +- Projects/CSharp/UnityEditor.csproj | 3 + Projects/CSharp/UnityEngine.csproj | 6 + README.md | 2 +- .../Export/Android/AndroidJava.bindings.cs | 150 ++++++- Runtime/Export/Android/AndroidJavaImpl.cs | 6 + Runtime/Export/Graphics/Texture.cs | 18 - .../Scripting/UnitySynchronizationContext.cs | 10 +- Runtime/Export/Shaders/Shader.bindings.cs | 2 +- 41 files changed, 1290 insertions(+), 613 deletions(-) create mode 100644 Editor/Mono/Inspector/EditorElement.cs create mode 100644 Modules/Terrain/Public/TerrainCallbacks.cs create mode 100644 Modules/Terrain/Public/TerrainData.GPUCopy.cs diff --git a/Editor/Mono/Inspector/EditMode.cs b/Editor/Mono/Inspector/EditMode.cs index 0d3447fa5e..867aa60674 100644 --- a/Editor/Mono/Inspector/EditMode.cs +++ b/Editor/Mono/Inspector/EditMode.cs @@ -16,6 +16,8 @@ namespace UnityEditorInternal [InitializeOnLoad] public class EditMode { + internal const int k_OwnerIdNone = 0; + private static class Styles { public static readonly GUIStyle multiButtonStyle = "Command"; @@ -30,18 +32,22 @@ static EditMode() ownerID = SessionState.GetInt(kOwnerStringKey, ownerID); s_EditMode = (SceneViewEditMode)SessionState.GetInt(kEditModeStringKey, (int)s_EditMode); Selection.selectionChanged += OnSelectionChange; + EditorToolContext.toolChanged += ToolChanged; } private const float k_EditColliderbuttonWidth = 33; private const float k_EditColliderbuttonHeight = 23; private const float k_SpaceBetweenLabelAndButton = 5; + // todo Obsolete, use editModeEnded public static OnEditModeStopFunc onEditModeEndDelegate; public delegate void OnEditModeStopFunc(Editor editor); - internal static event Action editModeEnded; + // todo Obsolete, use editModeStarted public static OnEditModeStartFunc onEditModeStartDelegate; public delegate void OnEditModeStartFunc(Editor editor, SceneViewEditMode mode); + + internal static event Action editModeEnded; internal static event Action editModeStarted; private static int s_OwnerID; @@ -127,11 +133,6 @@ private set } } - internal static void EndSceneViewEditing() - { - ChangeEditMode(SceneViewEditMode.None, new Bounds(Vector3.zero, Vector3.positiveInfinity), null); - } - public static void OnSelectionChange() { IToolModeOwner owner = InternalEditorUtility.GetObjectFromInstanceID(ownerID) as IToolModeOwner; @@ -140,9 +141,18 @@ public static void OnSelectionChange() QuitEditMode(); } + static void ToolChanged(EditorTool previous, EditorTool active) + { + var previousToolType = EditorToolUtility.GetEnumWithEditorTool(previous); + + if (previousToolType == Tool.None && ownerID != k_OwnerIdNone) + ChangeEditModeFromToolContext(null, SceneViewEditMode.None); + } + public static void QuitEditMode() { - EndSceneViewEditing(); + if (ownerID != k_OwnerIdNone) + ChangeEditMode(SceneViewEditMode.None, new Bounds(Vector3.zero, Vector3.positiveInfinity), null); } internal static void ChangeEditModeFromToolContext(IToolModeOwner owner, SceneViewEditMode mode) @@ -159,18 +169,22 @@ internal static void ChangeEditModeFromToolContext(IToolModeOwner owner, SceneVi editMode = mode; - ownerID = mode != SceneViewEditMode.None ? owner.GetInstanceID() : 0; + if (oldOwner != null) + { + if (onEditModeEndDelegate != null && oldOwner is Editor) + onEditModeEndDelegate(oldOwner as Editor); - if (onEditModeEndDelegate != null && oldOwner is Editor) - onEditModeEndDelegate(oldOwner as Editor); + if (editModeEnded != null) + editModeEnded(oldOwner); + } - if (editModeEnded != null) - editModeEnded(oldOwner); + ownerID = mode != SceneViewEditMode.None ? owner.GetInstanceID() : k_OwnerIdNone; if (editMode != SceneViewEditMode.None) { if (onEditModeStartDelegate != null && owner is Editor) onEditModeStartDelegate(owner as Editor, editMode); + if (editModeStarted != null) editModeStarted(owner, editMode); } diff --git a/Editor/Mono/Inspector/Editor.cs b/Editor/Mono/Inspector/Editor.cs index 0440473219..db3b202ae4 100644 --- a/Editor/Mono/Inspector/Editor.cs +++ b/Editor/Mono/Inspector/Editor.cs @@ -328,7 +328,25 @@ public partial class Editor : ScriptableObject, IPreviewable, IToolModeOwner internal SerializedObject m_SerializedObject = null; internal SerializedProperty m_EnabledProperty = null; - internal InspectorMode m_InspectorMode = InspectorMode.Normal; + private InspectorMode m_InspectorMode = InspectorMode.Normal; + internal InspectorMode inspectorMode + { + get + { + return m_InspectorMode; + } + set + { + if (m_InspectorMode != value) + { + m_InspectorMode = value; + m_SerializedObject = null; + m_EnabledProperty = null; + } + } + } + + internal const float kLineHeight = 16; internal bool hideInspector = false; @@ -529,7 +547,7 @@ internal virtual SerializedObject GetSerializedObjectInternal() if (m_SerializedObject == null) { m_SerializedObject = new SerializedObject(targets, m_Context); - m_SerializedObject.inspectorMode = m_InspectorMode; + m_SerializedObject.inspectorMode = inspectorMode; m_EnabledProperty = m_SerializedObject.FindProperty("m_Enabled"); } @@ -969,7 +987,7 @@ internal bool CanBeExpandedViaAFoldout() m_SerializedObject = new SerializedObject(targets, m_Context); else m_SerializedObject.Update(); - m_SerializedObject.inspectorMode = m_InspectorMode; + m_SerializedObject.inspectorMode = inspectorMode; SerializedProperty property = m_SerializedObject.GetIterator(); diff --git a/Editor/Mono/Inspector/EditorDragging.cs b/Editor/Mono/Inspector/EditorDragging.cs index 7bf97e9ff7..e526c5dcce 100644 --- a/Editor/Mono/Inspector/EditorDragging.cs +++ b/Editor/Mono/Inspector/EditorDragging.cs @@ -160,7 +160,7 @@ void HandleEditorDragging(Editor[] editors, int editorIndex, Rect targetRect, fl } } - if (m_TargetAbove && m_InspectorWindow.EditorHasLargeHeader(m_TargetIndex, editors)) + if (m_TargetAbove && InspectorWindow.EditorHasLargeHeader(m_TargetIndex, editors)) { m_TargetIndex--; while (m_TargetIndex >= 0 && m_InspectorWindow.ShouldCullEditor(editors, m_TargetIndex)) diff --git a/Editor/Mono/Inspector/EditorElement.cs b/Editor/Mono/Inspector/EditorElement.cs new file mode 100644 index 0000000000..50a3d5c31c --- /dev/null +++ b/Editor/Mono/Inspector/EditorElement.cs @@ -0,0 +1,353 @@ +// Unity C# reference source +// Copyright (c) Unity Technologies. For terms of use, see +// https://unity3d.com/legal/licenses/Unity_Reference_Only_License + +using System; +using UnityEditorInternal; +using UnityEngine; +using UnityEngine.UIElements; +using Object = UnityEngine.Object; + +namespace UnityEditor.UIElements +{ + internal class EditorElement : VisualElement + { + readonly InspectorWindow inspectorWindow; + + Editor[] m_Editors => inspectorWindow.tracker.activeEditors; + int m_editorIndex; + public Editor editor => m_Editors[m_editorIndex]; + + Rect m_DragRect; + Rect m_ContentRect; + + VisualElement m_PrefabElement; + + IMGUIContainer m_Header; + internal InspectorElement m_InspectorElement { get; private set; } + IMGUIContainer m_Footer; + + internal EditorElement(int editorIndex, InspectorWindow iw) + { + m_editorIndex = editorIndex; + inspectorWindow = iw; + + Init(); + + Add(m_Header); + Add(m_InspectorElement); + Add(m_Footer); + } + + void Init() + { + Object editorTarget = editor.targets[0]; + string editorTitle = ObjectNames.GetInspectorTitle(editorTarget); + + var inspectorElementMode = InspectorElement.GetModeFromInspectorMode(inspectorWindow.m_InspectorMode); + if (inspectorWindow.m_UseUIElementsDefaultInspector) + inspectorElementMode ^= InspectorElement.Mode.IMGUIDefault; + + m_InspectorElement = new InspectorElement(editor, inspectorElementMode) + { + focusable = false + }; + + + m_Header = BuildHeaderElement(editorTitle); + m_Footer = BuildFooterElement(editorTitle); + + m_InspectorElement.name = editorTitle + "Inspector"; + m_InspectorElement.style.paddingBottom = InspectorWindow.kEditorElementPaddingBottom; + + if (EditorNeedsVerticalOffset(editorTarget)) + { + // This is madness + m_InspectorElement.cacheAsBitmap = false; + m_InspectorElement.style.overflow = Overflow.Hidden; + } + } + + internal void Reinit(int editorIndex) + { + m_editorIndex = editorIndex; + + m_Header.onGUIHandler = HeaderOnGUI; + m_Footer.onGUIHandler = FooterOnGUI; + m_InspectorElement.editor = editor; + } + + internal void AddPrefabComponent(VisualElement comp) + { + if (m_PrefabElement != null) + { + m_PrefabElement.RemoveFromHierarchy(); + m_PrefabElement = null; + } + + if (comp != null) + { + m_PrefabElement = comp; + Insert(0, m_PrefabElement); + } + } + + #region Header + + IMGUIContainer BuildHeaderElement(string editorTitle) + { + //Create and IMGUIContainer to enclose the header + // This also needs to validate the state of the editor tracker (stuff that was already done in the original DrawEditors + var headerElement = inspectorWindow.CreateIMGUIContainer(HeaderOnGUI, editorTitle + "Header"); + return headerElement; + } + + void HeaderOnGUI() + { + var editors = inspectorWindow.tracker.activeEditors; + if (editors.Length <= m_editorIndex) + { + SetElementVisible(m_InspectorElement, false); + return; + } + + var target = editor.target; + + // Avoid drawing editor if native target object is not alive, unless it's a MonoBehaviour/ScriptableObject + // We want to draw the generic editor with a warning about missing/invalid script + // Case 891450: + // - ActiveEditorTracker will automatically create editors for materials of components on tracked game objects + // - UnityEngine.UI.Mask will destroy this material in OnDisable (e.g. disabling it with the checkbox) causing problems when drawing the material editor + if (target == null && !NativeClassExtensionUtilities.ExtendsANativeType(target)) + { + SetElementVisible(m_InspectorElement, false); + return; + } + + bool wasVisible = inspectorWindow.WasEditorVisible(editors, m_editorIndex, target); + + GUIUtility.GetControlID(target.GetInstanceID(), FocusType.Passive); + EditorGUIUtility.ResetGUIState(); + + if (editor.target is AssetImporter) + inspectorWindow.editorsWithImportedObjectLabel.Add(m_editorIndex + 1); + + //set the current PropertyHandlerCache to the current editor + ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; + using (new InspectorWindowUtils.LayoutGroupChecker()) + { + m_DragRect = DrawEditorHeader(target, ref wasVisible); + } + + if (wasVisible != m_InspectorElement.visible) + { + SetElementVisible(m_InspectorElement, wasVisible); + } + + var multiEditingSupported = inspectorWindow.IsMultiEditingSupported(editor, target); + + if (!multiEditingSupported && wasVisible) + { + GUILayout.Label("Multi-object editing not supported.", EditorStyles.helpBox); + return; + } + + InspectorWindowUtils.DisplayDeprecationMessageIfNecessary(editor); + + // Reset dirtiness when repainting + if (Event.current.type == EventType.Repaint) + { + editor.isInspectorDirty = false; + } + + bool excludedClass = InspectorWindowUtils.IsExcludedClass(target); + if (excludedClass) + EditorGUILayout.HelpBox( + "The module which implements this component type has been force excluded in player settings. This object will be removed in play mode and from any builds you make.", + MessageType.Warning); + + m_ContentRect = m_InspectorElement.layout; + } + + Rect DrawEditorHeader(Object target, ref bool wasVisible) + { + var largeHeader = DrawEditorLargeHeader(ref wasVisible); + + // Dragging handle used for editor reordering + var dragRect = largeHeader + ? new Rect() + : DrawEditorSmallHeader(target, wasVisible); + return dragRect; + } + + bool DrawEditorLargeHeader(ref bool wasVisible) + { + bool largeHeader = InspectorWindow.EditorHasLargeHeader(m_editorIndex, m_Editors); + + // Draw large headers before we do the culling of unsupported editors below, + // so the large header is always shown even when the editor can't be. + if (largeHeader) + { + String message = String.Empty; + bool IsOpenForEdit = editor.IsOpenForEdit(out message); + wasVisible = true; + + if (inspectorWindow.editorsWithImportedObjectLabel.Contains(m_editorIndex)) + { + var importedObjectBarRect = GUILayoutUtility.GetRect(16, 16); + importedObjectBarRect.height = 17; + + // Clip the label to avoid a black border at the bottom + GUI.BeginGroup(importedObjectBarRect); + GUI.Label(new Rect(0, 0, importedObjectBarRect.width, importedObjectBarRect.height), + "Imported Object", "OL Title"); + GUI.EndGroup(); + } + + // Header + using (new EditorGUI.DisabledScope(!IsOpenForEdit)) // Only disable the entire header if the asset is locked by VCS + { + editor.DrawHeader(); + } + } + + return largeHeader; + } + + // Draw small headers (the header above each component) after the culling above + // so we don't draw a component header for all the components that can't be shown. + Rect DrawEditorSmallHeader(Object target, bool wasVisible) + { + var editors = m_Editors; + var editor = editors[m_editorIndex]; + // ensure first component's title bar is flush with the header + if (EditorNeedsVerticalOffset(target)) + { + // TODO: Check if we can fix this in the GameObjectInspector instead + GUILayout.Space( + -1f // move back up so line overlaps + - EditorStyles.inspectorBig.margin.bottom - + EditorStyles.inspectorTitlebar.margin.top // move back up margins + ); + } + + using (new EditorGUI.DisabledScope(!editor.IsEnabled())) + { + bool isVisible = EditorGUILayout.InspectorTitlebar(wasVisible, editor); + if (wasVisible != isVisible) + { + inspectorWindow.tracker.SetVisible(m_editorIndex, isVisible ? 1 : 0); + InternalEditorUtility.SetIsInspectorExpanded(target, isVisible); + if (isVisible) + { + inspectorWindow.lastInteractedEditor = editor; + } + else if (inspectorWindow.lastInteractedEditor == editor) + { + inspectorWindow.lastInteractedEditor = null; + } + } + } + + return GUILayoutUtility.GetLastRect(); + } + + internal static void SetElementVisible(InspectorElement ve, bool visible) + { + if (visible) + { + ve.style.position = Position.Relative; + ve.style.visibility = Visibility.Visible; + SetInspectorElementChildIMGUIContainerFocusable(ve, true); + } + else + { + ve.style.position = Position.Absolute; + ve.style.visibility = Visibility.Hidden; + SetInspectorElementChildIMGUIContainerFocusable(ve, false); + } + } + + static void SetInspectorElementChildIMGUIContainerFocusable(InspectorElement ve, bool focusable) + { + foreach (var child in ve.Children()) + { + var imguiContainer = child as IMGUIContainer; + if (imguiContainer != null) + { + imguiContainer.focusable = focusable; + } + } + } + + #endregion Header + + #region Footer + + IMGUIContainer BuildFooterElement(string editorTitle) + { + IMGUIContainer footerElement = inspectorWindow.CreateIMGUIContainer(FooterOnGUI, editorTitle + "Footer"); + footerElement.style.height = 3; + return footerElement; + } + + void FooterOnGUI() + { + var editors = m_Editors; + if (editors.Length <= m_editorIndex) + { + return; + } + + var ed = editors[m_editorIndex]; + + m_ContentRect.y = -m_ContentRect.height; + inspectorWindow.editorDragging.HandleDraggingToEditor(editors, m_editorIndex, m_DragRect, m_ContentRect); + HandleComponentScreenshot(m_ContentRect, ed); + + var target = ed.target; + var comp = target as Component; + + if (EditorGUI.ShouldDrawOverrideBackground(ed.targets, Event.current, comp)) + { + var rect = GUILayoutUtility.kDummyRect; + bool wasVisible = inspectorWindow.WasEditorVisible(editors, m_editorIndex, target); + // if the inspector is currently visible then the override background drawn by the footer needs to be slightly larger than if the inspector is collapsed + if (wasVisible) + { + rect.y -= 1; + rect.height += 1; + } + else + { + rect.y += 1; + rect.height -= 1; + } + + EditorGUI.DrawOverrideBackground(rect, true); + } + } + + void HandleComponentScreenshot(Rect content, Editor editor) + { + if (ScreenShots.s_TakeComponentScreenshot) + { + content.yMin -= 16; + if (content.Contains(Event.current.mousePosition)) + { + Rect globalComponentRect = GUIClip.Unclip(content); + globalComponentRect.position = + globalComponentRect.position + inspectorWindow.m_Parent.screenPosition.position; + ScreenShots.ScreenShotComponent(globalComponentRect, editor.target); + } + } + } + + #endregion Footer + + internal bool EditorNeedsVerticalOffset(Object target) + { + return m_editorIndex > 0 && m_Editors[m_editorIndex - 1].target is GameObject && target is Component; + } + } +} diff --git a/Editor/Mono/Inspector/GenericInspector.cs b/Editor/Mono/Inspector/GenericInspector.cs index cb3445a6f9..f8edc55f87 100644 --- a/Editor/Mono/Inspector/GenericInspector.cs +++ b/Editor/Mono/Inspector/GenericInspector.cs @@ -53,16 +53,16 @@ internal override bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out fl // Update serialized object representation if (m_SerializedObject == null) - m_SerializedObject = new SerializedObject(targets, m_Context) {inspectorMode = m_InspectorMode}; + m_SerializedObject = new SerializedObject(targets, m_Context) {inspectorMode = inspectorMode}; else { m_SerializedObject.Update(); - m_SerializedObject.inspectorMode = m_InspectorMode; + m_SerializedObject.inspectorMode = inspectorMode; } height = 0; SerializedProperty property = m_SerializedObject.GetIterator(); - var isInspectorModeNormal = m_InspectorMode == InspectorMode.Normal; + var isInspectorModeNormal = inspectorMode == InspectorMode.Normal; var isAssetBased = behaviour != null && generatorAsset != null; while (property.NextVisible(height <= 0)) { @@ -99,7 +99,7 @@ internal override bool OnOptimizedInspectorGUI(Rect contentRect) contentRect.y += EditorGUI.kControlVerticalSpacing; var property = m_SerializedObject.GetIterator(); - var isInspectorModeNormal = m_InspectorMode == InspectorMode.Normal; + var isInspectorModeNormal = inspectorMode == InspectorMode.Normal; var behaviour = target as MonoBehaviour; var generatorAsset = ScriptGeneratorAsset.FromMonoBehaviour(behaviour); var isAssetBased = behaviour != null && generatorAsset != null; diff --git a/Editor/Mono/Inspector/InspectorElement.cs b/Editor/Mono/Inspector/InspectorElement.cs index 8bc912d941..e23698128a 100644 --- a/Editor/Mono/Inspector/InspectorElement.cs +++ b/Editor/Mono/Inspector/InspectorElement.cs @@ -52,11 +52,23 @@ internal enum Mode internal Mode mode { get; private set; } - internal Editor Editor { get; private set; } + internal Editor editor + { + get { return m_Editor; } + set + { + if (m_Editor != value) + { + DestroyOwnedEditor(); + m_Editor = value; + PartialReset(); + } + } + } - internal bool OwnsEditor { get; private set; } = false; + internal bool ownsEditor { get; private set; } = false; - internal SerializedObject BoundObject { get; private set; } + internal SerializedObject boundObject { get; private set; } internal VisualElement prefabOverrideBlueBarsContainer { get; private set; } @@ -106,7 +118,7 @@ internal InspectorElement(Editor editor, Mode mode) this.mode = mode; - Editor = editor; + this.editor = editor; if (editor.targets.Length == 0) { @@ -127,11 +139,16 @@ internal InspectorElement(Editor editor, Mode mode) void OnDetachFromPanel(DetachFromPanelEvent evt) { - if (OwnsEditor && Editor != null) + DestroyOwnedEditor(); + } + + void DestroyOwnedEditor() + { + if (ownsEditor && editor != null) { - Object.DestroyImmediate(Editor); - Editor = null; - OwnsEditor = false; + Object.DestroyImmediate(editor); + editor = null; + ownsEditor = false; RegisterCallback(OnAttachToPanel); } @@ -140,10 +157,23 @@ void OnDetachFromPanel(DetachFromPanelEvent evt) void OnAttachToPanel(AttachToPanelEvent evt) { - Reset(BoundObject); + Reset(boundObject); UnregisterCallback(OnAttachToPanel); } + internal static Mode GetModeFromInspectorMode(InspectorMode mode) + { + switch (mode) + { + case InspectorMode.Debug: + return Mode.Debug; + case InspectorMode.DebugInternal: + return Mode.DebugInternal; + default: + return Mode.Normal; + } + } + private void Reset(SerializedObject bindObject) { Clear(); @@ -172,7 +202,7 @@ private void Reset(SerializedObject bindObject) return; } - BoundObject = bindObject; + boundObject = bindObject; var customInspector = CreateInspectorElementFromEditor(editor); if (customInspector == null) @@ -184,6 +214,25 @@ private void Reset(SerializedObject bindObject) hierarchy.Add(customInspector); } + private void PartialReset() + { + if (boundObject == null) + { + Reset(null); + return; + } + + var customInspector = CreateInspectorElementFromEditor(editor, true); + if (customInspector == null) + { + customInspector = CreateDefaultInspector(boundObject); + } + + Clear(); + if (customInspector != null && customInspector != this) + hierarchy.Add(customInspector); + } + protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) { base.ExecuteDefaultActionAtTarget(evt); @@ -197,8 +246,8 @@ protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) private Editor GetOrCreateEditor(SerializedObject serializedObject) { - if (Editor != null) - return Editor; + if (editor != null) + return editor; var target = serializedObject?.targetObject; @@ -208,14 +257,14 @@ private Editor GetOrCreateEditor(SerializedObject serializedObject) { if (trackerEditor.target == target || trackerEditor.serializedObject == serializedObject) { - return Editor = trackerEditor; + return editor = trackerEditor; } } } RegisterCallback(OnDetachFromPanel); - OwnsEditor = true; - return Editor = Editor.CreateEditor(serializedObject?.targetObject); + ownsEditor = true; + return editor = Editor.CreateEditor(serializedObject?.targetObject); } private VisualElement CreateDefaultInspector(SerializedObject serializedObject) @@ -258,7 +307,10 @@ bool AddMissingScriptLabel(SerializedObject serializedObject) return false; } - private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serializedObject, Editor editor) + IMGUIContainer m_IMGUIContainer; + + private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serializedObject, Editor editor, + bool reuseIMGUIContainer) { if ((mode & (Mode.IMGUICustom | Mode.IMGUIDefault)) == 0) return null; @@ -279,12 +331,12 @@ private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serialized if ((mode & Mode.DebugMod) > 0) { AddToClassList(debugVariantUssClassName); - editor.m_InspectorMode = InspectorMode.Debug; + editor.inspectorMode = InspectorMode.Debug; } else if ((mode & Mode.DebugInternalMod) > 0) { AddToClassList(debugInternalVariantUssClassName); - editor.m_InspectorMode = InspectorMode.DebugInternal; + editor.inspectorMode = InspectorMode.DebugInternal; } } else @@ -292,8 +344,17 @@ private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serialized AddToClassList(iMGUICustomVariantUssClassName); } - IMGUIContainer inspector = null; - inspector = new IMGUIContainer(() => + IMGUIContainer inspector; + // Reusing the existing IMGUIContainer allows us to re-use the existing gui state, when we are drawing the same inspector this will let us keep the same control ids + if (reuseIMGUIContainer && m_IMGUIContainer != null) + { + inspector = m_IMGUIContainer; + } + else + { + inspector = new IMGUIContainer(); + } + inspector.onGUIHandler = () => { if (!editor.serializedObject.isValid) { @@ -309,13 +370,13 @@ private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serialized switch (mode) { case Mode.Normal: - genericEditor.m_InspectorMode = InspectorMode.Normal; + genericEditor.inspectorMode = InspectorMode.Normal; break; case Mode.Default: - genericEditor.m_InspectorMode = InspectorMode.Debug; + genericEditor.inspectorMode = InspectorMode.Debug; break; case Mode.Custom: - genericEditor.m_InspectorMode = InspectorMode.DebugInternal; + genericEditor.inspectorMode = InspectorMode.DebugInternal; break; case Mode.IMGUI: break; @@ -341,7 +402,9 @@ private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serialized EditorGUIUtility.wideMode = true; } - GUIStyle editorWrapper = (editor.UseDefaultMargins() ? EditorStyles.inspectorDefaultMargins : GUIStyle.none); + GUIStyle editorWrapper = (editor.UseDefaultMargins() + ? EditorStyles.inspectorDefaultMargins + : GUIStyle.none); try { GUI.changed = false; @@ -400,9 +463,10 @@ private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serialized EditorGUIUtility.hierarchyMode = originalHierarchyMode; } } - }); + }; inspector.style.overflow = Overflow.Visible; + m_IMGUIContainer = inspector; if (!(editor is GenericInspector)) inspector.AddToClassList(customInspectorUssClassName); @@ -414,7 +478,7 @@ private VisualElement CreateIMGUIInspectorFromEditor(SerializedObject serialized return inspector; } - private VisualElement CreateInspectorElementFromEditor(Editor editor) + private VisualElement CreateInspectorElementFromEditor(Editor editor, bool reuseIMGUIContainer = false) { var serializedObject = editor.serializedObject; var target = editor.targets[0]; @@ -440,7 +504,7 @@ private VisualElement CreateInspectorElementFromEditor(Editor editor) } if (inspectorElement == null) - inspectorElement = CreateIMGUIInspectorFromEditor(serializedObject, editor); + inspectorElement = CreateIMGUIInspectorFromEditor(serializedObject, editor, reuseIMGUIContainer); if (inspectorElement == null && (mode & Mode.UIEDefault) > 0) inspectorElement = CreateDefaultInspector(serializedObject); @@ -457,6 +521,7 @@ private VisualElement CreateInspectorElementFromEditor(Editor editor) bool m_IsOpenForEdit; bool m_InvalidateGUIBlockCache = true; + Editor m_Editor; private bool GetRebuildOptimizedGUIBlocks(Object inspectedObject) { diff --git a/Editor/Mono/Inspector/InspectorWindow.cs b/Editor/Mono/Inspector/InspectorWindow.cs index 922932a75d..64a012d923 100644 --- a/Editor/Mono/Inspector/InspectorWindow.cs +++ b/Editor/Mono/Inspector/InspectorWindow.cs @@ -22,7 +22,6 @@ using Object = UnityEngine.Object; using Overflow = UnityEngine.UIElements.Overflow; -using Visibility = UnityEngine.UIElements.Visibility; using AssetImporterEditor = UnityEditor.Experimental.AssetImporters.AssetImporterEditor; @@ -41,7 +40,7 @@ internal class InspectorWindow : EditorWindow, IHasCustomMenu const float kAddComponentButtonHeight = 45f; internal const int kInspectorPaddingLeft = 4 + 10; internal const int kInspectorPaddingRight = 4; - const float kEditorElementPaddingBottom = 2f; + internal const float kEditorElementPaddingBottom = 2f; const float k_MinAreaAbovePreview = 130; const float k_InspectorPreviewMinHeight = 130; @@ -65,7 +64,7 @@ internal class InspectorWindow : EditorWindow, IHasCustomMenu [SerializeField] EditorGUIUtility.EditorLockTrackerWithActiveEditorTracker m_LockTracker = new EditorGUIUtility.EditorLockTrackerWithActiveEditorTracker(); - Editor m_LastInteractedEditor; + internal Editor lastInteractedEditor { get; set; } int m_LastInitialEditorInstanceID; Component[] m_ComponentsInPrefabSource; HashSet m_RemovedComponents; @@ -85,14 +84,15 @@ internal class InspectorWindow : EditorWindow, IHasCustomMenu private Dictionary> m_PreviewableTypes; private IPreviewable m_SelectedPreview; - readonly HashSet m_EditorsWithImportedObjectLabel = new HashSet(); + internal HashSet editorsWithImportedObjectLabel { get; } = new HashSet(); - private EditorDragging editorDragging; + internal EditorDragging editorDragging { get; } IMGUIContainer m_TrackerResetter; VisualElement m_EditorsElement; VisualElement editorsElement => m_EditorsElement ?? (m_EditorsElement = FindVisualElementInTreeByName("editorsList")); + VisualElement m_RemovedPrefabComponentsElement; VisualElement m_PreviewAndLabelElement; @@ -273,16 +273,15 @@ internal static List GetInspectors() } [UsedByNativeCode] - static private void RedrawFromNative() + private static void RedrawFromNative() { foreach (var inspector in m_AllInspectors) { - inspector.tracker.ForceRebuild(); inspector.RebuildContentsContainers(); } } - static internal InspectorWindow[] GetAllInspectorWindows() + internal static InspectorWindow[] GetAllInspectorWindows() { return m_AllInspectors.ToArray(); } @@ -520,7 +519,7 @@ private void ClearTrackerDirtyOnRepaint() private bool m_TrackerResetInserted; - IMGUIContainer CreateIMGUIContainer(Action onGUIHandler, string name = null) + internal IMGUIContainer CreateIMGUIContainer(Action onGUIHandler, string name = null) { IMGUIContainer result = null; if (m_TrackerResetInserted) @@ -552,11 +551,16 @@ internal virtual void RebuildContentsContainers() m_Previews = null; m_SelectedPreview = null; m_TypeSelectionList = null; - m_TrackerResetInserted = false; m_FirstInitialize = false; - m_EditorsWithImportedObjectLabel.Clear(); + editorsWithImportedObjectLabel.Clear(); m_LastInitialEditorInstanceID = 0; + if (m_RemovedPrefabComponentsElement != null) + { + m_RemovedPrefabComponentsElement.RemoveFromHierarchy(); + m_RemovedPrefabComponentsElement = null; + } + FlushAllOptimizedGUIBlocksIfNeeded(); ResetKeyboardControl(); @@ -568,8 +572,9 @@ internal virtual void RebuildContentsContainers() if (m_TrackerResetter == null) { + m_TrackerResetInserted = false; m_TrackerResetter = CreateIMGUIContainer(() => {}, "activeEditorTrackerResetter"); - rootVisualElement.Add(m_TrackerResetter); + rootVisualElement.Insert(0, m_TrackerResetter); } Editor[] editors = tracker.activeEditors; @@ -641,8 +646,6 @@ internal virtual void RebuildContentsContainers() rootVisualElement.MarkDirtyRepaint(); - if (m_Parent != null) // parent may be null in some situations (case 970700, 851988) - m_Parent.ClearKeyboardControl(); ScriptAttributeUtility.ClearGlobalCache(); rootVisualElement.RegisterCallback(DragOverBottomArea); @@ -710,7 +713,7 @@ protected virtual void OnGUI() internal virtual Editor GetLastInteractedEditor() { - return m_LastInteractedEditor; + return lastInteractedEditor; } internal IPreviewable GetEditorThatControlsPreview(IPreviewable[] editors) @@ -1248,73 +1251,58 @@ protected static void DrawVCSShortInfoAsset(Asset asset, string tooltip, Rect re EditorGUI.LabelField(textRect, content, Styles.preToolbar2); } - private void SetElementVisible(VisualElement ve, bool visible) + HashSet m_DrawnSelection = new HashSet(); + void DrawEditors(Editor[] editors) { - if (visible) + Dictionary mapping = null; + + var selection = new HashSet(Selection.instanceIDs); + if (m_DrawnSelection.SetEquals(selection)) { - ve.style.position = Position.Relative; - ve.style.visibility = Visibility.Visible; - SetInspectorElementChildIMGUIContainerFocusable(ve, true); + if (editorsElement.childCount > 0 && m_DrawnSelection.Any()) // do we already have a hierarchy + { + mapping = ProcessEditorElementsToRebuild(editors); + } } else { - ve.style.position = Position.Absolute; - ve.style.visibility = Visibility.Hidden; - SetInspectorElementChildIMGUIContainerFocusable(ve, false); + m_DrawnSelection.Clear(); + m_DrawnSelection = selection; } - } - private void SetInspectorElementChildIMGUIContainerFocusable(VisualElement ve, bool focusable) - { - var inspectorElement = ve as InspectorElement; - if (inspectorElement != null) + if (mapping == null) { - foreach (var child in inspectorElement.Children()) - { - var imguiContainer = child as IMGUIContainer; - if (imguiContainer != null) - { - imguiContainer.focusable = focusable; - } - } + editorsElement.Clear(); } - } - - private void DrawEditors(Editor[] editors) - { - editorsElement.Clear(); if (editors.Length == 0) + { return; - - // We need to force optimized GUI to dirty when object becomes open for edit - // e.g. after checkout in version control. If this is not done the optimized - // GUI will need an extra repaint before it gets ungrayed out. + } Editor.m_AllowMultiObjectAccess = true; - VisualElement editorContainer = editorsElement; - if (editors.Length > 0 && editors[0].GetInstanceID() != m_LastInitialEditorInstanceID) OnTrackerRebuilt(); int prefabComponentIndex = -1; + for (int editorIndex = 0; editorIndex < editors.Length; editorIndex++) { + VisualElement prefabsComponentElement = new VisualElement() { name = "PrefabComponentElement" }; if (m_ComponentsInPrefabSource != null && editorIndex != 0) { while (prefabComponentIndex < m_ComponentsInPrefabSource.Length) { Object target = editors[editorIndex].target; - // This is possible if there's a component with a missing script. if (target != null) { Object correspondingSource = PrefabUtility.GetCorrespondingObjectFromSource(target); Component nextInSource = m_ComponentsInPrefabSource[prefabComponentIndex]; + if (correspondingSource == nextInSource) break; - - AddRemovedPrefabComponentElement(editors, nextInSource, editorContainer); + AddRemovedPrefabComponentElement(editors, nextInSource, prefabsComponentElement); } prefabComponentIndex++; @@ -1330,165 +1318,46 @@ private void DrawEditors(Editor[] editors) } var editor = editors[editorIndex]; - Object editorTarget = editor.targets[0]; string editorTitle = ObjectNames.GetInspectorTitle(editorTarget); + EditorElement editorContainer; - var inspectorElementMode = InspectorElement.Mode.Normal; - if (m_UseUIElementsDefaultInspector) - inspectorElementMode ^= InspectorElement.Mode.IMGUIDefault; - - VisualElement editorElement = new InspectorElement(editor, inspectorElementMode) + if (mapping == null || !mapping.TryGetValue(editors[editorIndex].target.GetInstanceID(), out editorContainer)) { - focusable = false - }; - VisualElement footerElement = null; - { - var i = editorIndex; - Rect dragRect = new Rect(); - Rect contentRect = new Rect(); - - //Create and IMGUIcontainer to enclose the header - // This also needs to validate the state of the editor tracker (stuff that was already done in the original DrawEditors - var headerElement = CreateIMGUIContainer(() => // Dragging handle used for editor reordering - { - var edits = tracker.activeEditors; - - if (edits.Length <= i) - { - SetElementVisible(editorElement, false); - return; - } - - var thisEditor = edits[i]; - - var target = thisEditor?.target; - - // Avoid drawing editor if native target object is not alive, unless it's a MonoBehaviour/ScriptableObject - // We want to draw the generic editor with a warning about missing/invalid script - // Case 891450: - // - ActiveEditorTracker will automatically create editors for materials of components on tracked game objects - // - UnityEngine.UI.Mask will destroy this material in OnDisable (e.g. disabling it with the checkbox) causing problems when drawing the material editor - if (target == null && !NativeClassExtensionUtilities.ExtendsANativeType(target)) - { - SetElementVisible(editorElement, false); - return; - } - - bool wasVisible = WasEditorVisible(editors, editor, i, target); - - GUIUtility.GetControlID(target.GetInstanceID(), FocusType.Passive); - EditorGUIUtility.ResetGUIState(); - - if (editor.target is AssetImporter) - m_EditorsWithImportedObjectLabel.Add(i + 1); - - //set the current PropertyHandlerCache to the current editor - ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; - using (new InspectorWindowUtils.LayoutGroupChecker()) - { - dragRect = DrawEditorHeader(edits, i, thisEditor, target, ref wasVisible); - } - - if (wasVisible != editorElement.visible) - { - SetElementVisible(editorElement, wasVisible); - } - - var multiEditingSupported = IsMultiEditingSupported(editor, target); - - if (!multiEditingSupported && wasVisible) - { - GUILayout.Label("Multi-object editing not supported.", EditorStyles.helpBox); - return; - } - - InspectorWindowUtils.DisplayDeprecationMessageIfNecessary(editor); - - // Reset dirtiness when repainting - if (Event.current.type == EventType.Repaint) - { - thisEditor.isInspectorDirty = false; - } - - bool excludedClass = InspectorWindowUtils.IsExcludedClass(target); - if (excludedClass) - EditorGUILayout.HelpBox("The module which implements this component type has been force excluded in player settings. This object will be removed in play mode and from any builds you make.", MessageType.Warning); - - contentRect = editorElement.layout; - }, editorTitle + "Header"); - - editorContainer.Add(headerElement); - - footerElement = CreateIMGUIContainer(() => - { - var edits = tracker.activeEditors; - - if (edits.Length <= i) - { - return; - } - - var ed = edits[i]; - - contentRect.y = -contentRect.height; - editorDragging.HandleDraggingToEditor(edits, i, dragRect, contentRect); - HandleComponentScreenshot(contentRect, ed); - - var target = ed.target; - var comp = target as Component; - - if (EditorGUI.ShouldDrawOverrideBackground(ed.targets, Event.current, comp)) - { - var rect = GUILayoutUtility.kDummyRect; - bool wasVisible = WasEditorVisible(editors, editor, i, target); - // if the inspector is currently visible then the override background drawn by the footer needs to be slightly larger than if the inspector is collapsed - if (wasVisible) - { - rect.y -= 1; - rect.height += 1; - } - else - { - rect.y += 1; - rect.height -= 1; - } - - EditorGUI.DrawOverrideBackground(rect, true); - } - }, editorTitle + "Footer"); - footerElement.style.height = 3; + editorContainer = new EditorElement(editorIndex, this) { name = editorTitle }; + editorsElement.Add(editorContainer); } - editorElement.name = editorTitle; - - editorElement.style.paddingBottom = kEditorElementPaddingBottom; - - if (EditorNeedsVerticalOffset(editors, editorIndex, editorTarget)) + if (prefabsComponentElement.childCount > 0) { - // This is madness - editorElement.cacheAsBitmap = false; - editorElement.style.overflow = Overflow.Hidden; + editorContainer.AddPrefabComponent(prefabsComponentElement); + } + else + { + editorContainer.AddPrefabComponent(null); } - - editorContainer.Add(editorElement); - editorContainer.Add(footerElement); } // Make sure to display any remaining removed components that come after the last component on the GameObject. if (m_ComponentsInPrefabSource != null) { + VisualElement prefabsComponentElement = new VisualElement() { name = "RemainingPrefabComponentElement" }; while (prefabComponentIndex < m_ComponentsInPrefabSource.Length) { Component nextInSource = m_ComponentsInPrefabSource[prefabComponentIndex]; - AddRemovedPrefabComponentElement(editors, nextInSource, editorContainer); - + AddRemovedPrefabComponentElement(editors, nextInSource, prefabsComponentElement); prefabComponentIndex++; } + + if (prefabsComponentElement.childCount > 0) + { + editorsElement.Add(prefabsComponentElement); + m_RemovedPrefabComponentsElement = prefabsComponentElement; + } } } - void AddRemovedPrefabComponentElement(Editor[] editors, Component nextInSource, VisualElement editorContainer) + void AddRemovedPrefabComponentElement(Editor[] editors, Component nextInSource, VisualElement element) { var targetGameObject = editors[0].target as GameObject; if (ShouldDisplayRemovedComponent(targetGameObject, nextInSource)) @@ -1498,7 +1367,7 @@ void AddRemovedPrefabComponentElement(Editor[] editors, Component nextInSource, CreateIMGUIContainer(() => DisplayRemovedComponent(targetGameObject, nextInSource), missingComponentTitle); removedComponentElement.style.paddingBottom = kEditorElementPaddingBottom; - editorContainer.Add(removedComponentElement); + element.Add(removedComponentElement); } } @@ -1518,13 +1387,13 @@ bool ShouldDisplayRemovedComponent(GameObject go, Component comp) return true; } - void DisplayRemovedComponent(GameObject go, Component comp) + static void DisplayRemovedComponent(GameObject go, Component comp) { Rect rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar); EditorGUI.RemovedComponentTitlebar(rect, go, comp); } - private bool WasEditorVisible(Editor[] editors, Editor editor, int editorIndex, Object target) + internal bool WasEditorVisible(Editor[] editors, int editorIndex, Object target) { int wasVisibleState = tracker.GetVisible(editorIndex); bool wasVisible; @@ -1534,7 +1403,7 @@ private bool WasEditorVisible(Editor[] editors, Editor editor, int editorIndex, // Some inspectors (MaterialEditor) needs to be told when they are the main visible asset. if (editorIndex == 0 || (editorIndex == 1 && ShouldCullEditor(editors, 0))) { - editor.firstInspectedEditor = true; + editors[editorIndex].firstInspectedEditor = true; } // Init our state with last state @@ -1551,89 +1420,7 @@ private bool WasEditorVisible(Editor[] editors, Editor editor, int editorIndex, return wasVisible; } - Rect DrawEditorHeader(Editor[] editors, int editorIndex, Editor editor, Object target, ref bool wasVisible) - { - var largeHeader = DrawEditorLargeHeader(editors, editorIndex, editor, ref wasVisible); - - // Dragging handle used for editor reordering - var dragRect = largeHeader ? new Rect() : DrawEditorSmallHeader(editors, editorIndex, target, editor, wasVisible); - return dragRect; - } - - bool DrawEditorLargeHeader(Editor[] editors, int editorIndex, Editor editor, ref bool wasVisible) - { - bool largeHeader = EditorHasLargeHeader(editorIndex, editors); - - // Draw large headers before we do the culling of unsupported editors below, - // so the large header is always shown even when the editor can't be. - if (largeHeader) - { - String message = String.Empty; - bool IsOpenForEdit = editor.IsOpenForEdit(out message); - wasVisible = true; - - if (m_EditorsWithImportedObjectLabel.Contains(editorIndex)) - { - var importedObjectBarRect = GUILayoutUtility.GetRect(16, 16); - importedObjectBarRect.height = 17; - - // Clip the label to avoid a black border at the bottom - GUI.BeginGroup(importedObjectBarRect); - GUI.Label(new Rect(0, 0, importedObjectBarRect.width, importedObjectBarRect.height), "Imported Object", "OL Title"); - GUI.EndGroup(); - } - - // Header - using (new EditorGUI.DisabledScope(!IsOpenForEdit)) // Only disable the entire header if the asset is locked by VCS - { - editor.DrawHeader(); - } - } - - return largeHeader; - } - - private bool EditorNeedsVerticalOffset(Editor[] editors, int editorIndex, Object target) - { - return editorIndex > 0 && editors[editorIndex - 1].target is GameObject && target is Component; - } - - // Draw small headers (the header above each component) after the culling above - // so we don't draw a component header for all the components that can't be shown. - Rect DrawEditorSmallHeader(Editor[] editors, int editorIndex, Object target, Editor editor, bool wasVisible) - { - // ensure first component's title bar is flush with the header - if (EditorNeedsVerticalOffset(editors, editorIndex, target)) - { - // TODO: Check if we can fix this in the GameObjectInspector instead - GUILayout.Space( - -1f // move back up so line overlaps - - EditorStyles.inspectorBig.margin.bottom - EditorStyles.inspectorTitlebar.margin.top // move back up margins - ); - } - - using (new EditorGUI.DisabledScope(!editor.IsEnabled())) - { - bool isVisible = EditorGUILayout.InspectorTitlebar(wasVisible, editor); - if (wasVisible != isVisible) - { - tracker.SetVisible(editorIndex, isVisible ? 1 : 0); - InternalEditorUtility.SetIsInspectorExpanded(target, isVisible); - if (isVisible) - { - m_LastInteractedEditor = editor; - } - else if (m_LastInteractedEditor == editor) - { - m_LastInteractedEditor = null; - } - } - } - - return GUILayoutUtility.GetLastRect(); - } - - bool IsMultiEditingSupported(Editor editor, Object target) + internal bool IsMultiEditingSupported(Editor editor, Object target) { // Culling of editors that can't be properly shown. // If the current editor is a GenericInspector even though a custom editor for it exists, @@ -1666,25 +1453,11 @@ bool IsMultiEditingSupported(Editor editor, Object target) return multiEditingSupported; } - internal bool EditorHasLargeHeader(int editorIndex, Editor[] trackerActiveEditors) + internal static bool EditorHasLargeHeader(int editorIndex, Editor[] trackerActiveEditors) { return trackerActiveEditors[editorIndex].firstInspectedEditor || trackerActiveEditors[editorIndex].HasLargeHeader(); } - private void HandleComponentScreenshot(Rect contentRect, Editor editor) - { - if (ScreenShots.s_TakeComponentScreenshot) - { - contentRect.yMin -= 16; - if (contentRect.Contains(Event.current.mousePosition)) - { - Rect globalComponentRect = GUIClip.Unclip(contentRect); - globalComponentRect.position = globalComponentRect.position + m_Parent.screenPosition.position; - ScreenShots.ScreenShotComponent(globalComponentRect, editor.target); - } - } - } - internal bool ShouldCullEditor(Editor[] editors, int editorIndex) { if (editors[editorIndex].hideInspector) @@ -1739,6 +1512,19 @@ void DrawSelectionPickerList() EditorGUIUtility.SetIconSize(oldSize); } + void HandleLastInteractedEditor(Rect componentRect, Editor editor) + { + if (editor != lastInteractedEditor && + Event.current.type == EventType.MouseDown && componentRect.Contains(Event.current.mousePosition)) + { + // Don't use the event because the editor might want to use it. + // But don't move the check down below the editor either, + // because we want to set the last interacted editor simultaneously. + lastInteractedEditor = editor; + Repaint(); + } + } + private void AddComponentButton(Editor[] editors) { Editor editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(editors); @@ -1925,5 +1711,62 @@ internal static void RemoveInspectorWindow(InspectorWindow window) { m_AllInspectors.Remove(window); } + + /* + * ProcessEditorElementsToRebuild is required as there are times when the ActiveEditorTracker + * is rebuilt even though the selection does not change and there are IMGUI controls outside + * the InspectorWindow that depend on currently valid control IDs + * An example is the Object Selector + * + * When a rebuild of the InspectorWindow is requested, we attempt to match up existing Editor references to current ones. + * We can't rely on the Editor instance ids those will have been recreated and our previously drawn ones will now be invalid + * Instead we can find matching Editor instances by comparing the target InstanceIDs. + */ + Dictionary ProcessEditorElementsToRebuild(Editor[] editors) + { + Dictionary editorToElementMap = new Dictionary(); + var currentElements = editorsElement.Children().OfType().ToList(); + if (editors.Length == 0) + { + return null; + } + + if (rootVisualElement.panel == null) + { + return null; + } + + var newEditorsIndex = 0; + var previousEditorsIndex = 0; + while (newEditorsIndex < editors.Length && previousEditorsIndex < currentElements.Count) + { + var ed = editors[newEditorsIndex]; + var currentEd = currentElements[previousEditorsIndex]; + if (ed.GetType() != currentEd.editor.GetType()) + { + // We won't have an EditorElement for editors that are normally culled so we should skip this + if (ShouldCullEditor(editors, newEditorsIndex)) + { + ++newEditorsIndex; + continue; + } + + return null; + } + + currentEd.Reinit(newEditorsIndex); + editorToElementMap[ed.target.GetInstanceID()] = currentEd; + ++newEditorsIndex; + ++previousEditorsIndex; + } + + // Remove any elements at the end of the InspectorWindow that don't have matching Editors + for (int j = previousEditorsIndex; j < currentElements.Count; ++j) + { + currentElements[j].RemoveFromHierarchy(); + } + + return editorToElementMap; + } } } diff --git a/Editor/Mono/Inspector/RenderTextureEditor.cs b/Editor/Mono/Inspector/RenderTextureEditor.cs index 72673b5761..08827238c4 100644 --- a/Editor/Mono/Inspector/RenderTextureEditor.cs +++ b/Editor/Mono/Inspector/RenderTextureEditor.cs @@ -107,12 +107,32 @@ protected void OnRenderTextureGUI(GUIElements guiElements) if ((guiElements & GUIElements.RenderTargetAAGUI) != 0) EditorGUILayout.IntPopup(m_AntiAliasing, styles.renderTextureAntiAliasing, styles.renderTextureAntiAliasingValues, styles.antiAliasing); - EditorGUILayout.PropertyField(m_EnableCompatibleFormat, styles.enableCompatibleFormat); + + GraphicsFormat format = (GraphicsFormat)m_ColorFormat.intValue; + GraphicsFormat compatibleFormat = SystemInfo.GetCompatibleFormat(format, FormatUsage.Render); + + using (new EditorGUI.DisabledScope(compatibleFormat == GraphicsFormat.None)) + EditorGUILayout.PropertyField(m_EnableCompatibleFormat, styles.enableCompatibleFormat); + EditorGUILayout.PropertyField(m_ColorFormat, styles.colorFormat); + + if (compatibleFormat != format) + { + string text = string.Format("Format {0} is not supported on this platform. ", format.ToString()); + if (compatibleFormat != GraphicsFormat.None) + { + if (m_EnableCompatibleFormat.boolValue) + text += string.Format("Using {0} as a compatible format.", compatibleFormat.ToString()); + else + text += string.Format("You may enable Compatible Color Format to fallback automatically to a platform specific comptible format, {0} on this device.", compatibleFormat.ToString()); + } + EditorGUILayout.HelpBox(text, m_EnableCompatibleFormat.boolValue && compatibleFormat != GraphicsFormat.None ? MessageType.Warning : MessageType.Error); + } + if ((guiElements & GUIElements.RenderTargetDepthGUI) != 0) EditorGUILayout.PropertyField(m_DepthFormat, styles.depthBuffer); - m_sRGB.boolValue = GraphicsFormatUtility.IsSRGBFormat((GraphicsFormat)m_ColorFormat.intValue); + m_sRGB.boolValue = GraphicsFormatUtility.IsSRGBFormat(format); using (new EditorGUI.DisabledScope(isTexture3D)) { diff --git a/Editor/Mono/Inspector/TextureInspector.cs b/Editor/Mono/Inspector/TextureInspector.cs index 9544f149de..832775e481 100644 --- a/Editor/Mono/Inspector/TextureInspector.cs +++ b/Editor/Mono/Inspector/TextureInspector.cs @@ -791,9 +791,6 @@ public override string GetInfoString() TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(t)) as TextureImporter; string info = t.width.ToString() + "x" + t.height.ToString(); - if (QualitySettings.desiredColorSpace == ColorSpace.Linear) - info += " " + TextureUtil.GetTextureColorSpaceString(t); - bool showSize = true; bool isPackedSprite = textureImporter && textureImporter.qualifiesForSpritePacking; bool isNormalmap = IsNormalMap(t); diff --git a/Editor/Mono/ObjectListArea.cs b/Editor/Mono/ObjectListArea.cs index e44211dfb3..81c2306173 100644 --- a/Editor/Mono/ObjectListArea.cs +++ b/Editor/Mono/ObjectListArea.cs @@ -1490,7 +1490,6 @@ int GetMaxNumVisibleItems() return g.m_Grid.GetMaxVisibleItems(m_TotalRect.height); } - Assert.IsTrue(false, "Unhandled group"); return 0; } diff --git a/Editor/Mono/SceneHierarchy.cs b/Editor/Mono/SceneHierarchy.cs index 8eabfa19e8..60fa0a1910 100644 --- a/Editor/Mono/SceneHierarchy.cs +++ b/Editor/Mono/SceneHierarchy.cs @@ -580,7 +580,7 @@ public void OnGUI(Rect rect) float searchPathHeight = DoSearchResultPathGUI(); DoTreeView(searchPathHeight); - DoSceneVisibilityBackgroundOverflow(); + DoSceneVisibilityBackgroundOverflow(searchPathHeight); DoPingRequest(); ExecuteCommands(); @@ -745,11 +745,12 @@ void OnEvent() // Tree view item handle their own scene visibility background. // So the background doesn't stop if we don't have enough item to fill the entire tree view rect, we draw the background in the unused space. - private void DoSceneVisibilityBackgroundOverflow() + private void DoSceneVisibilityBackgroundOverflow(float reservedFooterSpace) { Vector2 sizeTaken = treeView.gui.GetTotalSize(); Rect rectWithNoRows = treeViewRect; rectWithNoRows.yMin += sizeTaken.y; + rectWithNoRows.height -= reservedFooterSpace; SceneVisibilityHierarchyGUI.DrawBackground(rectWithNoRows); } diff --git a/Editor/Mono/SceneView/SceneView.cs b/Editor/Mono/SceneView/SceneView.cs index 2a0ba82620..fff8c31fb0 100644 --- a/Editor/Mono/SceneView/SceneView.cs +++ b/Editor/Mono/SceneView/SceneView.cs @@ -106,6 +106,16 @@ public static SceneView lastActiveSceneView [SerializeField] bool m_ShowContextualTools; + static void OnSelectedObjectWasDestroyed(int unused) + { + s_ActiveEditors = null; + } + + static void OnEditorTrackerRebuilt() + { + s_ActiveEditors = null; + } + static Editor[] s_ActiveEditors; internal bool displayToolModes @@ -871,7 +881,8 @@ public override void OnEnable() EditorApplication.modifierKeysChanged += RepaintAll; // Because we show handles on shift SceneVisibilityManager.hiddenContentChanged += HiddenContentChanged; SceneVisibilityManager.currentStageIsolated += CurrentStageIsolated; - ActiveEditorTracker.editorTrackerRebuilt += () => { s_ActiveEditors = null; }; + ActiveEditorTracker.editorTrackerRebuilt += OnEditorTrackerRebuilt; + Selection.selectedObjectWasDestroyed += OnSelectedObjectWasDestroyed; m_DraggingLockedState = DraggingLockedState.NotDragging; @@ -972,6 +983,8 @@ public override void OnDisable() EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; SceneVisibilityManager.hiddenContentChanged -= HiddenContentChanged; SceneVisibilityManager.currentStageIsolated -= CurrentStageIsolated; + ActiveEditorTracker.editorTrackerRebuilt -= OnEditorTrackerRebuilt; + Selection.selectedObjectWasDestroyed -= OnSelectedObjectWasDestroyed; if (m_Camera) DestroyImmediate(m_Camera.gameObject, true); diff --git a/Editor/Mono/SceneVisibilityManager.cs b/Editor/Mono/SceneVisibilityManager.cs index cb2f79dc2c..fa0b491088 100644 --- a/Editor/Mono/SceneVisibilityManager.cs +++ b/Editor/Mono/SceneVisibilityManager.cs @@ -229,7 +229,7 @@ internal static bool IsEntireSceneHidden(Scene scene) scene.GetRootGameObjects(m_RootBuffer); foreach (GameObject root in m_RootBuffer) { - if (!IsGameObjectHidden(root) || !AreAllChildrenHidden(root)) + if (!IsGameObjectHidden(root) || root.transform.childCount > 0 && !AreAllChildrenHidden(root)) return false; } diff --git a/Editor/Mono/SyncRiderProject.cs b/Editor/Mono/SyncRiderProject.cs index d65f4f125d..ab7179e363 100644 --- a/Editor/Mono/SyncRiderProject.cs +++ b/Editor/Mono/SyncRiderProject.cs @@ -199,7 +199,7 @@ static string[] CollectPathsFromToolbox( var json = File.ReadAllText(a).Replace("active-application", "active_application"); var toolbox = ToolboxInstallData.FromJson(json); var builds = toolbox.active_application.builds; - if (builds.Any()) + if (builds != null && builds.Any()) { var build = builds.First(); var folder = Path.Combine(Path.Combine(channelDir, build), dirName); @@ -207,6 +207,17 @@ static string[] CollectPathsFromToolbox( return new[] {Path.Combine(folder, searchPattern)}; return new DirectoryInfo(folder).GetDirectories(searchPattern).Select(f => f.FullName); } + + // new toolbox format doesn't have active-application block, so return all found Rider installations + return Directory.GetDirectories(channelDir) + .SelectMany(b => + { + var folder = Path.Combine(b, dirName); + if (!isMac) + return new[] {Path.Combine(folder, searchPattern)}; + return new DirectoryInfo(folder).GetDirectories(searchPattern).Select(f => f.FullName); + }) + .Where(File.Exists).ToArray(); } catch (Exception e) { diff --git a/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs index b9e3d64df0..9b9173438d 100644 --- a/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs +++ b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs @@ -611,7 +611,7 @@ private string ProjectHeader(MonoIsland island, if (PlayerSettingsEditor.IsLatestApiCompatibility(island._api_compatibility_level)) { - targetframeworkversion = "v4.7.2"; + targetframeworkversion = "v4.7.1"; targetLanguageVersion = "latest"; cscToolPath = Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "RoslynScripts"); diff --git a/Modules/IMGUI/GUI.cs b/Modules/IMGUI/GUI.cs index 1f0944aec5..a84741c7ca 100644 --- a/Modules/IMGUI/GUI.cs +++ b/Modules/IMGUI/GUI.cs @@ -1112,21 +1112,14 @@ private static Rect[] CalcMouseRects(Rect position, GUIContent[] contents, int x else retval[i] = currentStyle.margin.Add(new Rect(xPos, yPos, w, elemHeight)); - // Correct way to get the rounded width: - retval[i].width = Mathf.Round(retval[i].xMax) - Mathf.Round(retval[i].x); - // Round the position *after* the width has been rounded: - retval[i].x = Mathf.Round(retval[i].x); - - // Don't round xPos here. If rounded, the right edge of this rect may - // not line up correctly with the left edge of the next, - // plus it can cause cumulative rounding errors. - // (See case 366967) + //we round the values to the dpi-aware pixel grid + retval[i] = GUIUtility.AlignRectToDevice(retval[i]); GUIStyle nextStyle = midStyle; if (i == count - 2 || i == xCount - 2) nextStyle = lastStyle; - xPos += w + Mathf.Max(currentStyle.margin.right, nextStyle.margin.left); + xPos = retval[i].xMax + Mathf.Max(currentStyle.margin.right, nextStyle.margin.left); x++; if (x >= xCount) diff --git a/Modules/PackageManager/Editor/Managed/Requests/ListRequest.cs b/Modules/PackageManager/Editor/Managed/Requests/ListRequest.cs index 05e0ae19de..5e22d5dfc8 100644 --- a/Modules/PackageManager/Editor/Managed/Requests/ListRequest.cs +++ b/Modules/PackageManager/Editor/Managed/Requests/ListRequest.cs @@ -26,7 +26,10 @@ internal ListRequest(long operationId, NativeStatusCode initialStatus) protected override PackageCollection GetResult() { var operationStatus = NativeClient.GetListOperationData(Id); - return new PackageCollection(operationStatus.packageList, operationStatus.error); + var packageList = operationStatus.packageList + .Select(p => (PackageInfo)p) + .Where(p => p.type != ShimPackageType); + return new PackageCollection(packageList, operationStatus.error); } } } diff --git a/Modules/PackageManager/Editor/Managed/Requests/Request.cs b/Modules/PackageManager/Editor/Managed/Requests/Request.cs index d9d0f5fdbb..1d162cffa1 100644 --- a/Modules/PackageManager/Editor/Managed/Requests/Request.cs +++ b/Modules/PackageManager/Editor/Managed/Requests/Request.cs @@ -12,6 +12,8 @@ namespace UnityEditor.PackageManager.Requests /// public abstract class Request : ISerializationCallbackReceiver { + internal const string ShimPackageType = "shim"; + /// /// Note: This property is there to workaround the serializer /// that does not know how to handle null values diff --git a/Modules/PackageManager/Editor/Managed/Requests/SearchRequest.cs b/Modules/PackageManager/Editor/Managed/Requests/SearchRequest.cs index 2cf20a4166..6813da3836 100644 --- a/Modules/PackageManager/Editor/Managed/Requests/SearchRequest.cs +++ b/Modules/PackageManager/Editor/Managed/Requests/SearchRequest.cs @@ -40,7 +40,10 @@ internal SearchRequest(long operationId, NativeStatusCode initialStatus, string protected override PackageInfo[] GetResult() { - return NativeClient.GetSearchOperationData(Id).Select(p => (PackageInfo)p).ToArray(); + return NativeClient.GetSearchOperationData(Id) + .Select(p => (PackageInfo)p) + .Where(p => p.type != ShimPackageType) + .ToArray(); } } } diff --git a/Modules/Terrain/Public/PaintContext.cs b/Modules/Terrain/Public/PaintContext.cs index 21b1eb4b5d..b4ec3e364c 100644 --- a/Modules/Terrain/Public/PaintContext.cs +++ b/Modules/Terrain/Public/PaintContext.cs @@ -19,9 +19,9 @@ public class PaintContext public Vector2 pixelSize { get; } // size of a paint context pixel in object/terrain/world space // initialized by CreateRenderTargets() - public RenderTexture sourceRenderTexture { get { return m_SourceRenderTexture; } } // the original data - public RenderTexture destinationRenderTexture { get { return m_DestinationRenderTexture; } } // the modified data (you render to this) - public RenderTexture oldRenderTexture { get { return m_OldRenderTexture; } } // active render texture at the time CreateRenderTargets() is called, restored on Cleanup() + public RenderTexture sourceRenderTexture { get; private set; } // the original data + public RenderTexture destinationRenderTexture { get; private set; } // the modified data (you render to this) + public RenderTexture oldRenderTexture { get; private set; } // active render texture at the time CreateRenderTargets() is called, restored on Cleanup() public int terrainCount { get { return m_TerrainTiles.Count; } } public Terrain GetTerrain(int terrainIndex) @@ -40,26 +40,40 @@ public RectInt GetClippedPixelRectInRenderTexturePixels(int terrainIndex) } // initialized by constructor - private List m_TerrainTiles; // all terrain tiles touched by this paint context + private List m_TerrainTiles; // all terrain tiles touched by this paint context - // initialized by CreateRenderTargets() - private RenderTexture m_SourceRenderTexture; - private RenderTexture m_DestinationRenderTexture; - private RenderTexture m_OldRenderTexture; - - internal class TerrainTile + internal struct TerrainTile { - public TerrainTile() {} - public TerrainTile(Terrain newTerrain, int tileOriginPixelsX, int tileOriginPixelsY) { terrain = newTerrain; tileOriginPixels = new Vector2Int(tileOriginPixelsX, tileOriginPixelsY); } - public Terrain terrain; // the terrain object for this tile public Vector2Int tileOriginPixels; // coordinates of this terrain tile in originTerrain target texture pixels public RectInt clippedLocalPixels; // the tile pixels touched by this PaintContext (in local target texture pixels) public RectInt clippedPCPixels; // the tile pixels touched by this PaintContext (in PaintContext/source/destRenderTexture pixels) - public int mapIndex; // for splatmap operations, the splatmap index on this Terrain containing the desired TerrainLayer weight - public int channelIndex; // for splatmap operations, the channel on the splatmap containing the desired TerrainLayer weight + public int mapIndex; // for splatmap operations, the splatmap index on this Terrain containing the desired TerrainLayer weight + public int channelIndex; // for splatmap operations, the channel on the splatmap containing the desired TerrainLayer weight + + public static TerrainTile Make(Terrain terrain, int tileOriginPixelsX, int tileOriginPixelsY, RectInt pixelRect, int targetTextureWidth, int targetTextureHeight) + { + var tile = new TerrainTile() + { + terrain = terrain, + tileOriginPixels = new Vector2Int(tileOriginPixelsX, tileOriginPixelsY), + clippedLocalPixels = new RectInt() + { + x = Mathf.Max(0, pixelRect.x - tileOriginPixelsX), + y = Mathf.Max(0, pixelRect.y - tileOriginPixelsY), + xMax = Mathf.Min(targetTextureWidth, pixelRect.xMax - tileOriginPixelsX), + yMax = Mathf.Min(targetTextureHeight, pixelRect.yMax - tileOriginPixelsY) + } + }; + tile.clippedPCPixels = new RectInt( + tile.clippedLocalPixels.x + tile.tileOriginPixels.x - pixelRect.x, + tile.clippedLocalPixels.y + tile.tileOriginPixels.y - pixelRect.y, + tile.clippedLocalPixels.width, + tile.clippedLocalPixels.height); + return tile; + } } @@ -86,7 +100,6 @@ public PaintContext(Terrain terrain, RectInt pixelRect, int targetTextureWidth, terrainData.size.z / (targetTextureHeight - 1.0f)); FindTerrainTiles(); - ClipTerrainTiles(); } public static PaintContext CreateFromBounds(Terrain terrain, Rect boundsInTerrainSpace, int inputTextureWidth, int inputTextureHeight, int extraBorderPixels = 0) @@ -124,8 +137,7 @@ internal void FindTerrainTiles() } // add center tile - TerrainTile tile = new TerrainTile(originTerrain, 0, 0); - m_TerrainTiles.Add(tile); + m_TerrainTiles.Add(TerrainTile.Make(originTerrain, 0, 0, pixelRect, targetTextureWidth, targetTextureHeight)); // add horizontal and vertical neighbors Terrain horiz = null; @@ -159,8 +171,7 @@ internal void FindTerrainTiles() if (horiz) { - tile = new TerrainTile(horiz, horizTileDelta * (targetTextureWidth - 1), 0); - m_TerrainTiles.Add(tile); + m_TerrainTiles.Add(TerrainTile.Make(horiz, horizTileDelta * (targetTextureWidth - 1), 0, pixelRect, targetTextureWidth, targetTextureHeight)); // add corner, if we have a link if (wantTop && horiz.topNeighbor) @@ -171,8 +182,7 @@ internal void FindTerrainTiles() if (vert) { - tile = new PaintContext.TerrainTile(vert, 0, vertTileDelta * (targetTextureHeight - 1)); - m_TerrainTiles.Add(tile); + m_TerrainTiles.Add(TerrainTile.Make(vert, 0, vertTileDelta * (targetTextureHeight - 1), pixelRect, targetTextureWidth, targetTextureHeight)); // add corner, if we have a link if (wantLeft && vert.leftNeighbor) @@ -182,51 +192,27 @@ internal void FindTerrainTiles() } if (cornerTerrain != null) - { - tile = new TerrainTile(cornerTerrain, horizTileDelta * (targetTextureWidth - 1), vertTileDelta * (targetTextureHeight - 1)); - m_TerrainTiles.Add(tile); - } - } - - internal void ClipTerrainTiles() - { - for (int i = 0; i < m_TerrainTiles.Count; i++) - { - TerrainTile tile = m_TerrainTiles[i]; - tile.clippedLocalPixels = new RectInt(); - tile.clippedLocalPixels.x = Mathf.Max(0, pixelRect.x - tile.tileOriginPixels.x); - tile.clippedLocalPixels.y = Mathf.Max(0, pixelRect.y - tile.tileOriginPixels.y); - tile.clippedLocalPixels.xMax = Mathf.Min(targetTextureWidth, pixelRect.xMax - tile.tileOriginPixels.x); - tile.clippedLocalPixels.yMax = Mathf.Min(targetTextureHeight, pixelRect.yMax - tile.tileOriginPixels.y); - - tile.clippedPCPixels = new RectInt( - tile.clippedLocalPixels.x + tile.tileOriginPixels.x - pixelRect.x, - tile.clippedLocalPixels.y + tile.tileOriginPixels.y - pixelRect.y, - tile.clippedLocalPixels.width, - tile.clippedLocalPixels.height); - } + m_TerrainTiles.Add(TerrainTile.Make(cornerTerrain, horizTileDelta * (targetTextureWidth - 1), vertTileDelta * (targetTextureHeight - 1), pixelRect, targetTextureWidth, targetTextureHeight)); } public void CreateRenderTargets(RenderTextureFormat colorFormat) { - m_SourceRenderTexture = RenderTexture.GetTemporary(pixelRect.width, pixelRect.height, 0, colorFormat, RenderTextureReadWrite.Linear); - m_DestinationRenderTexture = RenderTexture.GetTemporary(pixelRect.width, pixelRect.height, 0, colorFormat, RenderTextureReadWrite.Linear); - m_SourceRenderTexture.wrapMode = TextureWrapMode.Clamp; - m_SourceRenderTexture.filterMode = FilterMode.Point; - m_OldRenderTexture = RenderTexture.active; + sourceRenderTexture = RenderTexture.GetTemporary(pixelRect.width, pixelRect.height, 0, colorFormat, RenderTextureReadWrite.Linear); + destinationRenderTexture = RenderTexture.GetTemporary(pixelRect.width, pixelRect.height, 0, colorFormat, RenderTextureReadWrite.Linear); + sourceRenderTexture.wrapMode = TextureWrapMode.Clamp; + sourceRenderTexture.filterMode = FilterMode.Point; + oldRenderTexture = RenderTexture.active; } public void Cleanup(bool restoreRenderTexture = true) { if (restoreRenderTexture) - { - RenderTexture.active = m_OldRenderTexture; - } - RenderTexture.ReleaseTemporary(m_SourceRenderTexture); - RenderTexture.ReleaseTemporary(m_DestinationRenderTexture); - m_SourceRenderTexture = null; - m_DestinationRenderTexture = null; - m_OldRenderTexture = null; + RenderTexture.active = oldRenderTexture; + RenderTexture.ReleaseTemporary(sourceRenderTexture); + RenderTexture.ReleaseTemporary(destinationRenderTexture); + sourceRenderTexture = null; + destinationRenderTexture = null; + oldRenderTexture = null; } public void GatherHeightmap() @@ -271,7 +257,8 @@ public void GatherHeightmap() public void ScatterHeightmap(string editorUndoName) { - Material blitMaterial = TerrainPaintUtility.GetBlitMaterial(); + var oldRT = RenderTexture.active; + RenderTexture.active = destinationRenderTexture; for (int i = 0; i < m_TerrainTiles.Count; i++) { @@ -279,32 +266,19 @@ public void ScatterHeightmap(string editorUndoName) if (terrainTile.clippedLocalPixels.width == 0 || terrainTile.clippedLocalPixels.height == 0) continue; - RenderTexture heightmap = terrainTile.terrain.terrainData.heightmapTexture; - if ((heightmap.width != targetTextureWidth) || (heightmap.height != targetTextureHeight)) + var terrainData = terrainTile.terrain.terrainData; + if ((terrainData.heightmapResolution != targetTextureWidth) || (terrainData.heightmapResolution != targetTextureHeight)) { Debug.LogWarning("PaintContext heightmap operations must use the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); continue; } - if (onTerrainTileBeforePaint != null) - onTerrainTileBeforePaint(terrainTile, ToolAction.PaintHeightmap, editorUndoName); - - RenderTexture.active = heightmap; - GL.PushMatrix(); - GL.LoadPixelMatrix(0, heightmap.width, 0, heightmap.height); - - destinationRenderTexture.filterMode = FilterMode.Point; - - blitMaterial.SetTexture("_MainTex", destinationRenderTexture); - blitMaterial.SetPass(0); - - TerrainPaintUtility.DrawQuad(terrainTile.clippedLocalPixels, terrainTile.clippedPCPixels, destinationRenderTexture); - - GL.PopMatrix(); - - terrainTile.terrain.terrainData.UpdateDirtyRegion(terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y, terrainTile.clippedLocalPixels.width, terrainTile.clippedLocalPixels.height, !terrainTile.terrain.drawInstanced); + onTerrainTileBeforePaint?.Invoke(terrainTile, ToolAction.PaintHeightmap, editorUndoName); + terrainData.CopyActiveRenderTextureToHeightmap(terrainTile.clippedPCPixels, terrainTile.clippedLocalPixels.min, terrainTile.terrain.drawInstanced ? TerrainHeightmapSyncControl.None : TerrainHeightmapSyncControl.HeightOnly); OnTerrainPainted(terrainTile, ToolAction.PaintHeightmap); } + + RenderTexture.active = oldRT; } public void GatherNormals() @@ -353,10 +327,6 @@ public void GatherAlphamap(TerrainLayer inputLayer, bool addLayerIfDoesntExist = if (inputLayer == null) return; - int terrainLayerIndex = TerrainPaintUtility.FindTerrainLayerIndex(originTerrain, inputLayer); - if (terrainLayerIndex == -1 && addLayerIfDoesntExist) - terrainLayerIndex = TerrainPaintUtility.AddTerrainLayer(originTerrain, inputLayer); - RenderTexture.active = sourceRenderTexture; GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); GL.PushMatrix(); @@ -381,13 +351,15 @@ public void GatherAlphamap(TerrainLayer inputLayer, bool addLayerIfDoesntExist = terrainTile.clippedLocalPixels.height = 0; terrainTile.clippedPCPixels.width = 0; terrainTile.clippedPCPixels.height = 0; + m_TerrainTiles[i] = terrainTile; continue; } tileLayerIndex = TerrainPaintUtility.AddTerrainLayer(terrainTile.terrain, inputLayer); } - terrainTile.mapIndex = tileLayerIndex >> 2; - terrainTile.channelIndex = tileLayerIndex & 0x3; + terrainTile.mapIndex = tileLayerIndex / 4; + terrainTile.channelIndex = tileLayerIndex % 4; + m_TerrainTiles[i] = terrainTile; Texture sourceTexture = TerrainPaintUtility.GetTerrainAlphaMapChecked(terrainTile.terrain, terrainTile.mapIndex); if ((sourceTexture.width != targetTextureWidth) || (sourceTexture.height != targetTextureHeight)) @@ -421,21 +393,20 @@ public void ScatterAlphamap(string editorUndoName) Material copyTerrainLayerMaterial = TerrainPaintUtility.GetCopyTerrainLayerMaterial(); + var rtdesc = new RenderTextureDescriptor(destinationRenderTexture.width, destinationRenderTexture.height, RenderTextureFormat.ARGB32); + rtdesc.sRGB = false; + rtdesc.useMipMap = false; + rtdesc.autoGenerateMips = false; + RenderTexture destTarget = RenderTexture.GetTemporary(rtdesc); + RenderTexture.active = destTarget; + for (int i = 0; i < m_TerrainTiles.Count; i++) { TerrainTile terrainTile = m_TerrainTiles[i]; if (terrainTile.clippedLocalPixels.width == 0 || terrainTile.clippedLocalPixels.height == 0) continue; - if (onTerrainTileBeforePaint != null) - onTerrainTileBeforePaint(terrainTile, ToolAction.PaintTexture, editorUndoName); - - var rtdesc = new RenderTextureDescriptor(destinationRenderTexture.width, destinationRenderTexture.height, RenderTextureFormat.ARGB32); - rtdesc.sRGB = false; - rtdesc.useMipMap = false; - rtdesc.autoGenerateMips = false; - RenderTexture destTarget = RenderTexture.GetTemporary(rtdesc); - RenderTexture.active = destTarget; + onTerrainTileBeforePaint?.Invoke(terrainTile, ToolAction.PaintTexture, editorUndoName); RectInt writeRect = terrainTile.clippedPCPixels; @@ -449,11 +420,11 @@ public void ScatterAlphamap(string editorUndoName) int mapIndex = terrainTile.mapIndex; int channelIndex = terrainTile.channelIndex; - Texture2D sourceTexTargetChannel = terrainTile.terrain.terrainData.alphamapTextures[mapIndex]; - - for (int j = 0; j < terrainTile.terrain.terrainData.alphamapTextureCount; j++) + var terrainData = terrainTile.terrain.terrainData; + var alphamapTextures = terrainData.alphamapTextures; + for (int j = 0; j < alphamapTextures.Length; j++) { - Texture2D sourceTex = terrainTile.terrain.terrainData.alphamapTextures[j]; + Texture2D sourceTex = alphamapTextures[j]; if ((sourceTex.width != targetTextureWidth) || (sourceTex.height != targetTextureHeight)) { Debug.LogWarning("PaintContext alphamap operations must use the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); @@ -468,7 +439,7 @@ public void ScatterAlphamap(string editorUndoName) copyTerrainLayerMaterial.SetTexture("_MainTex", destinationRenderTexture); copyTerrainLayerMaterial.SetTexture("_OldAlphaMapTexture", sourceRenderTexture); - copyTerrainLayerMaterial.SetTexture("_OriginalTargetAlphaMap", sourceTexTargetChannel); + copyTerrainLayerMaterial.SetTexture("_OriginalTargetAlphaMap", alphamapTextures[mapIndex]); copyTerrainLayerMaterial.SetTexture("_AlphaMapTexture", sourceTex); copyTerrainLayerMaterial.SetVector("_LayerMask", j == mapIndex ? layerMasks[channelIndex] : Vector4.zero); @@ -497,46 +468,18 @@ public void ScatterAlphamap(string editorUndoName) GL.End(); GL.PopMatrix(); - if (TerrainPaintUtility.paintTextureUsesCopyTexture) - { - var rtdesc2 = new RenderTextureDescriptor(sourceTex.width, sourceTex.height, RenderTextureFormat.ARGB32); - rtdesc2.sRGB = false; - rtdesc2.useMipMap = true; - rtdesc2.autoGenerateMips = false; - var mips = RenderTexture.GetTemporary(rtdesc2); - if (!mips.IsCreated()) - mips.Create(); - - // Composes mip0 in a RT with full mipchain. - Graphics.CopyTexture(sourceTex, 0, 0, mips, 0, 0); - Graphics.CopyTexture(destTarget, 0, 0, writeRect.x, writeRect.y, writeRect.width, writeRect.height, mips, 0, 0, terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y); - mips.GenerateMips(); - - // Copy them into sourceTex. - Graphics.CopyTexture(mips, sourceTex); - - RenderTexture.ReleaseTemporary(mips); - } - else - { - GraphicsDeviceType deviceType = SystemInfo.graphicsDeviceType; - if (deviceType == GraphicsDeviceType.Metal || deviceType == GraphicsDeviceType.OpenGLCore) - sourceTex.ReadPixels(new Rect(writeRect.x, writeRect.y, writeRect.width, writeRect.height), terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y); - else - sourceTex.ReadPixels(new Rect(writeRect.x, destTarget.height - writeRect.y - writeRect.height, writeRect.width, writeRect.height), terrainTile.clippedLocalPixels.x, terrainTile.clippedLocalPixels.y); - sourceTex.Apply(); - } + terrainData.CopyActiveRenderTextureToTexture(TerrainData.AlphamapTextureName, j, writeRect, terrainTile.clippedLocalPixels.min, true); } - RenderTexture.active = null; - RenderTexture.ReleaseTemporary(destTarget); - OnTerrainPainted(terrainTile, ToolAction.PaintTexture); } + + RenderTexture.active = null; + RenderTexture.ReleaseTemporary(destTarget); } // Collects modified terrain so that we can update some deferred operations at the mouse up event - private class PaintedTerrain + private struct PaintedTerrain { public Terrain terrain; public ToolAction action; @@ -549,7 +492,9 @@ private static void OnTerrainPainted(PaintContext.TerrainTile tile, ToolAction a { if (tile.terrain == s_PaintedTerrain[i].terrain) { - s_PaintedTerrain[i].action |= action; + var pt = s_PaintedTerrain[i]; + pt.action |= action; + s_PaintedTerrain[i] = pt; return; } } @@ -561,32 +506,18 @@ public static void ApplyDelayedActions() for (int i = 0; i < s_PaintedTerrain.Count; ++i) { var pt = s_PaintedTerrain[i]; + var terrainData = pt.terrain.terrainData; + if (terrainData == null) + continue; if ((pt.action & ToolAction.PaintHeightmap) != 0) { - pt.terrain.ApplyDelayedHeightmapModification(); + terrainData.SyncHeightmap(); pt.terrain.editorRenderFlags = TerrainRenderFlags.All; } if ((pt.action & ToolAction.PaintTexture) != 0) { - var terrainData = pt.terrain.terrainData; - if (terrainData == null) - continue; terrainData.SetBaseMapDirty(); - if (TerrainPaintUtility.paintTextureUsesCopyTexture) - { - // pull the data from GPU to CPU - var rtdesc = new RenderTextureDescriptor(terrainData.alphamapResolution, terrainData.alphamapResolution, RenderTextureFormat.ARGB32); - rtdesc.sRGB = false; - rtdesc.useMipMap = false; - rtdesc.autoGenerateMips = false; - RenderTexture tmp = RenderTexture.GetTemporary(rtdesc); - for (int c = 0; c < terrainData.alphamapTextureCount; ++c) - { - Graphics.Blit(terrainData.alphamapTextures[c], tmp); - terrainData.alphamapTextures[c].ReadPixels(new Rect(0, 0, rtdesc.width, rtdesc.height), 0, 0, true); - } - RenderTexture.ReleaseTemporary(tmp); - } + terrainData.SyncTexture(TerrainData.AlphamapTextureName); } } diff --git a/Modules/Terrain/Public/Terrain.bindings.cs b/Modules/Terrain/Public/Terrain.bindings.cs index c6bbf77b3a..5c3292a420 100644 --- a/Modules/Terrain/Public/Terrain.bindings.cs +++ b/Modules/Terrain/Public/Terrain.bindings.cs @@ -21,6 +21,7 @@ public enum TerrainChangedFlags DelayedHeightmapUpdate = 4, FlushEverythingImmediately = 8, RemoveDirtyDetailsImmediately = 16, + HeightmapResolution = 32, WillBeDestroyed = 256, } @@ -137,7 +138,11 @@ public bool castShadows extern public float SampleHeight(Vector3 worldPosition); - extern public void ApplyDelayedHeightmapModification(); + [Obsolete("Use TerrainData.SyncHeightmap to notify all Terrain instances using the TerrainData.", false)] + public void ApplyDelayedHeightmapModification() + { + terrainData?.SyncHeightmap(); + } extern public void AddTreeInstance(TreeInstance instance); @@ -188,6 +193,19 @@ static public RenderTextureFormat heightmapRenderTextureFormat get { return GraphicsFormatUtility.GetRenderTextureFormat(heightmapFormat); } } + [StaticAccessor("Terrain", StaticAccessorType.DoubleColon)] + extern static public GraphicsFormat normalmapFormat { get; } + + static public TextureFormat normalmapTextureFormat + { + get { return GraphicsFormatUtility.GetTextureFormat(normalmapFormat); } + } + + static public RenderTextureFormat normalmapRenderTextureFormat + { + get { return GraphicsFormatUtility.GetRenderTextureFormat(normalmapFormat); } + } + extern public static Terrain activeTerrain { get; } extern public static void SetConnectivityDirty(); diff --git a/Modules/Terrain/Public/TerrainCallbacks.cs b/Modules/Terrain/Public/TerrainCallbacks.cs new file mode 100644 index 0000000000..93db70d139 --- /dev/null +++ b/Modules/Terrain/Public/TerrainCallbacks.cs @@ -0,0 +1,37 @@ +// Unity C# reference source +// Copyright (c) Unity Technologies. For terms of use, see +// https://unity3d.com/legal/licenses/Unity_Reference_Only_License + +using UnityEngine.Scripting; + +namespace UnityEngine.Experimental.TerrainAPI +{ + public static class TerrainCallbacks + { + public delegate void HeightmapChangedCallback(Terrain terrain, RectInt heightRegion, bool synched); + public delegate void TextureChangedCallback(Terrain terrain, string textureName, RectInt texelRegion, bool synched); + + public static event HeightmapChangedCallback heightmapChanged; + public static event TextureChangedCallback textureChanged; + + [RequiredByNativeCode] + internal static void InvokeHeightmapChangedCallback(TerrainData terrainData, RectInt heightRegion, bool synched) + { + if (heightmapChanged != null) + { + foreach (var user in terrainData.users) + heightmapChanged.Invoke(user, heightRegion, synched); + } + } + + [RequiredByNativeCode] + internal static void InvokeTextureChangedCallback(TerrainData terrainData, string textureName, RectInt texelRegion, bool synched) + { + if (textureChanged != null) + { + foreach (var user in terrainData.users) + textureChanged.Invoke(user, textureName, texelRegion, synched); + } + } + } +} diff --git a/Modules/Terrain/Public/TerrainData.GPUCopy.cs b/Modules/Terrain/Public/TerrainData.GPUCopy.cs new file mode 100644 index 0000000000..ccc315d3ce --- /dev/null +++ b/Modules/Terrain/Public/TerrainData.GPUCopy.cs @@ -0,0 +1,182 @@ +// Unity C# reference source +// Copyright (c) Unity Technologies. For terms of use, see +// https://unity3d.com/legal/licenses/Unity_Reference_Only_License + +using System; +using CopyTextureSupport = UnityEngine.Rendering.CopyTextureSupport; +using GraphicsDeviceType = UnityEngine.Rendering.GraphicsDeviceType; + +namespace UnityEngine +{ + partial class TerrainData + { + private static bool SupportsCopyTextureBetweenRTAndTexture + { + get + { + const CopyTextureSupport kRT2TexAndTex2RT = CopyTextureSupport.RTToTexture | CopyTextureSupport.TextureToRT; + return (SystemInfo.copyTextureSupport & kRT2TexAndTex2RT) == kRT2TexAndTex2RT; + } + } + + public void CopyActiveRenderTextureToHeightmap(RectInt sourceRect, Vector2Int dest, TerrainHeightmapSyncControl syncControl) + { + var source = RenderTexture.active; + if (source == null) + throw new InvalidOperationException("Active RenderTexture is null."); + + if (sourceRect.x < 0 || sourceRect.y < 0 || sourceRect.xMax > source.width || sourceRect.yMax > source.height) + throw new ArgumentOutOfRangeException("sourceRect"); + else if (dest.x < 0 || dest.x + sourceRect.width > heightmapResolution) + throw new ArgumentOutOfRangeException("dest.x"); + else if (dest.y < 0 || dest.y + sourceRect.height > heightmapResolution) + throw new ArgumentOutOfRangeException("dest.y"); + + Internal_CopyActiveRenderTextureToHeightmap(sourceRect, dest.x, dest.y, syncControl); + Experimental.TerrainAPI.TerrainCallbacks.InvokeHeightmapChangedCallback(this, new RectInt(dest.x, dest.y, sourceRect.width, sourceRect.height), syncControl == TerrainHeightmapSyncControl.HeightAndLod); + } + + public void DirtyHeightmapRegion(RectInt region, TerrainHeightmapSyncControl syncControl) + { + int resolution = heightmapResolution; + if (region.x < 0 || region.x >= resolution) + throw new ArgumentOutOfRangeException("region.x"); + else if (region.width <= 0 || region.xMax > resolution) + throw new ArgumentOutOfRangeException("region.width"); + if (region.y < 0 || region.y >= resolution) + throw new ArgumentOutOfRangeException("region.y"); + else if (region.height <= 0 || region.yMax > resolution) + throw new ArgumentOutOfRangeException("region.height"); + + Internal_DirtyHeightmapRegion(region.x, region.y, region.width, region.height, syncControl); + Experimental.TerrainAPI.TerrainCallbacks.InvokeHeightmapChangedCallback(this, region, syncControl == TerrainHeightmapSyncControl.HeightAndLod); + } + + public static string AlphamapTextureName => "alphamap"; + + public void CopyActiveRenderTextureToTexture(string textureName, int textureIndex, RectInt sourceRect, Vector2Int dest, bool allowDelayedCPUSync) + { + if (String.IsNullOrEmpty(textureName)) + throw new ArgumentNullException("textureName"); + + // TODO: Support generic terrain textures. + // For now the textureName should always equal to "alphamap". + if (textureName != AlphamapTextureName) + throw new ArgumentException($"Unrecognized terrain texture name: \"{textureName}\""); + + int textureCount = alphamapTextureCount; + if (textureIndex < 0 || textureIndex >= textureCount) + throw new ArgumentOutOfRangeException("textureIndex"); + + var source = RenderTexture.active; + if (source == null) + throw new InvalidOperationException("Active RenderTexture is null."); + + // TODO: Support generic terrain textures. + var dstTexture = GetAlphamapTexture(textureIndex); + int dstWidth = dstTexture.width; + int dstHeight = dstTexture.height; + + if (sourceRect.x < 0 || sourceRect.y < 0 || sourceRect.xMax > source.width || sourceRect.yMax > source.height) + throw new ArgumentOutOfRangeException("sourceRect"); + else if (dest.x < 0 || dest.x + sourceRect.width > dstWidth) + throw new ArgumentOutOfRangeException("dest.x"); + else if (dest.y < 0 || dest.y + sourceRect.height > dstHeight) + throw new ArgumentOutOfRangeException("dest.y"); + + // Delay synching back (using ReadPixels) if CopyTexture can be used. + // TODO: Checking the format compatibility is difficult as it varies by platforms. For instance copying between ARGB32 RT and RGBA32 Tex seems to be fine on all tested platforms... + allowDelayedCPUSync = allowDelayedCPUSync && SupportsCopyTextureBetweenRTAndTexture; + if (allowDelayedCPUSync) + { + if (dstTexture.mipmapCount > 1) + { + // Composes mip0 in a RT with full mipchain. + var tmp = RenderTexture.GetTemporary(new RenderTextureDescriptor(dstWidth, dstHeight, source.format) + { + sRGB = false, + useMipMap = true, + autoGenerateMips = false + }); + if (!tmp.IsCreated()) + tmp.Create(); + + Graphics.CopyTexture(dstTexture, 0, 0, tmp, 0, 0); + Graphics.CopyTexture(source, 0, 0, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height, tmp, 0, 0, dest.x, dest.y); + + // Generate the mips on the GPU + tmp.GenerateMips(); + + // Copy the full mipchain back to the alphamap texture + Graphics.CopyTexture(tmp, dstTexture); + + RenderTexture.ReleaseTemporary(tmp); + } + else + { + Graphics.CopyTexture(source, 0, 0, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height, dstTexture, 0, 0, dest.x, dest.y); + } + + // TODO: Support generic terrain textures. + Internal_MarkAlphamapDirtyRegion(textureIndex, dest.x, dest.y, sourceRect.width, sourceRect.height); + } + else + { + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal || !SystemInfo.graphicsUVStartsAtTop) + dstTexture.ReadPixels(new Rect(sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height), dest.x, dest.y); + else + dstTexture.ReadPixels(new Rect(sourceRect.x, source.height - sourceRect.yMax, sourceRect.width, sourceRect.height), dest.x, dest.y); + dstTexture.Apply(true); + + // TODO: Check if the texture is previously marked dirty? + // TODO: Support generic terrain textures. + Internal_ClearAlphamapDirtyRegion(textureIndex); + } + + Experimental.TerrainAPI.TerrainCallbacks.InvokeTextureChangedCallback(this, textureName, new RectInt(dest.x, dest.y, sourceRect.width, sourceRect.height), !allowDelayedCPUSync); + } + + public void DirtyTextureRegion(string textureName, RectInt region, bool allowDelayedCPUSync) + { + if (String.IsNullOrEmpty(textureName)) + throw new ArgumentNullException("textureName"); + + // TODO: Support generic terrain textures. + // For now the textureName should always equal to "alphamap". + if (textureName != AlphamapTextureName) + throw new ArgumentException($"Unrecognized terrain texture name: \"{textureName}\""); + + // TODO: Support generic terrain textures. + int resolution = alphamapResolution; + if (region.x < 0 || region.x >= resolution) + throw new ArgumentOutOfRangeException("region.x"); + else if (region.width <= 0 || region.xMax > resolution) + throw new ArgumentOutOfRangeException("region.width"); + if (region.y < 0 || region.y >= resolution) + throw new ArgumentOutOfRangeException("region.y"); + else if (region.height <= 0 || region.yMax > resolution) + throw new ArgumentOutOfRangeException("region.height"); + + // TODO: Support generic terrain textures. + Internal_MarkAlphamapDirtyRegion(-1, region.x, region.y, region.width, region.height); + + if (!allowDelayedCPUSync) + SyncTexture(textureName); + else + Experimental.TerrainAPI.TerrainCallbacks.InvokeTextureChangedCallback(this, textureName, region, false); + } + + public void SyncTexture(string textureName) + { + if (String.IsNullOrEmpty(textureName)) + throw new ArgumentNullException("textureName"); + + // TODO: Support generic terrain textures. + // For now the textureName should always equal to "alphamap". + if (textureName != AlphamapTextureName) + throw new ArgumentException($"Unrecognized terrain texture name: \"{textureName}\""); + + Internal_SyncAlphamaps(); + } + } +} diff --git a/Modules/Terrain/Public/TerrainData.bindings.cs b/Modules/Terrain/Public/TerrainData.bindings.cs index 6ac8939589..1f5bf89299 100644 --- a/Modules/Terrain/Public/TerrainData.bindings.cs +++ b/Modules/Terrain/Public/TerrainData.bindings.cs @@ -218,6 +218,14 @@ public struct PatchExtents public float max { get { return m_max; } set { m_max = value; } } } + // Must Match Heightmap::SyncControl + public enum TerrainHeightmapSyncControl + { + None = 0, + HeightOnly, + HeightAndLod + } + [NativeHeader("TerrainScriptingClasses.h")] [NativeHeader("Modules/Terrain/Public/TerrainDataScriptingInterface.h")] [UsedByNativeCode] @@ -263,8 +271,11 @@ public TerrainData() [FreeFunction(k_ScriptingInterfacePrefix + "Create")] extern private static void Internal_Create([Writable] TerrainData terrainData); - extern public void UpdateDirtyRegion(int x, int y, int width, int height, bool syncHeightmapTextureImmediately); - + [Obsolete("Please use DirtyHeightmapRegion instead.", false)] + public void UpdateDirtyRegion(int x, int y, int width, int height, bool syncHeightmapTextureImmediately) + { + DirtyHeightmapRegion(new RectInt(x, y, width, height), syncHeightmapTextureImmediately ? TerrainHeightmapSyncControl.HeightOnly : TerrainHeightmapSyncControl.None); + } extern public int heightmapWidth { @@ -546,7 +557,7 @@ public TreeInstance[] treeInstances set { - Internal_SetTreeInstances(value); + SetTreeInstances(value, false); } } @@ -554,7 +565,7 @@ public TreeInstance[] treeInstances extern private TreeInstance[] Internal_GetTreeInstances(); [FreeFunction(k_ScriptingInterfacePrefix + "SetTreeInstances", HasExplicitThis = true)] - extern private void Internal_SetTreeInstances([NotNull] TreeInstance[] instances); + extern public void SetTreeInstances([NotNull] TreeInstance[] instances, bool snapToHeightmap); public TreeInstance GetTreeInstance(int index) { @@ -589,9 +600,6 @@ extern public TreePrototype[] treePrototypes [NativeName(k_TreeDatabasePrefix + "RemoveTreePrototype")] extern internal void RemoveTreePrototype(int index); - [NativeName(k_TreeDatabasePrefix + "RecalculateTreePositions")] - extern internal void RecalculateTreePositions(); - [NativeName(k_DetailDatabasePrefix + "RemoveDetailPrototype")] extern internal void RemoveDetailPrototype(int index); @@ -739,5 +747,28 @@ extern public TerrainLayer[] terrainLayers [NativeName(k_TreeDatabasePrefix + "RemoveTrees")] extern internal int RemoveTrees(Vector2 position, float radius, int prototypeIndex); + + [NativeName(k_HeightmapPrefix + "CopyFromActiveRenderTexture")] + private extern void Internal_CopyActiveRenderTextureToHeightmap(RectInt rect, int destX, int destY, TerrainHeightmapSyncControl syncControl); + + [NativeName(k_HeightmapPrefix + "DirtyRegion")] + private extern void Internal_DirtyHeightmapRegion(int x, int y, int width, int height, TerrainHeightmapSyncControl syncControl); + + [NativeName(k_HeightmapPrefix + "SyncGPUModifications")] + public extern void SyncHeightmap(); + + [NativeName(k_SplatDatabasePrefix + "MarkDirtyRegion")] + private extern void Internal_MarkAlphamapDirtyRegion(int alphamapIndex, int x, int y, int width, int height); + + [NativeName(k_SplatDatabasePrefix + "ClearDirtyRegion")] + private extern void Internal_ClearAlphamapDirtyRegion(int alphamapIndex); + + [NativeName(k_SplatDatabasePrefix + "SyncGPUModifications")] + private extern void Internal_SyncAlphamaps(); + + internal extern Terrain[] users + { + get; + } } } diff --git a/Modules/Terrain/Public/TerrainPaintUtility.cs b/Modules/Terrain/Public/TerrainPaintUtility.cs index 2e74aba5c3..421178af85 100644 --- a/Modules/Terrain/Public/TerrainPaintUtility.cs +++ b/Modules/Terrain/Public/TerrainPaintUtility.cs @@ -126,9 +126,9 @@ internal static bool paintTextureUsesCopyTexture } } - static PaintContext InitializePaintContext(Terrain terrain, Texture target, RenderTextureFormat pcFormat, Rect boundsInTerrainSpace, int extraBorderPixels = 0) + internal static PaintContext InitializePaintContext(Terrain terrain, int targetWidth, int targetHeight, RenderTextureFormat pcFormat, Rect boundsInTerrainSpace, int extraBorderPixels = 0) { - PaintContext ctx = PaintContext.CreateFromBounds(terrain, boundsInTerrainSpace, target.width, target.height, extraBorderPixels); + PaintContext ctx = PaintContext.CreateFromBounds(terrain, boundsInTerrainSpace, targetWidth, targetHeight, extraBorderPixels); ctx.CreateRenderTargets(pcFormat); return ctx; } @@ -140,8 +140,8 @@ public static void ReleaseContextResources(PaintContext ctx) public static PaintContext BeginPaintHeightmap(Terrain terrain, Rect boundsInTerrainSpace, int extraBorderPixels = 0) { - RenderTexture rt = terrain.terrainData.heightmapTexture; - PaintContext ctx = InitializePaintContext(terrain, rt, rt.format, boundsInTerrainSpace, extraBorderPixels); + int heightmapResolution = terrain.terrainData.heightmapResolution; + PaintContext ctx = InitializePaintContext(terrain, heightmapResolution, heightmapResolution, Terrain.heightmapRenderTextureFormat, boundsInTerrainSpace, extraBorderPixels); ctx.GatherHeightmap(); return ctx; } @@ -154,8 +154,8 @@ public static void EndPaintHeightmap(PaintContext ctx, string editorUndoName) public static PaintContext CollectNormals(Terrain terrain, Rect boundsInTerrainSpace, int extraBorderPixels = 0) { - RenderTexture rt = terrain.normalmapTexture; - PaintContext ctx = InitializePaintContext(terrain, rt, rt.format, boundsInTerrainSpace, extraBorderPixels); + int heightmapResolution = terrain.terrainData.heightmapResolution; + PaintContext ctx = InitializePaintContext(terrain, heightmapResolution, heightmapResolution, Terrain.normalmapRenderTextureFormat, boundsInTerrainSpace, extraBorderPixels); ctx.GatherNormals(); return ctx; } @@ -165,14 +165,9 @@ public static PaintContext BeginPaintTexture(Terrain terrain, Rect boundsInTerra if (inputLayer == null) return null; - int terrainLayerIndex = FindTerrainLayerIndex(terrain, inputLayer); - if (terrainLayerIndex == -1) - terrainLayerIndex = AddTerrainLayer(terrain, inputLayer); - - Texture2D inputTexture = GetTerrainAlphaMapChecked(terrain, terrainLayerIndex >> 2); - - PaintContext ctx = InitializePaintContext(terrain, inputTexture, RenderTextureFormat.R8, boundsInTerrainSpace, extraBorderPixels); - ctx.GatherAlphamap(inputLayer); + int resolution = terrain.terrainData.alphamapResolution; + PaintContext ctx = InitializePaintContext(terrain, resolution, resolution, RenderTextureFormat.R8, boundsInTerrainSpace, extraBorderPixels); + ctx.GatherAlphamap(inputLayer, true); return ctx; } @@ -185,18 +180,18 @@ public static void EndPaintTexture(PaintContext ctx, string editorUndoName) // materials public static Material GetBlitMaterial() { - if (!m_BlitMaterial) - m_BlitMaterial = new Material(Shader.Find("Hidden/BlitCopy")); + if (!s_BlitMaterial) + s_BlitMaterial = new Material(Shader.Find("Hidden/BlitCopy")); - return m_BlitMaterial; + return s_BlitMaterial; } public static Material GetCopyTerrainLayerMaterial() { - if (!m_CopyTerrainLayerMaterial) - m_CopyTerrainLayerMaterial = new Material(Shader.Find("Hidden/TerrainEngine/TerrainLayerUtils")); + if (!s_CopyTerrainLayerMaterial) + s_CopyTerrainLayerMaterial = new Material(Shader.Find("Hidden/TerrainEngine/TerrainLayerUtils")); - return m_CopyTerrainLayerMaterial; + return s_CopyTerrainLayerMaterial; } internal static void DrawQuad(RectInt destinationPixels, RectInt sourcePixels, Texture sourceTexture) @@ -240,14 +235,15 @@ public static Texture2D GetTerrainAlphaMapChecked(Terrain terrain, int mapIndex) if (mapIndex >= terrain.terrainData.alphamapTextureCount) throw new System.ArgumentException("Trying to access out-of-bounds terrain alphamap information."); - return terrain.terrainData.alphamapTextures[mapIndex]; + return terrain.terrainData.GetAlphamapTexture(mapIndex); } static public int FindTerrainLayerIndex(Terrain terrain, TerrainLayer inputLayer) { - for (int i = 0; i < terrain.terrainData.terrainLayers.Length; i++) + var terrainLayers = terrain.terrainData.terrainLayers; + for (int i = 0; i < terrainLayers.Length; i++) { - if (terrain.terrainData.terrainLayers[i] == inputLayer) + if (terrainLayers[i] == inputLayer) return i; } return -1; @@ -255,17 +251,18 @@ static public int FindTerrainLayerIndex(Terrain terrain, TerrainLayer inputLayer internal static int AddTerrainLayer(Terrain terrain, TerrainLayer inputLayer) { - int newIndex = terrain.terrainData.terrainLayers.Length; - var newarray = new TerrainLayer[newIndex + 1]; - System.Array.Copy(terrain.terrainData.terrainLayers, 0, newarray, 0, newIndex); - newarray[newIndex] = inputLayer; - terrain.terrainData.terrainLayers = newarray; + var oldArray = terrain.terrainData.terrainLayers; + int newIndex = oldArray.Length; + var newArray = new TerrainLayer[newIndex + 1]; + Array.Copy(oldArray, 0, newArray, 0, newIndex); + newArray[newIndex] = inputLayer; + terrain.terrainData.terrainLayers = newArray; return newIndex; } //-- - static Material m_BlitMaterial = null; - static Material m_CopyTerrainLayerMaterial = null; + static Material s_BlitMaterial = null; + static Material s_CopyTerrainLayerMaterial = null; } } diff --git a/Modules/TerrainEditor/PaintTools/CreateTerrainTool.cs b/Modules/TerrainEditor/PaintTools/CreateTerrainTool.cs index 28410aa638..1072bd9b58 100644 --- a/Modules/TerrainEditor/PaintTools/CreateTerrainTool.cs +++ b/Modules/TerrainEditor/PaintTools/CreateTerrainTool.cs @@ -109,7 +109,7 @@ Terrain CreateNeighbor(Terrain parent, Vector3 position) if (null != GameObject.Find(uniqueName)) { Debug.LogWarning("Already have a neighbor on that side"); - return (Terrain)null; + return null; } TerrainData terrainData = new TerrainData(); @@ -125,7 +125,7 @@ Terrain CreateNeighbor(Terrain parent, Vector3 position) terrainData.SetDetailResolution(parent.terrainData.detailResolution, parent.terrainData.detailResolutionPerPatch); terrainData.name = Guid.NewGuid().ToString(); terrainData.size = parent.terrainData.size; - GameObject terrainGO = (GameObject)Terrain.CreateTerrainGameObject(terrainData); + GameObject terrainGO = Terrain.CreateTerrainGameObject(terrainData); terrainGO.name = uniqueName; terrainGO.transform.position = position; @@ -199,8 +199,7 @@ private void FillHeightmapUsingNeighbors(Terrain terrain) Graphics.Blit(null, heightmap, crossBlendMat); - terrain.terrainData.UpdateDirtyRegion(0, 0, heightmap.width, heightmap.height, true); - terrain.ApplyDelayedHeightmapModification(); + terrain.terrainData.DirtyHeightmapRegion(new RectInt(0, 0, heightmap.width, heightmap.height), TerrainHeightmapSyncControl.HeightAndLod); } private bool RaycastTerrain(Terrain terrain, Ray mouseRay, out RaycastHit hit, out Terrain hitTerrain) diff --git a/Modules/TerrainEditor/PaintTools/PaintTreesTool.cs b/Modules/TerrainEditor/PaintTools/PaintTreesTool.cs index 01ced5517e..6dcd857b61 100644 --- a/Modules/TerrainEditor/PaintTools/PaintTreesTool.cs +++ b/Modules/TerrainEditor/PaintTools/PaintTreesTool.cs @@ -260,8 +260,7 @@ public void MassPlaceTrees(TerrainData terrainData, int numberOfTrees, bool rand instances = allTrees; } - terrainData.treeInstances = instances; - terrainData.RecalculateTreePositions(); + terrainData.SetTreeInstances(instances, true); } public override bool OnPaint(Terrain terrain, IOnPaint editContext) diff --git a/Modules/TerrainEditor/TerrainInspector.cs b/Modules/TerrainEditor/TerrainInspector.cs index 11af457ed8..0fab8736d5 100644 --- a/Modules/TerrainEditor/TerrainInspector.cs +++ b/Modules/TerrainEditor/TerrainInspector.cs @@ -1434,14 +1434,12 @@ void ResizeControlTexture(int newResolution) for (int i = 0; i < oldAlphaMaps.Length; i++) { RenderTexture.active = oldAlphaMaps[i]; - td.alphamapTextures[i].ReadPixels(new Rect(0, 0, newResolution, newResolution), 0, 0); - td.alphamapTextures[i].Apply(); + td.CopyActiveRenderTextureToTexture(TerrainData.AlphamapTextureName, i, new RectInt(0, 0, newResolution, newResolution), Vector2Int.zero, false); } + td.SetBaseMapDirty(); RenderTexture.active = oldRT; for (int i = 0; i < oldAlphaMaps.Length; i++) RenderTexture.ReleaseTemporary(oldAlphaMaps[i]); - - td.SetBaseMapDirty(); Repaint(); } @@ -1464,9 +1462,7 @@ void ResizeHeightmap(int newResolution) RenderTexture.active = oldRT; - m_Terrain.terrainData.UpdateDirtyRegion(0, 0, m_Terrain.terrainData.heightmapTexture.width, m_Terrain.terrainData.heightmapTexture.height, !m_Terrain.drawInstanced); - m_Terrain.Flush(); - m_Terrain.ApplyDelayedHeightmapModification(); + m_Terrain.terrainData.DirtyHeightmapRegion(new RectInt(0, 0, m_Terrain.terrainData.heightmapTexture.width, m_Terrain.terrainData.heightmapTexture.height), TerrainHeightmapSyncControl.HeightAndLod); Repaint(); } diff --git a/Modules/TerrainEditor/Utilities/TerrainMenus.cs b/Modules/TerrainEditor/Utilities/TerrainMenus.cs index d9cf145f16..fe97563b55 100644 --- a/Modules/TerrainEditor/Utilities/TerrainMenus.cs +++ b/Modules/TerrainEditor/Utilities/TerrainMenus.cs @@ -20,11 +20,8 @@ static void CreateTerrain(MenuCommand menuCommand) // Create the storage for the terrain in the project // (So we can reuse it in multiple scenes) TerrainData terrainData = new TerrainData(); - const int size = 1025; - terrainData.heightmapResolution = size; + terrainData.heightmapResolution = 513; terrainData.size = new Vector3(1000, 600, 1000); - - terrainData.heightmapResolution = 512; terrainData.baseMapResolution = 1024; terrainData.SetDetailResolution(1024, terrainData.detailResolutionPerPatch); diff --git a/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs b/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs index 25d0fe133b..4474658efb 100644 --- a/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs +++ b/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs @@ -30,7 +30,7 @@ static TerrainPaintUtilityEditor() s_CurrentOperationUndoStack.Clear(); } - if (tile == null || string.IsNullOrEmpty(editorUndoName)) + if (string.IsNullOrEmpty(editorUndoName)) return; if (!s_CurrentOperationUndoStack.Contains(tile.terrain)) diff --git a/Modules/UIElements/Renderer/UIRUtility.cs b/Modules/UIElements/Renderer/UIRUtility.cs index fb02b95eaf..958e9737d5 100644 --- a/Modules/UIElements/Renderer/UIRUtility.cs +++ b/Modules/UIElements/Renderer/UIRUtility.cs @@ -3,7 +3,9 @@ // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; -using System.Collections.Generic; +using System.Text.RegularExpressions; +using UnityEngine.Rendering; +using UnityEngine.Assertions; using UnityEngine.UIElements.UIR; namespace UnityEngine.UIElements @@ -211,5 +213,23 @@ public static bool IsViewTransformWithoutNesting(VisualElement ve) } public static readonly Rect s_InfiniteRect = new Rect(-1000000, -1000000, 2000000, 2000000); + + // to be moved to UIR Utility + public static bool GetOpenGLCoreVersion(out int major, out int minor) + { + if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore) + { + var version = SystemInfo.graphicsDeviceVersion; + var rx = new Regex(@"OpenGL( *)[0-9].[0-9]"); + var matches = rx.Matches(version); + Assert.IsTrue(matches.Count == 1); + var match = matches[0].Value; + major = match[match.Length - 3] - '0'; + minor = match[match.Length - 1] - '0'; + return true; + } + major = minor = -1; + return false; + } } } diff --git a/Modules/UIElements/Renderer/UIRenderer/UIRenderDevice.cs b/Modules/UIElements/Renderer/UIRenderer/UIRenderDevice.cs index dbb8ce98e3..590fbec4c9 100644 --- a/Modules/UIElements/Renderer/UIRenderer/UIRenderDevice.cs +++ b/Modules/UIElements/Renderer/UIRenderer/UIRenderDevice.cs @@ -152,7 +152,9 @@ public void Dispose() bool m_TransformBufferNeedsUpdate; ComputeBuffer[] m_TransformBuffers; - public bool supportsFragmentClipping { get; } = SystemInfo.supportsComputeShaders; + // We need to make sure we're using version 4.5+ with OpenGL as this is the condition used by the shader + // to determine whether StructuredBuffers are used or not + public bool supportsFragmentClipping { get; } = SystemInfo.supportsComputeShaders && !OpenGLCoreBelow45(); BlockAllocator m_ClippingAllocator; List> m_ClippingPages; uint m_ClippingBufferToUse; @@ -222,7 +224,7 @@ void CompleteCreation() // Initialize Skinning-Transform Data { var initialTransformCapacity = m_LazyCreationInitialTransformCapacity; - bool unlimitedTransformCount = SystemInfo.supportsComputeShaders; + bool unlimitedTransformCount = SystemInfo.supportsComputeShaders && !OpenGLCoreBelow45(); if (!unlimitedTransformCount) initialTransformCapacity = 200; // Math.Min(200, initialTransformCapacity); // Default UIR shader can hold up to 200 matrices as constants initialTransformCapacity = Math.Max(1, initialTransformCapacity); // Reserve one entry for "unskinned" meshes @@ -624,6 +626,18 @@ public Material GetStandardMaterial() return m_DefaultMaterial; } + static bool OpenGLCoreBelow45() + { + int maj, min; + if (UIRUtility.GetOpenGLCoreVersion(out maj, out min)) + { + if (maj == 4) + return min < 5; + return maj < 4; + } + else return false; + } + static void SetupStandardMaterial(Material material, DrawingModes mode) { const CompareFunction compFront = CompareFunction.Always; diff --git a/Modules/UnityWebRequestWWW/Public/WWW.cs b/Modules/UnityWebRequestWWW/Public/WWW.cs index 6128e522da..040b5e3665 100644 --- a/Modules/UnityWebRequestWWW/Public/WWW.cs +++ b/Modules/UnityWebRequestWWW/Public/WWW.cs @@ -307,11 +307,15 @@ public float uploadProgress public string url { get { return _uwr.url; } } - public override bool keepWaiting { get { return !_uwr.isDone; } } + public override bool keepWaiting { get { return _uwr == null ? false : !_uwr.isDone; } } public void Dispose() { - _uwr.Dispose(); + if (_uwr != null) + { + _uwr.Dispose(); + _uwr = null; + } } internal Object GetAudioClipInternal(bool threeD, bool stream, bool compressed, AudioType audioType) diff --git a/Projects/CSharp/UnityEditor.csproj b/Projects/CSharp/UnityEditor.csproj index d3bd6ce23a..067453cdeb 100644 --- a/Projects/CSharp/UnityEditor.csproj +++ b/Projects/CSharp/UnityEditor.csproj @@ -2194,6 +2194,9 @@ Editor\Mono\Inspector\EditorDragging.cs + + Editor\Mono\Inspector\EditorElement.cs + Editor\Mono\Inspector\EditorSettingsInspector.cs diff --git a/Projects/CSharp/UnityEngine.csproj b/Projects/CSharp/UnityEngine.csproj index f63fd617df..0509e107fa 100644 --- a/Projects/CSharp/UnityEngine.csproj +++ b/Projects/CSharp/UnityEngine.csproj @@ -1723,6 +1723,12 @@ Modules\Terrain\Public\Terrain.bindings.cs + + Modules\Terrain\Public\TerrainCallbacks.cs + + + Modules\Terrain\Public\TerrainData.GPUCopy.cs + Modules\Terrain\Public\TerrainData.bindings.cs diff --git a/README.md b/README.md index 8baa1743eb..7031761b61 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Unity 2019.1.0b1 C# reference source code +## Unity 2019.1.0b2 C# reference source code The C# part of the Unity engine and editor source code. May be used for reference purposes only. diff --git a/Runtime/Export/Android/AndroidJava.bindings.cs b/Runtime/Export/Android/AndroidJava.bindings.cs index 136aeb8f92..e5b05bb7f9 100644 --- a/Runtime/Export/Android/AndroidJava.bindings.cs +++ b/Runtime/Export/Android/AndroidJava.bindings.cs @@ -7,26 +7,146 @@ namespace UnityEngine { - + // AndroidJavaObject is the Unity representation of a generic instance of java.lang.Object. public partial class AndroidJavaObject : IDisposable { - internal AndroidJavaObject() {} - public AndroidJavaObject(string className, params object[] args) {} - public void Dispose() {} - public void Call(string methodName, params object[] args) {} - public void CallStatic(string methodName, params object[] args) {} - public FieldType Get(string fieldName) { return default(FieldType); } - public void Set(string fieldName, FieldType val) {} - public FieldType GetStatic(string fieldName) { return default(FieldType); } - public void SetStatic(string fieldName, FieldType val) {} - public IntPtr GetRawObject() { return IntPtr.Zero; } - public IntPtr GetRawClass() { return IntPtr.Zero; } - public ReturnType Call(string methodName, params object[] args) { return default(ReturnType); } - public ReturnType CallStatic(string methodName, params object[] args) { return default(ReturnType); } + // Construct an AndroidJavaObject based on the name of the class. + public AndroidJavaObject(string className, string[] args) : this() + { + _AndroidJavaObject(className, (object)args); + } + + public AndroidJavaObject(string className, AndroidJavaObject[] args) : this() + { + _AndroidJavaObject(className, (object)args); + } + + public AndroidJavaObject(string className, AndroidJavaClass[] args) : this() + { + _AndroidJavaObject(className, (object)args); + } + + public AndroidJavaObject(string className, AndroidJavaProxy[] args) : this() + { + _AndroidJavaObject(className, (object)args); + } + + public AndroidJavaObject(string className, AndroidJavaRunnable[] args) : this() + { + _AndroidJavaObject(className, (object)args); + } + + public AndroidJavaObject(string className, params object[] args) : this() + { + _AndroidJavaObject(className, args); + } + + // IDisposable callback + public void Dispose() + { + _Dispose(); + } + + //=================================================================== + + // Calls a Java method on an object (non-static). + public void Call(string methodName, T[] args) + { + _Call(methodName, (object)args); + } + + public void Call(string methodName, params object[] args) + { + _Call(methodName, args); + } + + //=================================================================== + + // Call a static Java method on a class. + public void CallStatic(string methodName, T[] args) + { + _CallStatic(methodName, (object)args); + } + + public void CallStatic(string methodName, params object[] args) + { + _CallStatic(methodName, args); + } + + //=================================================================== + + // Get the value of a field in an object (non-static). + public FieldType Get(string fieldName) + { + return _Get(fieldName); + } + + // Set the value of a field in an object (non-static). + public void Set(string fieldName, FieldType val) + { + _Set(fieldName, val); + } + + //=================================================================== + + // Get the value of a static field in an object type. + public FieldType GetStatic(string fieldName) + { + return _GetStatic(fieldName); + } + + // Set the value of a static field in an object type. + public void SetStatic(string fieldName, FieldType val) + { + _SetStatic(fieldName, val); + } + + //=================================================================== + + // Retrieve the raw jobject pointer to the Java object. + public IntPtr GetRawObject() + { + return _GetRawObject(); + } + + // Retrieve the raw jclass pointer to the Java class; + public IntPtr GetRawClass() + { + return _GetRawClass(); + } + + //=================================================================== + + // Call a Java method on an object. + public ReturnType Call(string methodName, T[] args) + { + return _Call(methodName, (object)args); + } + + public ReturnType Call(string methodName, params object[] args) + { + return _Call(methodName, args); + } + + // Call a static Java method on a class. + public ReturnType CallStatic(string methodName, T[] args) + { + return _CallStatic(methodName, (object)args); + } + + public ReturnType CallStatic(string methodName, params object[] args) + { + return _CallStatic(methodName, args); + } } + // AndroidJavaClass is the Unity representation of a generic instance of java.lang.Class public partial class AndroidJavaClass : AndroidJavaObject { - public AndroidJavaClass(string className) {} + // Construct an AndroidJavaClass from the class name + public AndroidJavaClass(string className) : base() + { + _AndroidJavaClass(className); + } } } diff --git a/Runtime/Export/Android/AndroidJavaImpl.cs b/Runtime/Export/Android/AndroidJavaImpl.cs index 6f8d15886d..630b22586f 100644 --- a/Runtime/Export/Android/AndroidJavaImpl.cs +++ b/Runtime/Export/Android/AndroidJavaImpl.cs @@ -47,6 +47,8 @@ public partial class AndroidJavaObject { protected void DebugPrint(string msg) {} protected void DebugPrint(string call, string methodName, string signature, object[] args) {} + private void _AndroidJavaObject(string className, params object[] args) {} + internal AndroidJavaObject() {} ~AndroidJavaObject() {} protected virtual void Dispose(bool disposing) {} protected void _Dispose() {} @@ -64,4 +66,8 @@ protected void _SetStatic(string fieldName, FieldType val) {} protected static AndroidJavaClass JavaLangClass { get { return null; } } } + public partial class AndroidJavaClass + { + private void _AndroidJavaClass(string className) {} + } } diff --git a/Runtime/Export/Graphics/Texture.cs b/Runtime/Export/Graphics/Texture.cs index f6823ebd69..74286e645d 100644 --- a/Runtime/Export/Graphics/Texture.cs +++ b/Runtime/Export/Graphics/Texture.cs @@ -413,24 +413,6 @@ void EnableCubemapFace(CubemapFace face, bool value) public partial class Texture : Object { -/* - internal static GraphicsFormat GetCompatibleFormat(TextureFormat format, bool isSRGB) - { - GraphicsFormat requestedFormat = GraphicsFormatUtility.GetGraphicsFormat(format, isSRGB); - GraphicsFormat compatibleFormat = SystemInfo.GetCompatibleFormat(requestedFormat, FormatUsage.Sample); - - if (requestedFormat == compatibleFormat) - { - return requestedFormat; - } - else - { - Debug.LogWarning(String.Format("'{0}' is not supported. Texture fallbacks to {1} format on this platform. Use 'SystemInfo.IsFormatSupported' C# API to check format support.", requestedFormat.ToString(), compatibleFormat.ToString())); - return compatibleFormat; - } - } -*/ - internal bool ValidateFormat(RenderTextureFormat format) { if (SystemInfo.SupportsRenderTextureFormat(format)) diff --git a/Runtime/Export/Scripting/UnitySynchronizationContext.cs b/Runtime/Export/Scripting/UnitySynchronizationContext.cs index 7898cbc6ff..9c91717ffb 100644 --- a/Runtime/Export/Scripting/UnitySynchronizationContext.cs +++ b/Runtime/Export/Scripting/UnitySynchronizationContext.cs @@ -11,17 +11,17 @@ namespace UnityEngine internal sealed class UnitySynchronizationContext : SynchronizationContext { private const int kAwqInitialCapacity = 20; - private readonly Queue m_AsyncWorkQueue; + private readonly List m_AsyncWorkQueue; private readonly List m_CurrentFrameWork = new List(kAwqInitialCapacity); private readonly int m_MainThreadID; private UnitySynchronizationContext(int mainThreadID) { - m_AsyncWorkQueue = new Queue(kAwqInitialCapacity); + m_AsyncWorkQueue = new List(kAwqInitialCapacity); m_MainThreadID = mainThreadID; } - private UnitySynchronizationContext(Queue queue, int mainThreadID) + private UnitySynchronizationContext(List queue, int mainThreadID) { m_AsyncWorkQueue = queue; m_MainThreadID = mainThreadID; @@ -42,7 +42,7 @@ public override void Send(SendOrPostCallback callback, object state) { lock (m_AsyncWorkQueue) { - m_AsyncWorkQueue.Enqueue(new WorkRequest(callback, state, waitHandle)); + m_AsyncWorkQueue.Add(new WorkRequest(callback, state, waitHandle)); } waitHandle.WaitOne(); } @@ -54,7 +54,7 @@ public override void Post(SendOrPostCallback callback, object state) { lock (m_AsyncWorkQueue) { - m_AsyncWorkQueue.Enqueue(new WorkRequest(callback, state)); + m_AsyncWorkQueue.Add(new WorkRequest(callback, state)); } } diff --git a/Runtime/Export/Shaders/Shader.bindings.cs b/Runtime/Export/Shaders/Shader.bindings.cs index 8e8a67af87..e07e24a6b5 100644 --- a/Runtime/Export/Shaders/Shader.bindings.cs +++ b/Runtime/Export/Shaders/Shader.bindings.cs @@ -152,7 +152,7 @@ public partial class Material : Object public string GetTag(string tag, bool searchFallbacks, string defaultValue) { return GetTagImpl(tag, !searchFallbacks, defaultValue); } public string GetTag(string tag, bool searchFallbacks) { return GetTagImpl(tag, !searchFallbacks, ""); } - [FreeFunction("MaterialScripting::Lerp", HasExplicitThis = true)] extern public void Lerp(Material start, Material end, float t); + [FreeFunction("MaterialScripting::Lerp", HasExplicitThis = true)] extern public void Lerp([NotNull] Material start, [NotNull] Material end, float t); [FreeFunction("MaterialScripting::SetPass", HasExplicitThis = true)] extern public bool SetPass(int pass); [FreeFunction("MaterialScripting::CopyPropertiesFrom", HasExplicitThis = true)] extern public void CopyPropertiesFromMaterial(Material mat); From ce23d7f1b11317d4c8a2a7ec3a93f4f504efbb3e Mon Sep 17 00:00:00 2001 From: Unity Technologies Date: Mon, 11 Feb 2019 15:22:34 +0000 Subject: [PATCH 04/26] Unity 2019.1.0b3 C# reference source code --- .../Mono/Annotation/SceneViewCameraWindow.cs | 81 +- .../Annotation/SceneViewSettingsProvider.cs | 74 - Editor/Mono/BuildPipeline/AssemblyStripper.cs | 13 +- .../Mono/Camera/EditorCameraUtils.bindings.cs | 22 + Editor/Mono/ConsoleWindow.cs | 2 +- Editor/Mono/EditorWindow.cs | 73 +- Editor/Mono/GUI/DockArea.cs | 16 +- Editor/Mono/GUI/Tools/EditorToolContext.cs | 5 +- Editor/Mono/GUI/Tools/EditorToolUtility.cs | 5 + Editor/Mono/GUIView.cs | 179 +- Editor/Mono/HostView.cs | 84 +- Editor/Mono/Inspector/LightEditor.cs | 25 + Editor/Mono/Inspector/PreviewWindow.cs | 10 +- .../Mono/Inspector/QualitySettingsEditor.cs | 6 + Editor/Mono/Inspector/RendererEditorBase.cs | 2 +- .../ScriptExecutionOrderInspector.cs | 1 + .../Inspector/StandardParticlesShaderGUI.cs | 8 +- Editor/Mono/InternalEditorUtility.cs | 2 +- Editor/Mono/Prefabs/PrefabUtility.bindings.cs | 2 +- Editor/Mono/Prefabs/PrefabUtility.cs | 9 +- Editor/Mono/RetainedMode.cs | 157 +- Editor/Mono/SceneView/SceneView.cs | 63 +- Editor/Mono/SceneView/SceneViewMotion.cs | 41 +- .../Providers/AssetSettingsProvider.cs | 6 +- Editor/Mono/Settings/SettingsWindow.cs | 23 +- .../Mono/UIElements/Controls/GradientField.cs | 3 +- .../EditorWindowPersistentViewData.cs | 4 +- .../Controls/BaseCompositeField.cs | 136 -- .../Experimental/Controls/BasePopupField.cs | 90 - .../Controls/BindingExtensions.cs | 913 ----------- .../Experimental/Controls/BoundsField.cs | 90 - .../Experimental/Controls/BoundsIntField.cs | 91 - .../Experimental/Controls/ColorField.cs | 126 -- .../Experimental/Controls/CompoundFields.cs | 222 --- .../Experimental/Controls/CurveField.cs | 526 ------ .../Experimental/Controls/DoubleField.cs | 63 - .../Experimental/Controls/EnumField.cs | 135 -- .../Experimental/Controls/FloatField.cs | 62 - .../Experimental/Controls/GradientField.cs | 155 -- .../Experimental/Controls/IntegerField.cs | 62 - .../Experimental/Controls/LayerField.cs | 123 -- .../Experimental/Controls/LayerMaskField.cs | 70 - .../Experimental/Controls/LongField.cs | 62 - .../Experimental/Controls/MaskField.cs | 428 ----- .../Experimental/Controls/ObjectField.cs | 256 --- .../Experimental/Controls/PopupField.cs | 133 -- .../Experimental/Controls/PropertyControl.cs | 312 ---- .../Experimental/Controls/TagField.cs | 111 -- .../Experimental/Controls/TextValueField.cs | 153 -- .../EditorContextualMenuManager.cs | 59 - .../UIElements/Experimental/EditorCursor.cs | 40 - .../Experimental/EditorMenuExtensions.cs | 76 - .../EditorWindowPersistentViewData.cs | 27 - .../Experimental/FieldMouseDragger.cs | 101 -- .../UIElements/Experimental/PanelDebug.cs | 183 --- .../SerializableJsonDictionary.cs | 10 - .../Toolbar/IToolbarMenuElement.cs | 33 - .../Experimental/Toolbar/Toolbar.cs | 24 - .../Experimental/Toolbar/ToolbarButton.cs | 27 - .../Experimental/Toolbar/ToolbarMenu.cs | 53 - .../Toolbar/ToolbarPopupSearchField.cs | 24 - .../Toolbar/ToolbarSearchField.cs | 139 -- .../Experimental/Toolbar/ToolbarSpacer.cs | 32 - .../Experimental/Toolbar/ToolbarToggle.cs | 22 - .../Mono/UIElements/Experimental/Tooltip.cs | 45 - .../Experimental/UIElementsEditorUtility.cs | 60 - .../Experimental/UXMLEditorFactories.cs | 76 - .../Experimental/UXMLSchemaGenerator.cs | 590 ------- .../UIElements/Experimental/VisualSplitter.cs | 202 --- .../Experimental/VisualTreeAssetEditor.cs | 107 -- Editor/Mono/UIElements/Tooltip.cs | 5 +- .../UxmlTemplateCreator.cs | 2 +- .../Mono/UIElements/UIElementsViewImporter.cs | 9 +- Editor/Mono/UIElements/UXMLEditorFactories.cs | 2 +- .../Mono/UIElements/VisualTreeAssetEditor.cs | 2 - .../Managed/AssetBundle.bindings.cs | 1 + .../ModelImporterMaterialEditor.cs | 10 +- .../AudioClipExtensions.bindings.cs | 7 +- .../Public/csas/Managed/DSPCommandBlock.cs | 93 +- Modules/Audio/Public/csas/Managed/DSPGraph.cs | 9 +- .../Public/csas/Managed/ExecuteContext.cs | 13 +- .../Public/csas/Managed/ResourceContext.cs | 2 + .../Public/csas/Managed/SampleBufferArray.cs | 1 + .../DSPCommandBlock.bindings.cs | 4 +- .../Elements/Blackboard/BlackboardField.cs | 3 +- Modules/GraphViewEditor/Elements/Edge.cs | 7 +- Modules/GraphViewEditor/Elements/StackNode.cs | 9 +- ...ation.cs => ExperimentalNamespaceRelic.cs} | 8 +- .../ExperimentalUIElements/Capabilities.cs | 21 - .../Decorators/GridBackground.cs | 235 --- .../ExperimentalUIElements/Direction.cs | 12 - .../ExperimentalUIElements/EdgeControl.cs | 993 ----------- .../Elements/Blackboard/Blackboard.cs | 141 -- .../Elements/Blackboard/BlackboardField.cs | 150 -- .../Elements/Blackboard/BlackboardRow.cs | 73 - .../Elements/Blackboard/BlackboardSection.cs | 301 ---- .../ExperimentalUIElements/Elements/Edge.cs | 397 ----- .../Elements/GraphElement.cs | 247 --- .../Elements/GraphElementScopeExtensions.cs | 25 - .../ExperimentalUIElements/Elements/Group.cs | 170 -- .../Elements/GroupDropArea.cs | 97 -- .../Elements/MiniMap.cs | 377 ----- .../ExperimentalUIElements/Elements/Node.cs | 462 ------ .../ExperimentalUIElements/Elements/Pill.cs | 188 --- .../ExperimentalUIElements/Elements/Port.cs | 473 ------ .../ExperimentalUIElements/Elements/Scope.cs | 329 ---- .../Elements/ScopeContentContainer.cs | 61 - .../Elements/StackNode.cs | 272 --- .../Elements/StackNodeDropTarget.cs | 352 ---- .../Elements/StackNodeSeparator.cs | 146 -- .../Elements/TokenNode.cs | 64 - .../ExperimentalUIElements/IDroppable.cs | 26 - .../ExperimentalUIElements/IInsertLocation.cs | 23 - .../ExperimentalUIElements/ISelectable.cs | 19 - .../ExperimentalUIElements/ISelection.cs | 17 - .../ExperimentalUIElements/IconBadge.cs | 377 ----- .../Manipulators/ClickSelector.cs | 91 - .../Manipulators/ContentDragger.cs | 135 -- .../Manipulators/Dragger.cs | 150 -- .../Manipulators/EdgeConnector.cs | 157 -- .../Manipulators/EdgeDragHelper.cs | 383 ----- .../Manipulators/EdgeManipulator.cs | 197 --- .../Manipulators/FreehandSelector.cs | 229 --- .../Manipulators/Inserter.cs | 71 - .../Manipulators/RectangleSelector.cs | 241 --- .../Manipulators/Resizer.cs | 225 --- .../Manipulators/SelectionDragger.cs | 550 ------- .../Manipulators/SelectionDropper.cs | 214 --- .../Manipulators/ShortcutHandler.cs | 51 - .../Manipulators/Zoomer.cs | 195 --- .../ExperimentalUIElements/NodeAdapter.cs | 153 -- .../NodeSearch/SearchTree.cs | 47 - .../NodeSearch/SearchWindow.cs | 629 ------- .../ExperimentalUIElements/Utils/RectUtils.cs | 92 -- .../Utils/VisualElementAttacher.cs | 219 --- .../ExperimentalUIElements/ValueAnimation.cs | 150 -- .../ExperimentalUIElements/Views/GraphView.cs | 1458 ----------------- .../GraphViewEditor/Manipulators/Zoomer.cs | 4 +- Modules/GraphViewEditor/Views/GraphView.cs | 5 +- .../ParticleSystemEditor/ParticleEffectUI.cs | 1 - .../ParticleSystemModules/ShapeModuleUI.cs | 10 +- Modules/UIElements/Controls/TextField.cs | 2 - Modules/UIElements/Experimental/BaseField.cs | 102 -- Modules/UIElements/Experimental/BaseSlider.cs | 308 ---- .../Experimental/BindableElement.cs | 42 - Modules/UIElements/Experimental/Box.cs | 11 - Modules/UIElements/Experimental/Button.cs | 28 - .../UIElements/Experimental/ClampedDragger.cs | 88 - Modules/UIElements/Experimental/Clickable.cs | 166 -- .../Experimental/ContextualMenu.Deprecated.cs | 106 -- .../Experimental/ContextualMenuManager.cs | 23 - .../Experimental/ContextualMenuManipulator.cs | 88 - .../Experimental/Controls/Binding.cs | 27 - .../Controls/INotifyValueChanged.cs | 21 - .../Controls/KeyboardTextEditor.cs | 390 ----- .../Experimental/Controls/TextEditor.cs | 39 - .../Experimental/Controls/TextEditorEngine.cs | 41 - .../Experimental/Controls/TextField.cs | 171 -- .../Controls/TextInputFieldBase.cs | 493 ------ .../Experimental/Controls/Toggle.cs | 124 -- .../Controls/TouchScreenTextEditor.cs | 53 - .../Controls/VisualTreeBindingsUpdater.cs | 179 -- Modules/UIElements/Experimental/Cursor.cs | 58 - .../UIElements/Experimental/DisposeHelper.cs | 33 - .../UIElements/Experimental/DropdownMenu.cs | 173 -- .../Experimental/EventDispatcher.cs | 274 ---- .../Experimental/Events/CaptureEvents.cs | 43 - .../Experimental/Events/ChangeEvent.cs | 37 - .../Events/CommandEventDispatchingStrategy.cs | 43 - .../Experimental/Events/CommandEvents.cs | 64 - .../DebuggerEventDispatchingStrategy.cs | 28 - .../Events/DefaultDispatchingStrategy.cs | 43 - .../Experimental/Events/DragAndDropEvents.cs | 64 - .../Experimental/Events/EventBase.cs | 399 ----- .../Experimental/Events/EventCallback.cs | 109 -- .../Events/EventCallbackRegistry.cs | 414 ----- .../Experimental/Events/EventHandler.cs | 157 -- .../Experimental/Events/EventPool.cs | 26 - .../Experimental/Events/FocusEvents.cs | 90 - .../Events/IEventDispatchingStrategy.cs | 165 -- .../Events/IMGUIEventDispatchingStrategy.cs | 25 - .../Experimental/Events/InputEvents.cs | 33 - .../KeyboardEventDispatchingStrategy.cs | 51 - .../Experimental/Events/KeyboardEvents.cs | 106 -- .../Experimental/Events/LayoutEvents.cs | 32 - .../Events/MouseCaptureDispatchingStrategy.cs | 114 -- .../Events/MouseEventDispatchingStrategy.cs | 72 - .../Experimental/Events/MouseEvents.cs | 332 ---- .../Experimental/Events/MouseEventsHelper.cs | 131 -- .../Experimental/Events/PanelEvents.cs | 44 - .../Experimental/Events/PropagationPaths.cs | 63 - .../Experimental/Events/TooltipEvent.cs | 36 - .../UIElements/Experimental/Events/UIEvent.cs | 29 - .../Experimental/FocusController.cs | 227 --- Modules/UIElements/Experimental/Foldout.cs | 114 -- .../Experimental/HierarchyTraversal.cs | 37 - .../UIElements/Experimental/IMGUIContainer.cs | 580 ------- Modules/UIElements/Experimental/IStyle.cs | 88 - Modules/UIElements/Experimental/ITransform.cs | 14 - Modules/UIElements/Experimental/Image.cs | 175 -- .../Experimental/ImmediateStylePainter.cs | 168 -- .../Experimental/InteractionEnums.cs | 13 - Modules/UIElements/Experimental/Label.cs | 21 - Modules/UIElements/Experimental/ListView.cs | 577 ------- .../ManipulatorActivationFilter.cs | 45 - .../UIElements/Experimental/Manipulators.cs | 37 - .../UIElements/Experimental/MinMaxSlider.cs | 413 ----- .../UIElements/Experimental/MouseButton.cs | 13 - .../Experimental/MouseCaptureController.cs | 106 -- .../Experimental/MouseManipulator.cs | 38 - Modules/UIElements/Experimental/ObjectPool.cs | 60 - Modules/UIElements/Experimental/Panel.cs | 590 ------- .../UIElements/Experimental/PanelWrapper.cs | 249 --- .../UIElements/Experimental/PopupWindow.cs | 38 - .../UIElements/Experimental/RepeatButton.cs | 43 - Modules/UIElements/Experimental/Scheduler.cs | 357 ---- Modules/UIElements/Experimental/ScrollView.cs | 284 ---- Modules/UIElements/Experimental/Scroller.cs | 174 -- Modules/UIElements/Experimental/Slider.cs | 101 -- Modules/UIElements/Experimental/SliderInt.cs | 106 -- Modules/UIElements/Experimental/Spacing.cs | 53 - Modules/UIElements/Experimental/StyleEnums.cs | 79 - .../UIElements/Experimental/StylePainter.cs | 271 --- .../StyleComplexSelectorExtensions.cs | 77 - .../StyleSheets/StyleSelectorHelper.cs | 239 --- .../StyleSheets/StyleSheetApplicator.cs | 447 ----- .../StyleSheets/StyleSheetCache.cs | 201 --- .../StyleSheets/StyleSheetExtensions.cs | 63 - .../Experimental/StyleSheets/StyleValue.cs | 241 --- .../StyleSheets/VisualElementStylesData.cs | 641 -------- .../Experimental/TemplateContainer.cs | 62 - .../UIElements/Experimental/TextElement.cs | 137 -- Modules/UIElements/Experimental/TreeView.cs | 605 ------- .../UIElements/Experimental/TreeViewItem.cs | 83 - .../Experimental/UIElementsUtility.cs | 285 ---- Modules/UIElements/Experimental/UQuery.cs | 711 -------- .../Experimental/UXML/IUxmlAttributes.cs | 13 - .../Experimental/UXML/TemplateAsset.cs | 19 - .../UXML/UxmlAttributeDescription.cs | 374 ----- .../UXML/UxmlChildElementDescription.cs | 20 - .../Experimental/UXML/UxmlFactory.cs | 272 --- .../Experimental/UXML/UxmlRootElement.cs | 55 - .../Experimental/UXML/UxmlTypeRestriction.cs | 72 - .../Experimental/UXML/VisualElementAsset.cs | 10 - .../UXML/VisualElementFactoryRegistry.cs | 126 -- .../Experimental/UXML/VisualTreeAsset.cs | 248 --- .../Experimental/VisualContainer.cs | 79 - .../UIElements/Experimental/VisualElement.cs | 1295 --------------- .../Experimental/VisualElementDataWatch.cs | 100 -- .../Experimental/VisualElementFocusRing.cs | 283 ---- .../Experimental/VisualElementHierarchy.cs | 682 -------- .../Experimental/VisualElementScheduler.cs | 308 ---- .../Experimental/VisualElementStyleAccess.cs | 960 ----------- .../Experimental/VisualElementTooltip.cs | 41 - .../Experimental/VisualElementUtils.cs | 26 - .../VisualTreeHierarchyTracker.cs | 116 -- .../Experimental/VisualTreeLayoutUpdater.cs | 99 -- .../VisualTreePersistentDataUpdater.cs | 98 -- .../Experimental/VisualTreeRepaintUpdater.cs | 341 ---- .../Experimental/VisualTreeStyleUpdater.cs | 282 ---- .../VisualTreeTransformClipUpdater.cs | 73 - .../Experimental/VisualTreeUpdater.cs | 160 -- .../Renderer/UIRDataChainBuilder.cs | 5 +- .../UIElements/Renderer/UIRRepaintUpdater.cs | 2 +- .../UIElements/Renderer/UIRStylePainter.cs | 4 +- .../Renderer/UIRTransformClipUpdater.cs | 5 +- Modules/UIElements/Renderer/UIRUtility.cs | 10 +- .../Renderer/UIRenderer/UIRenderDevice.cs | 5 +- Modules/UIElements/StyleSheets/StyleValue.cs | 1 - Modules/UIElements/UIElementsUtility.cs | 8 +- Modules/UIElements/UXML/IUxmlAttributes.cs | 4 +- Modules/UIElements/UXML/VisualTreeAsset.cs | 4 +- .../UIElements/VisualElementStyleSheetSet.cs | 1 - .../Experimental/PanelPickerWindow.cs | 42 - .../Experimental/PickingData.cs | 176 -- .../Experimental/UIElementsDebugger.cs | 924 ----------- .../Experimental/UxmlExporter.cs | 126 -- .../Experimental/VisualTreeTreeView.cs | 80 - Projects/CSharp/UnityEditor.csproj | 301 +--- Projects/CSharp/UnityEngine.csproj | 360 ---- README.md | 2 +- .../Graphics/GraphicsComponents.bindings.cs | 1 + .../Rendering/BatchRendererGroup.bindings.cs | 38 +- Runtime/Export/Scripting/PreserveAttribute.cs | 3 +- 284 files changed, 520 insertions(+), 41444 deletions(-) delete mode 100644 Editor/Mono/Annotation/SceneViewSettingsProvider.cs create mode 100644 Editor/Mono/Camera/EditorCameraUtils.bindings.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/BaseCompositeField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/BasePopupField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/BindingExtensions.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/BoundsField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/BoundsIntField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/ColorField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/CompoundFields.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/CurveField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/DoubleField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/EnumField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/FloatField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/GradientField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/IntegerField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/LayerField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/LayerMaskField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/LongField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/MaskField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/ObjectField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/PopupField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/PropertyControl.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/TagField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Controls/TextValueField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/EditorContextualMenuManager.cs delete mode 100644 Editor/Mono/UIElements/Experimental/EditorCursor.cs delete mode 100644 Editor/Mono/UIElements/Experimental/EditorMenuExtensions.cs delete mode 100644 Editor/Mono/UIElements/Experimental/EditorWindowPersistentViewData.cs delete mode 100644 Editor/Mono/UIElements/Experimental/FieldMouseDragger.cs delete mode 100644 Editor/Mono/UIElements/Experimental/PanelDebug.cs delete mode 100644 Editor/Mono/UIElements/Experimental/SerializableJsonDictionary.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/IToolbarMenuElement.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/Toolbar.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/ToolbarButton.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/ToolbarMenu.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/ToolbarPopupSearchField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSearchField.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSpacer.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Toolbar/ToolbarToggle.cs delete mode 100644 Editor/Mono/UIElements/Experimental/Tooltip.cs delete mode 100644 Editor/Mono/UIElements/Experimental/UIElementsEditorUtility.cs delete mode 100644 Editor/Mono/UIElements/Experimental/UXMLEditorFactories.cs delete mode 100644 Editor/Mono/UIElements/Experimental/UXMLSchemaGenerator.cs delete mode 100644 Editor/Mono/UIElements/Experimental/VisualSplitter.cs delete mode 100644 Editor/Mono/UIElements/Experimental/VisualTreeAssetEditor.cs rename Modules/GraphViewEditor/{ExperimentalUIElements/Orientation.cs => ExperimentalNamespaceRelic.cs} (50%) delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Capabilities.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Decorators/GridBackground.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Direction.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/EdgeControl.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/Blackboard.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/BlackboardField.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/BlackboardRow.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/BlackboardSection.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Edge.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/GraphElement.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/GraphElementScopeExtensions.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Group.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/GroupDropArea.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/MiniMap.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Node.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Pill.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Port.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/Scope.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/ScopeContentContainer.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/StackNode.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/StackNodeDropTarget.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/StackNodeSeparator.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Elements/TokenNode.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/IDroppable.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/IInsertLocation.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/ISelectable.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/ISelection.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/IconBadge.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/ClickSelector.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/ContentDragger.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/Dragger.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/EdgeConnector.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/EdgeDragHelper.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/EdgeManipulator.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/FreehandSelector.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/Inserter.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/RectangleSelector.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/Resizer.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/SelectionDragger.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/SelectionDropper.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/ShortcutHandler.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Manipulators/Zoomer.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/NodeAdapter.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/NodeSearch/SearchTree.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/NodeSearch/SearchWindow.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Utils/RectUtils.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Utils/VisualElementAttacher.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/ValueAnimation.cs delete mode 100644 Modules/GraphViewEditor/ExperimentalUIElements/Views/GraphView.cs delete mode 100644 Modules/UIElements/Experimental/BaseField.cs delete mode 100644 Modules/UIElements/Experimental/BaseSlider.cs delete mode 100644 Modules/UIElements/Experimental/BindableElement.cs delete mode 100644 Modules/UIElements/Experimental/Box.cs delete mode 100644 Modules/UIElements/Experimental/Button.cs delete mode 100644 Modules/UIElements/Experimental/ClampedDragger.cs delete mode 100644 Modules/UIElements/Experimental/Clickable.cs delete mode 100644 Modules/UIElements/Experimental/ContextualMenu.Deprecated.cs delete mode 100644 Modules/UIElements/Experimental/ContextualMenuManager.cs delete mode 100644 Modules/UIElements/Experimental/ContextualMenuManipulator.cs delete mode 100644 Modules/UIElements/Experimental/Controls/Binding.cs delete mode 100644 Modules/UIElements/Experimental/Controls/INotifyValueChanged.cs delete mode 100644 Modules/UIElements/Experimental/Controls/KeyboardTextEditor.cs delete mode 100644 Modules/UIElements/Experimental/Controls/TextEditor.cs delete mode 100644 Modules/UIElements/Experimental/Controls/TextEditorEngine.cs delete mode 100644 Modules/UIElements/Experimental/Controls/TextField.cs delete mode 100644 Modules/UIElements/Experimental/Controls/TextInputFieldBase.cs delete mode 100644 Modules/UIElements/Experimental/Controls/Toggle.cs delete mode 100644 Modules/UIElements/Experimental/Controls/TouchScreenTextEditor.cs delete mode 100644 Modules/UIElements/Experimental/Controls/VisualTreeBindingsUpdater.cs delete mode 100644 Modules/UIElements/Experimental/Cursor.cs delete mode 100644 Modules/UIElements/Experimental/DisposeHelper.cs delete mode 100644 Modules/UIElements/Experimental/DropdownMenu.cs delete mode 100644 Modules/UIElements/Experimental/EventDispatcher.cs delete mode 100644 Modules/UIElements/Experimental/Events/CaptureEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/ChangeEvent.cs delete mode 100644 Modules/UIElements/Experimental/Events/CommandEventDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/CommandEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/DebuggerEventDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/DefaultDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/DragAndDropEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/EventBase.cs delete mode 100644 Modules/UIElements/Experimental/Events/EventCallback.cs delete mode 100644 Modules/UIElements/Experimental/Events/EventCallbackRegistry.cs delete mode 100644 Modules/UIElements/Experimental/Events/EventHandler.cs delete mode 100644 Modules/UIElements/Experimental/Events/EventPool.cs delete mode 100644 Modules/UIElements/Experimental/Events/FocusEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/IEventDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/IMGUIEventDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/InputEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/KeyboardEventDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/KeyboardEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/LayoutEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/MouseCaptureDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/MouseEventDispatchingStrategy.cs delete mode 100644 Modules/UIElements/Experimental/Events/MouseEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/MouseEventsHelper.cs delete mode 100644 Modules/UIElements/Experimental/Events/PanelEvents.cs delete mode 100644 Modules/UIElements/Experimental/Events/PropagationPaths.cs delete mode 100644 Modules/UIElements/Experimental/Events/TooltipEvent.cs delete mode 100644 Modules/UIElements/Experimental/Events/UIEvent.cs delete mode 100644 Modules/UIElements/Experimental/FocusController.cs delete mode 100644 Modules/UIElements/Experimental/Foldout.cs delete mode 100644 Modules/UIElements/Experimental/HierarchyTraversal.cs delete mode 100644 Modules/UIElements/Experimental/IMGUIContainer.cs delete mode 100644 Modules/UIElements/Experimental/IStyle.cs delete mode 100644 Modules/UIElements/Experimental/ITransform.cs delete mode 100644 Modules/UIElements/Experimental/Image.cs delete mode 100644 Modules/UIElements/Experimental/ImmediateStylePainter.cs delete mode 100644 Modules/UIElements/Experimental/InteractionEnums.cs delete mode 100644 Modules/UIElements/Experimental/Label.cs delete mode 100644 Modules/UIElements/Experimental/ListView.cs delete mode 100644 Modules/UIElements/Experimental/ManipulatorActivationFilter.cs delete mode 100644 Modules/UIElements/Experimental/Manipulators.cs delete mode 100644 Modules/UIElements/Experimental/MinMaxSlider.cs delete mode 100644 Modules/UIElements/Experimental/MouseButton.cs delete mode 100644 Modules/UIElements/Experimental/MouseCaptureController.cs delete mode 100644 Modules/UIElements/Experimental/MouseManipulator.cs delete mode 100644 Modules/UIElements/Experimental/ObjectPool.cs delete mode 100644 Modules/UIElements/Experimental/Panel.cs delete mode 100644 Modules/UIElements/Experimental/PanelWrapper.cs delete mode 100644 Modules/UIElements/Experimental/PopupWindow.cs delete mode 100644 Modules/UIElements/Experimental/RepeatButton.cs delete mode 100644 Modules/UIElements/Experimental/Scheduler.cs delete mode 100644 Modules/UIElements/Experimental/ScrollView.cs delete mode 100644 Modules/UIElements/Experimental/Scroller.cs delete mode 100644 Modules/UIElements/Experimental/Slider.cs delete mode 100644 Modules/UIElements/Experimental/SliderInt.cs delete mode 100644 Modules/UIElements/Experimental/Spacing.cs delete mode 100644 Modules/UIElements/Experimental/StyleEnums.cs delete mode 100644 Modules/UIElements/Experimental/StylePainter.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/StyleComplexSelectorExtensions.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/StyleSelectorHelper.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/StyleSheetApplicator.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/StyleSheetCache.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/StyleSheetExtensions.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/StyleValue.cs delete mode 100644 Modules/UIElements/Experimental/StyleSheets/VisualElementStylesData.cs delete mode 100644 Modules/UIElements/Experimental/TemplateContainer.cs delete mode 100644 Modules/UIElements/Experimental/TextElement.cs delete mode 100644 Modules/UIElements/Experimental/TreeView.cs delete mode 100644 Modules/UIElements/Experimental/TreeViewItem.cs delete mode 100644 Modules/UIElements/Experimental/UIElementsUtility.cs delete mode 100644 Modules/UIElements/Experimental/UQuery.cs delete mode 100644 Modules/UIElements/Experimental/UXML/IUxmlAttributes.cs delete mode 100644 Modules/UIElements/Experimental/UXML/TemplateAsset.cs delete mode 100644 Modules/UIElements/Experimental/UXML/UxmlAttributeDescription.cs delete mode 100644 Modules/UIElements/Experimental/UXML/UxmlChildElementDescription.cs delete mode 100644 Modules/UIElements/Experimental/UXML/UxmlFactory.cs delete mode 100644 Modules/UIElements/Experimental/UXML/UxmlRootElement.cs delete mode 100644 Modules/UIElements/Experimental/UXML/UxmlTypeRestriction.cs delete mode 100644 Modules/UIElements/Experimental/UXML/VisualElementAsset.cs delete mode 100644 Modules/UIElements/Experimental/UXML/VisualElementFactoryRegistry.cs delete mode 100644 Modules/UIElements/Experimental/UXML/VisualTreeAsset.cs delete mode 100644 Modules/UIElements/Experimental/VisualContainer.cs delete mode 100644 Modules/UIElements/Experimental/VisualElement.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementDataWatch.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementFocusRing.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementHierarchy.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementScheduler.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementStyleAccess.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementTooltip.cs delete mode 100644 Modules/UIElements/Experimental/VisualElementUtils.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreeHierarchyTracker.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreeLayoutUpdater.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreePersistentDataUpdater.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreeRepaintUpdater.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreeStyleUpdater.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreeTransformClipUpdater.cs delete mode 100644 Modules/UIElements/Experimental/VisualTreeUpdater.cs delete mode 100644 Modules/UIElementsDebuggerEditor/Experimental/PanelPickerWindow.cs delete mode 100644 Modules/UIElementsDebuggerEditor/Experimental/PickingData.cs delete mode 100644 Modules/UIElementsDebuggerEditor/Experimental/UIElementsDebugger.cs delete mode 100644 Modules/UIElementsDebuggerEditor/Experimental/UxmlExporter.cs delete mode 100644 Modules/UIElementsDebuggerEditor/Experimental/VisualTreeTreeView.cs diff --git a/Editor/Mono/Annotation/SceneViewCameraWindow.cs b/Editor/Mono/Annotation/SceneViewCameraWindow.cs index 906a4ac358..cb87c982ae 100644 --- a/Editor/Mono/Annotation/SceneViewCameraWindow.cs +++ b/Editor/Mono/Annotation/SceneViewCameraWindow.cs @@ -30,39 +30,44 @@ public static void Init() readonly SceneView m_SceneView; GUIContent m_CameraSpeedSliderContent; - GUIContent[] m_CameraSpeedMinMax; + GUIContent m_CameraSpeedMin; + GUIContent m_CameraSpeedMax; GUIContent m_FieldOfView; GUIContent m_DynamicClip; GUIContent m_OcclusionCulling; + GUIContent m_EasingEnabled; + GUIContent m_EasingDuration; - const int k_FieldCount = 10; - const int k_WindowWidth = 300; - const int k_WindowHeight = ((int)EditorGUI.kSingleLineHeight) * k_FieldCount + kFrameWidth * 2; + const int kFieldCount = 12; + const int kWindowWidth = 290; + const int kWindowHeight = ((int)EditorGUI.kSingleLineHeight) * kFieldCount + kFrameWidth * 2; const int kFrameWidth = 10; - const float k_PrefixLabelWidth = 120f; - const float kMinMaxSpeedLabelWidth = 26f; - const float k_NearClipMin = .01f; + const float kPrefixLabelWidth = 120f; + const float kMinSpeedLabelWidth = 25f; + const float kMaxSpeedLabelWidth = 29f; + const float kMinMaxSpeedFieldWidth = 50f; + const float kMinMaxSpeedSpace = 8f; + const float kNearClipMin = .01f; float[] m_Vector2Floats = { 0, 0 }; public override Vector2 GetWindowSize() { - return new Vector2(k_WindowWidth, k_WindowHeight); + return new Vector2(kWindowWidth, kWindowHeight); } public SceneViewCameraWindow(SceneView sceneView) { m_SceneView = sceneView; - m_CameraSpeedSliderContent = EditorGUIUtility.TrTextContent("Speed", "The current speed of the camera in the Scene view."); - m_CameraSpeedMinMax = new GUIContent[] - { - EditorGUIUtility.TrTextContent("Min", "The minimum speed of the camera in the Scene view. Valid values are between [0.01, 98]."), - EditorGUIUtility.TrTextContent("Max", "The maximum speed of the camera in the Scene view. Valid values are between [0.02, 99].") - }; - m_FieldOfView = EditorGUIUtility.TrTextContent("Field of View", "The height of the Camera's view angle. Measured in degrees vertically, or along the local Y axis."); + m_CameraSpeedSliderContent = EditorGUIUtility.TrTextContent("Camera Speed", "The current speed of the camera in the Scene view."); + m_CameraSpeedMin = EditorGUIUtility.TrTextContent("Min", "The minimum speed of the camera in the Scene view. Valid values are between [0.01, 98]."); + m_CameraSpeedMax = EditorGUIUtility.TrTextContent("Max", "The maximum speed of the camera in the Scene view. Valid values are between [0.02, 99]."); + m_FieldOfView = EditorGUIUtility.TrTextContent("Field of View", "The height of the camera's view angle. Measured in degrees vertically, or along the local Y axis."); m_DynamicClip = EditorGUIUtility.TrTextContent("Dynamic Clipping", "Check this to enable camera's near and far clipping planes to be calculated relative to the viewport size of the Scene."); - m_OcclusionCulling = EditorGUIUtility.TrTextContent("Occlusion Culling", "Check this to enable occlusion culling in the Scene view. Occlusion culling disables rendering of objects when they\'re not currently seen by the Camera because they\'re hidden (occluded) by other objects."); + m_OcclusionCulling = EditorGUIUtility.TrTextContent("Occlusion Culling", "Check this to enable occlusion culling in the Scene view. Occlusion culling disables rendering of objects when they\'re not currently seen by the camera because they\'re hidden (occluded) by other objects."); + m_EasingEnabled = EditorGUIUtility.TrTextContent("Camera Easing", "Check this to enable camera movement easing. This makes the camera ease in when it starts moving, and ease out when it stops."); + m_EasingDuration = EditorGUIUtility.TrTextContent("Duration", "How long it takes for the speed of the camera to accelerate to its initial full speed. Measured in seconds."); } public override void OnGUI(Rect rect) @@ -82,7 +87,7 @@ public override void OnGUI(Rect rect) private void Draw(Rect rect) { - var settings = m_SceneView.sceneViewCameraSettings; + var settings = m_SceneView.cameraSettings; Styles.Init(); const int k_SettingsIconPad = 2; @@ -96,7 +101,7 @@ private void Draw(Rect rect) EditorGUI.BeginChangeCheck(); - EditorGUIUtility.labelWidth = k_PrefixLabelWidth; + EditorGUIUtility.labelWidth = kPrefixLabelWidth; GUILayout.Label(EditorGUIUtility.TrTextContent("Scene Camera"), EditorStyles.boldLabel); @@ -111,12 +116,12 @@ private void Draw(Rect rect) using (new EditorGUI.DisabledScope(settings.dynamicClip)) { float near = settings.nearClip, far = settings.farClip; - ClipPlanesField(EditorGUI.s_ClipingPlanesLabel, ref near, ref far, EditorGUI.kNearFarLabelsWidth); + DrawClipPlanesField(EditorGUI.s_ClipingPlanesLabel, ref near, ref far, EditorGUI.kNearFarLabelsWidth); settings.nearClip = near; settings.farClip = far; - settings.nearClip = Mathf.Max(k_NearClipMin, settings.nearClip); + settings.nearClip = Mathf.Max(kNearClipMin, settings.nearClip); if (settings.nearClip > settings.farClip) - settings.farClip = settings.nearClip + k_NearClipMin; + settings.farClip = settings.nearClip + kNearClipMin; } settings.occlusionCulling = EditorGUILayout.Toggle(m_OcclusionCulling, settings.occlusionCulling); @@ -126,6 +131,15 @@ private void Draw(Rect rect) GUILayout.Label(EditorGUIUtility.TrTextContent("Navigation"), EditorStyles.boldLabel); + settings.easingEnabled = EditorGUILayout.Toggle(m_EasingEnabled, settings.easingEnabled); + + using (new EditorGUI.DisabledScope(!settings.easingEnabled)) + { + EditorGUI.indentLevel += 1; + settings.easingDuration = EditorGUILayout.Slider(m_EasingDuration, settings.easingDuration, .1f, 2f); + EditorGUI.indentLevel -= 1; + } + settings.speed = EditorGUILayout.Slider(m_CameraSpeedSliderContent, settings.speed, settings.speedMin, settings.speedMax); EditorGUI.BeginChangeCheck(); @@ -133,11 +147,7 @@ private void Draw(Rect rect) m_Vector2Floats[0] = settings.speedMin; m_Vector2Floats[1] = settings.speedMax; - GUILayout.BeginHorizontal(); - GUILayout.Space(EditorGUIUtility.labelWidth); - Rect r = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight, EditorStyles.numberField); - EditorGUI.MultiFloatField(r, m_CameraSpeedMinMax, m_Vector2Floats, kMinMaxSpeedLabelWidth); - GUILayout.EndHorizontal(); + DrawSpeedMinMaxFields(); if (EditorGUI.EndChangeCheck()) settings.SetSpeedMinMax(m_Vector2Floats); @@ -147,7 +157,22 @@ private void Draw(Rect rect) GUILayout.EndArea(); } - internal static void ClipPlanesField(GUIContent label, ref float near, ref float far, float propertyLabelsWidth, params GUILayoutOption[] options) + void DrawSpeedMinMaxFields() + { + GUILayout.BeginHorizontal(); + GUILayout.Space(EditorGUIUtility.labelWidth); + Rect r = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight, EditorStyles.numberField); + r.width = kMinSpeedLabelWidth + kMinMaxSpeedFieldWidth; + EditorGUIUtility.labelWidth = kMinSpeedLabelWidth; + m_Vector2Floats[0] = EditorGUI.FloatField(r, m_CameraSpeedMin, m_Vector2Floats[0]); + r.x += r.width + kMinMaxSpeedSpace; + r.width = kMaxSpeedLabelWidth + kMinMaxSpeedFieldWidth; + EditorGUIUtility.labelWidth = kMaxSpeedLabelWidth; + m_Vector2Floats[1] = EditorGUI.FloatField(r, m_CameraSpeedMax, m_Vector2Floats[1]); + GUILayout.EndHorizontal(); + } + + void DrawClipPlanesField(GUIContent label, ref float near, ref float far, float propertyLabelsWidth, params GUILayoutOption[] options) { bool hasLabel = EditorGUI.LabelHasContent(label); const float height = EditorGUI.kSingleLineHeight * 2 + EditorGUI.kVerticalSpacingMultiField; @@ -179,7 +204,7 @@ void ShowContextMenu() void Reset() { - m_SceneView.ResetSceneViewCameraSettings(); + m_SceneView.ResetCameraSettings(); m_SceneView.Repaint(); } } diff --git a/Editor/Mono/Annotation/SceneViewSettingsProvider.cs b/Editor/Mono/Annotation/SceneViewSettingsProvider.cs deleted file mode 100644 index 19a3a88776..0000000000 --- a/Editor/Mono/Annotation/SceneViewSettingsProvider.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; - -namespace UnityEditor -{ - class SceneViewSettingsProvider : SettingsProvider - { - class Styles - { - static bool s_Initialized; - - public static GUIContent cameraMovementEasingEnabled = EditorGUIUtility.TrTextContent("Camera Easing", "Check this to enable camera movement easing. This makes the Camera ease in when it starts moving, and ease out when it stops."); - public static GUIContent cameraMovementEasingDuration = EditorGUIUtility.TrTextContent("Duration", "How long it takes for the Camera speed to accelerate to full speed. Measured in seconds."); - - public static GUIStyle settings; - - public static void Init() - { - if (s_Initialized) - return; - - s_Initialized = true; - - settings = new GUIStyle() - { - margin = new RectOffset(8, 4, 4, 4) - }; - } - } - - [SettingsProvider] - static SettingsProvider CreateSceneViewSettingsProvider() - { - return new SceneViewSettingsProvider("Preferences/Scene View"); - } - - public SceneViewSettingsProvider(string path, SettingsScope scopes = SettingsScope.User) - : base(path, scopes) - { - PopulateSearchKeywordsFromGUIContentProperties(); - } - - public override void OnGUI(string searchContext) - { - base.OnGUI(searchContext); - Styles.Init(); - var searching = !string.IsNullOrEmpty(searchContext); - - GUILayout.BeginVertical(Styles.settings, GUILayout.MaxWidth(SettingsWindow.s_DefaultLayoutMaxWidth)); - - if (!searching) - GUILayout.Label(EditorGUIUtility.TrTextContent("Navigation"), EditorStyles.boldLabel); - - if (!searching || SearchUtils.MatchSearch(searchContext, Styles.cameraMovementEasingEnabled.text)) - SceneViewMotion.movementEasingEnabled = EditorGUILayout.Toggle( - Styles.cameraMovementEasingEnabled, - SceneViewMotion.movementEasingEnabled); - - using (new EditorGUI.DisabledScope(!SceneViewMotion.movementEasingEnabled)) - { - EditorGUI.indentLevel += 1; - if (!searching || SearchUtils.MatchSearch(searchContext, Styles.cameraMovementEasingDuration.text)) - SceneViewMotion.movementEasingDuration = EditorGUILayout.Slider(Styles.cameraMovementEasingDuration, SceneViewMotion.movementEasingDuration, .1f, 3f); - EditorGUI.indentLevel -= 1; - } - - GUILayout.EndVertical(); - } - } -} diff --git a/Editor/Mono/BuildPipeline/AssemblyStripper.cs b/Editor/Mono/BuildPipeline/AssemblyStripper.cs index 833c780330..7a7240cb4a 100644 --- a/Editor/Mono/BuildPipeline/AssemblyStripper.cs +++ b/Editor/Mono/BuildPipeline/AssemblyStripper.cs @@ -303,7 +303,8 @@ private static void RunAssemblyStripper(IEnumerable assemblies, string managedAs string error; var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(platformProvider.target); bool isMono = PlayerSettings.GetScriptingBackend(buildTargetGroup) == ScriptingImplementation.Mono2x; - bool stripEngineCode = rcr != null && PlayerSettings.stripEngineCode && platformProvider.supportsEngineStripping && !platformProvider.scriptsOnlyBuild; + bool engineStrippingSupported = platformProvider.supportsEngineStripping && !isMono; + bool performEngineStripping = rcr != null && PlayerSettings.stripEngineCode && engineStrippingSupported && !platformProvider.scriptsOnlyBuild; IEnumerable blacklists = Il2CppBlacklistPaths; if (rcr != null) { @@ -327,7 +328,7 @@ private static void RunAssemblyStripper(IEnumerable assemblies, string managedAs } } - if (!stripEngineCode) + if (!performEngineStripping) { // if we don't do stripping, add all modules blacklists. foreach (var file in Directory.GetFiles(platformProvider.moduleStrippingInformationFolder, "*.xml")) @@ -359,20 +360,20 @@ private static void RunAssemblyStripper(IEnumerable assemblies, string managedAs blacklists, buildTargetGroup, managedStrippingLevel, - stripEngineCode)) + performEngineStripping)) throw new Exception("Error in stripping assemblies: " + assemblies + ", " + error); - if (platformProvider.supportsEngineStripping) + if (engineStrippingSupported) { var icallSummaryPath = Path.Combine(managedAssemblyFolderPath, "ICallSummary.txt"); GenerateInternalCallSummaryFile(icallSummaryPath, managedAssemblyFolderPath, tempStripPath); - if (stripEngineCode) + if (performEngineStripping) { // Find which modules we must include in the build based on Assemblies HashSet nativeClasses; HashSet nativeModules; - CodeStrippingUtils.GenerateDependencies(tempStripPath, icallSummaryPath, rcr, stripEngineCode, out nativeClasses, out nativeModules, platformProvider); + CodeStrippingUtils.GenerateDependencies(tempStripPath, icallSummaryPath, rcr, performEngineStripping, out nativeClasses, out nativeModules, platformProvider); // Add module-specific blacklists. addedMoreBlacklists = AddWhiteListsForModules(nativeModules, ref blacklists, platformProvider.moduleStrippingInformationFolder); } diff --git a/Editor/Mono/Camera/EditorCameraUtils.bindings.cs b/Editor/Mono/Camera/EditorCameraUtils.bindings.cs new file mode 100644 index 0000000000..39d1798fe8 --- /dev/null +++ b/Editor/Mono/Camera/EditorCameraUtils.bindings.cs @@ -0,0 +1,22 @@ +// Unity C# reference source +// Copyright (c) Unity Technologies. For terms of use, see +// https://unity3d.com/legal/licenses/Unity_Reference_Only_License + +using UnityEngine; +using UnityEngine.Bindings; +using UnityEngine.Internal; +using UnityEngine.Scripting; + +namespace UnityEditor.Rendering +{ + [NativeHeader("Editor/Src/Camera/EditorCameraUtils.h")] + [RequiredByNativeCode] + public static class EditorCameraUtils + { + public static bool RenderToCubemap(this Camera camera, Texture target, int faceMask, StaticEditorFlags culledFlags) + => RenderToCubemapImpl(camera, target, faceMask, culledFlags) == 1; + + [FreeFunction("EditorCameraUtilsScripting::RenderToCubemap")] + static extern int RenderToCubemapImpl(Camera camera, Texture target, [DefaultValue("63")] int faceMask, StaticEditorFlags culledFlags); + } +} diff --git a/Editor/Mono/ConsoleWindow.cs b/Editor/Mono/ConsoleWindow.cs index 7373ceb417..802cbc1cb4 100644 --- a/Editor/Mono/ConsoleWindow.cs +++ b/Editor/Mono/ConsoleWindow.cs @@ -369,7 +369,7 @@ static internal GUIStyle GetStyleForErrorMode(int mode, bool isIcon, bool isSmal if (HasMode(mode, Mode.Fatal | Mode.Assert | Mode.Error | Mode.ScriptingError | Mode.AssetImportError | Mode.ScriptCompileError | - Mode.GraphCompileError | Mode.ScriptingAssertion)) + Mode.GraphCompileError | Mode.ScriptingAssertion | Mode.ScriptingException)) { if (isIcon) { diff --git a/Editor/Mono/EditorWindow.cs b/Editor/Mono/EditorWindow.cs index 823b0e5948..1ba5751caf 100644 --- a/Editor/Mono/EditorWindow.cs +++ b/Editor/Mono/EditorWindow.cs @@ -10,8 +10,7 @@ using UnityEngine.Internal; using Unity.Experimental.EditorMode; -using SerializableJsonDictionary = UnityEditor.Experimental.UIElements.SerializableJsonDictionary; -using ExperimentalVisualElement = UnityEngine.Experimental.UIElements.VisualElement; +using SerializableJsonDictionary = UnityEditor.UIElements.SerializableJsonDictionary; using UnityEngine.UIElements; using UnityEditor.UIElements; @@ -48,26 +47,6 @@ public partial class EditorWindow : ScriptableObject private readonly Dictionary m_RootElementPerEditorMode = new Dictionary(); - //temporary for backward compatibility - internal ExperimentalVisualElement m_RootVisualContainer; - internal ExperimentalVisualElement rootVisualContainer - { - get - { - if (m_RootVisualContainer == null) - { - m_RootVisualContainer = new ExperimentalVisualElement() - { - name = VisualElementUtils.GetUniqueName("rootVisualContainer"), - pickingMode = UnityEngine.Experimental.UIElements.PickingMode.Ignore, // do not eat events so IMGUI gets them - persistenceKey = name - }; - UnityEditor.Experimental.UIElements.UIElementsEditorUtility.AddDefaultEditorStyleSheets(m_RootVisualContainer); - } - return m_RootVisualContainer; - } - } - public VisualElement rootVisualElement { get @@ -678,24 +657,10 @@ internal void ShowModal() ShowWithMode(ShowMode.AuxWindow); SavedGUIState guiState = SavedGUIState.Create(); - if (m_Parent.uieMode == GUIView.UIElementsMode.Public) - { - m_Parent.visualTree.panel.dispatcher?.PushDispatcherContext(); - } - else if (m_Parent.uieMode == GUIView.UIElementsMode.Experimental) - { - m_Parent.experimentalVisualTree.panel.dispatcher?.PushDispatcherContext(); - } + m_Parent.visualTree.panel.dispatcher?.PushDispatcherContext(); MakeModal(m_Parent.window); - if (m_Parent.uieMode == GUIView.UIElementsMode.Public) - { - m_Parent.visualTree.panel.dispatcher?.PopDispatcherContext(); - } - else if (m_Parent.uieMode == GUIView.UIElementsMode.Experimental) - { - m_Parent.experimentalVisualTree.panel.dispatcher?.PopDispatcherContext(); - } + m_Parent.visualTree.panel.dispatcher?.PopDispatcherContext(); guiState.ApplyAndForget(); } @@ -1111,9 +1076,6 @@ public Rect position private void RefreshStylesAfterExternalEvent() { - if (m_Parent.uieMode != GUIView.UIElementsMode.Public) - return; - var panel = m_Parent.visualTree.elementPanel; if (panel == null) return; @@ -1193,35 +1155,6 @@ internal class EditorWindowTitleAttribute : System.Attribute public bool useTypeNameAsIconName { get; set; } } - // makes UIElements opt-in while it's experimental, as a using statement is necessary to call this method - namespace Experimental.UIElements - { - public static class UIElementsEntryPoint - { - public static ExperimentalVisualElement GetRootVisualContainer(this EditorWindow window) - { - var result = window.rootVisualContainer; - - //this nasty code is temporary, thank god! - if (result.panel == null && window.m_Parent != null && window.m_Parent.actualView == window) - { - window.m_Parent.RegisterExperimentalUIElementWindow(); - } - - return result; - } - - public static void SetAntiAliasing(this EditorWindow window, int aa) - { - window.antiAliasing = aa; - } - - public static int GetAntiAliasing(this EditorWindow window) - { - return window.antiAliasing; - } - } - } namespace UIElements { public static class UIElementsEntryPoint diff --git a/Editor/Mono/GUI/DockArea.cs b/Editor/Mono/GUI/DockArea.cs index 55ae29a7c5..d67b03afa0 100644 --- a/Editor/Mono/GUI/DockArea.cs +++ b/Editor/Mono/GUI/DockArea.cs @@ -161,19 +161,11 @@ protected override void OnEnable() base.OnEnable(); - if (uieMode == UIElementsMode.Experimental) + if (imguiContainer != null) { - if (experimentalImguiContainer != null) - experimentalImguiContainer.name = VisualElementUtils.GetUniqueName("Dockarea"); - } - else - { - if (imguiContainer != null) - { - imguiContainer.name = VisualElementUtils.GetUniqueName("Dockarea"); - imguiContainer.tabIndex = -1; - imguiContainer.focusOnlyIfHasFocusableControls = false; - } + imguiContainer.name = VisualElementUtils.GetUniqueName("Dockarea"); + imguiContainer.tabIndex = -1; + imguiContainer.focusOnlyIfHasFocusableControls = false; } } diff --git a/Editor/Mono/GUI/Tools/EditorToolContext.cs b/Editor/Mono/GUI/Tools/EditorToolContext.cs index f41c827779..330e20526f 100644 --- a/Editor/Mono/GUI/Tools/EditorToolContext.cs +++ b/Editor/Mono/GUI/Tools/EditorToolContext.cs @@ -275,6 +275,7 @@ void RestoreCustomEditorTool() var targets = restored.targets.ToArray(); EditorJsonUtility.FromJsonOverwrite(m_PreviousCustomEditorToolContext.editorToolState, restored); restored.m_Targets = targets; + restored.m_Target = targets.Last(); activeTool = restored; } @@ -438,9 +439,9 @@ void RebuildAvailableCustomEditorTools() bool CollectCustomEditorToolsFromTracker(ActiveEditorTracker tracker, List list) { + list.Clear(); var activeIsCustomEditorTool = IsCustomEditorTool(m_ActiveTool); var preservedActiveTool = false; - s_CustomEditorTools.Clear(); EditorToolUtility.GetEditorToolsForTracker(tracker, s_CustomEditorTools); @@ -553,7 +554,7 @@ internal static void GetCustomEditorTools(List list, bool includeLoc internal static void GetCustomEditorToolsForTarget(UnityObject target, List list, bool searchLockedInspectors) { - s_CustomEditorTools.Clear(); + list.Clear(); if (target == null) return; diff --git a/Editor/Mono/GUI/Tools/EditorToolUtility.cs b/Editor/Mono/GUI/Tools/EditorToolUtility.cs index 660325c704..33e72ce19a 100644 --- a/Editor/Mono/GUI/Tools/EditorToolUtility.cs +++ b/Editor/Mono/GUI/Tools/EditorToolUtility.cs @@ -9,6 +9,9 @@ namespace UnityEditor.EditorTools { + /// + /// An Editor instance and EditorTool type. + /// struct CustomEditorTool { public Editor owner; @@ -136,6 +139,8 @@ internal static Type GetCustomEditorToolTargetType(EditorTool tool) internal static void GetEditorToolsForTracker(ActiveEditorTracker tracker, List tools) { + tools.Clear(); + var editors = tracker.activeEditors; for (int i = 0, c = editors.Length; i < c; i++) diff --git a/Editor/Mono/GUIView.cs b/Editor/Mono/GUIView.cs index 28c06b2b37..67362bb72a 100644 --- a/Editor/Mono/GUIView.cs +++ b/Editor/Mono/GUIView.cs @@ -11,11 +11,6 @@ using UnityEngine.UIElements.StyleSheets; using UnityEngine.Scripting; -//temporary until everyone is out of experimental -using ExperimentalUI = UnityEngine.Experimental.UIElements; -using EditorExperimentalUI = UnityEditor.Experimental.UIElements; - - namespace UnityEditor { // This is what we (not users) derive from to create various views. (Main Toolbar, etc.) @@ -28,10 +23,6 @@ internal partial class GUIView : View readonly EditorCursorManager m_CursorManager = new EditorCursorManager(); static EditorContextualMenuManager s_ContextualMenuManager = new EditorContextualMenuManager(); - internal ExperimentalUI.Panel m_ExperimentalPanel = null; - readonly EditorExperimentalUI.EditorCursorManager m_ExperimentalCursorManager = new EditorExperimentalUI.EditorCursorManager(); - static EditorExperimentalUI.EditorContextualMenuManager s_ExperimentalContextualMenuManager = new EditorExperimentalUI.EditorContextualMenuManager(); - static Shader s_EditorShader = null; static Shader EditorShader @@ -53,11 +44,6 @@ protected Panel panel { if (m_Panel == null) { - if (m_ExperimentalPanel != null) - { - throw new InvalidOperationException("UIElements can't run in Experimental and Public mode at the same time. Please update your code to use the UnityEngine.UIElements namespace. Use SwitchUIElementMode() to change namespaces"); - } - uieMode = GUIView.UIElementsMode.Public; m_Panel = UIElementsUtility.FindOrCreatePanel(this, ContextType.Editor); m_Panel.name = GetType().Name; m_Panel.cursorManager = m_CursorManager; @@ -75,84 +61,8 @@ protected Panel panel } } - protected ExperimentalUI.Panel experimentalPanel - { - get - { - if (m_ExperimentalPanel == null) - { - if (m_Panel != null) - { - throw new InvalidOperationException("UIElements can't run in Experimental and Public mode at the same time. Please update your code to use the UnityEngine.UIElements namespace. Use SwitchUIElementMode() to change namespaces"); - } - uieMode = UIElementsMode.Experimental; - EditorExperimentalUI.UXMLEditorFactories.RegisterAll(); - m_ExperimentalPanel = ExperimentalUI.UIElementsUtility.FindOrCreatePanel(this, ExperimentalUI.ContextType.Editor, DataWatchService.sharedInstance); - m_ExperimentalPanel.cursorManager = m_ExperimentalCursorManager; - m_ExperimentalPanel.contextualMenuManager = s_ExperimentalContextualMenuManager; - m_ExperimentalPanel.panelDebug = new EditorExperimentalUI.PanelDebug(m_ExperimentalPanel); - - if (experimentalImguiContainer != null) - m_ExperimentalPanel.visualTree.Insert(0, experimentalImguiContainer); - - m_ExperimentalPanel.visualTree.SetSize(windowPosition.size); - } - - return m_ExperimentalPanel; - } - } - - //Remove this once we remove the Experimental namespace - internal enum UIElementsMode - { - Unset, - Experimental, - Public, - } - - internal UIElementsMode m_UIElementsMode = UIElementsMode.Unset; - public UnityEditor.GUIView.UIElementsMode uieMode - { - get { return m_UIElementsMode; } - set { m_UIElementsMode = value; } - } - - internal void SwitchUIElementsMode(UIElementsMode mode) - { - if (mode == UIElementsMode.Experimental) - { - if (m_Panel != null) - { - imguiContainer.RemoveFromHierarchy(); - m_Panel.Dispose(); - m_Panel = null; - } - - if (m_ExperimentalPanel == null) - { - var p = experimentalPanel; - } - } - else - { - if (m_ExperimentalPanel != null) - { - experimentalImguiContainer.RemoveFromHierarchy(); - m_ExperimentalPanel.Dispose(); - m_ExperimentalPanel = null; - } - if (m_Panel == null) - { - var p = panel; - } - } - } - public VisualElement visualTree => panel.visualTree; - public ExperimentalUI.VisualElement experimentalVisualTree => experimentalPanel.visualTree; - protected IMGUIContainer imguiContainer { get; private set; } - protected ExperimentalUI.IMGUIContainer experimentalImguiContainer { get; private set; } int m_DepthBufferBits = 0; int m_AntiAliasing = 1; @@ -186,15 +96,7 @@ protected override void SetWindow(ContainerWindow win) Internal_SetWantsMouseMove(m_EventInterests.wantsMouseMove); Internal_SetWantsMouseEnterLeaveWindow(m_EventInterests.wantsMouseMove); - if (m_ExperimentalPanel != null) - { - m_ExperimentalPanel.visualTree.SetSize(windowPosition.size); - } - else - { - panel.visualTree.SetSize(windowPosition.size); - } - + panel.visualTree.SetSize(windowPosition.size); m_BackgroundValid = false; } @@ -211,15 +113,7 @@ public EventInterests eventInterests set { m_EventInterests = value; - - if (m_ExperimentalPanel != null) - { - m_ExperimentalPanel.IMGUIEventInterests = m_EventInterests; - } - else - { - panel.IMGUIEventInterests = m_EventInterests; - } + panel.IMGUIEventInterests = m_EventInterests; Internal_SetWantsMouseMove(wantsMouseMove); Internal_SetWantsMouseEnterLeaveWindow(wantsMouseEnterLeaveWindow); @@ -232,15 +126,7 @@ public bool wantsMouseMove set { m_EventInterests.wantsMouseMove = value; - - if (m_ExperimentalPanel != null) - { - m_ExperimentalPanel.IMGUIEventInterests = m_EventInterests; - } - else - { - panel.IMGUIEventInterests = m_EventInterests; - } + panel.IMGUIEventInterests = m_EventInterests; Internal_SetWantsMouseMove(wantsMouseMove); } @@ -252,15 +138,7 @@ public bool wantsMouseEnterLeaveWindow set { m_EventInterests.wantsMouseEnterLeaveWindow = value; - - if (m_ExperimentalPanel != null) - { - m_ExperimentalPanel.IMGUIEventInterests = m_EventInterests; - } - else - { - panel.IMGUIEventInterests = m_EventInterests; - } + panel.IMGUIEventInterests = m_EventInterests; Internal_SetWantsMouseEnterLeaveWindow(wantsMouseEnterLeaveWindow); } @@ -299,14 +177,6 @@ public int antiAlias protected virtual void OnEnable() { - { - experimentalImguiContainer = new ExperimentalUI.IMGUIContainer(OldOnGUI) { useOwnerObjectGUIState = true }; - ExperimentalUI.VisualElementExtensions.StretchToParentSize(experimentalImguiContainer); - experimentalImguiContainer.persistenceKey = "Dockarea"; - - if (m_ExperimentalPanel != null) - m_ExperimentalPanel.visualTree.Insert(0, experimentalImguiContainer); - } { imguiContainer = new IMGUIContainer(OldOnGUI) { useOwnerObjectGUIState = true }; imguiContainer.StretchToParentSize(); @@ -322,32 +192,16 @@ protected virtual void OnEnable() protected virtual void OnDisable() { - if (uieMode == UIElementsMode.Experimental) - { - if (ExperimentalUI.MouseCaptureController.HasMouseCapture(experimentalImguiContainer)) - MouseCaptureController.ReleaseMouse(); - experimentalImguiContainer.RemoveFromHierarchy(); - experimentalImguiContainer = null; + if (imguiContainer.HasMouseCapture()) + MouseCaptureController.ReleaseMouse(); + imguiContainer.RemoveFromHierarchy(); + imguiContainer = null; - if (m_ExperimentalPanel != null) - { - m_ExperimentalPanel.Dispose(); - /// We don't set m_Panel to null to prevent it from being re-created from panel. - } - } - else + if (m_Panel != null) { - if (imguiContainer.HasMouseCapture()) - MouseCaptureController.ReleaseMouse(); - imguiContainer.RemoveFromHierarchy(); - imguiContainer = null; - - if (m_Panel != null) - { - UpdateDrawChainRegistration(false); - m_Panel.Dispose(); - /// We don't set m_Panel to null to prevent it from being re-created from panel. - } + UpdateDrawChainRegistration(false); + m_Panel.Dispose(); + /// We don't set m_Panel to null to prevent it from being re-created from panel. } Panel.BeforeUpdaterChange -= OnBeforeUpdaterChange; @@ -409,14 +263,7 @@ protected override void SetPosition(Rect newPos) m_BackgroundValid = false; - if (m_ExperimentalPanel != null) - { - m_ExperimentalPanel.visualTree.SetSize(windowPosition.size); - } - else - { - panel.visualTree.SetSize(windowPosition.size); - } + panel.visualTree.SetSize(windowPosition.size); positionChanged?.Invoke(this); diff --git a/Editor/Mono/HostView.cs b/Editor/Mono/HostView.cs index be86bb7e40..af85c25720 100644 --- a/Editor/Mono/HostView.cs +++ b/Editor/Mono/HostView.cs @@ -7,7 +7,6 @@ using System.Reflection; using UnityEditor.UIElements.Debugger; using UnityEngine.UIElements; -using ExperimentalUI = UnityEngine.Experimental.UIElements; using Unity.Experimental.EditorMode; namespace UnityEditor @@ -61,24 +60,12 @@ protected void UpdateViewMargins(EditorWindow view) RectOffset margins = GetBorderSize(); - if (view.m_RootVisualContainer != null) - { - var style = view.m_RootVisualContainer.style; - style.positionTop = margins.top; - style.positionBottom = margins.bottom; - style.positionLeft = margins.left; - style.positionRight = margins.right; - style.positionType = ExperimentalUI.StyleEnums.PositionType.Absolute; - } - else - { - IStyle style = EditorModes.GetRootElement(view).style; - style.top = margins.top; - style.bottom = margins.bottom; - style.left = margins.left; - style.right = margins.right; - style.position = Position.Absolute; - } + IStyle style = EditorModes.GetRootElement(view).style; + style.top = margins.top; + style.bottom = margins.bottom; + style.left = margins.left; + style.right = margins.right; + style.position = Position.Absolute; } protected override void SetPosition(Rect newPos) @@ -361,16 +348,6 @@ protected void Invoke(string methodName, object obj) mi?.Invoke(obj, null); } - internal void RegisterExperimentalUIElementWindow() - { - SwitchUIElementsMode(GUIView.UIElementsMode.Experimental); - experimentalVisualTree.Add(m_ActualView.m_RootVisualContainer); - - m_ExperimentalPanel.getViewDataDictionary = m_ActualView.GetViewDataDictionary; - m_ExperimentalPanel.savePersistentViewData = m_ActualView.SaveViewData; - m_ExperimentalPanel.name = m_ActualView.GetType().Name; - } - protected void RegisterSelectedPane(bool sendEvents) { if (!m_ActualView) @@ -378,18 +355,10 @@ protected void RegisterSelectedPane(bool sendEvents) m_ActualView.m_Parent = this; - if (m_ActualView.m_RootVisualContainer != null) - { - RegisterExperimentalUIElementWindow(); - } - else - { - SwitchUIElementsMode(GUIView.UIElementsMode.Public); - visualTree.Add(EditorModes.GetRootElement(m_ActualView)); - panel.getViewDataDictionary = m_ActualView.GetViewDataDictionary; - panel.saveViewData = m_ActualView.SaveViewData; - panel.name = m_ActualView.GetType().Name; - } + visualTree.Add(EditorModes.GetRootElement(m_ActualView)); + panel.getViewDataDictionary = m_ActualView.GetViewDataDictionary; + panel.saveViewData = m_ActualView.SaveViewData; + panel.name = m_ActualView.GetType().Name; if (GetPaneMethod("Update") != null) EditorApplication.update += SendUpdate; @@ -432,25 +401,13 @@ protected void DeregisterSelectedPane(bool clearActualView, bool sendEvents) { if (!m_ActualView) return; - if (m_ActualView.m_RootVisualContainer != null) + + var root = EditorModes.GetRootElement(m_ActualView); + if (root.hierarchy.parent == visualTree) { - var root = m_ActualView.m_RootVisualContainer; - if (m_ExperimentalPanel != null && root.shadow.parent == m_ExperimentalPanel.visualTree) - { - root.RemoveFromHierarchy(); - experimentalPanel.getViewDataDictionary = null; - experimentalPanel.savePersistentViewData = null; - } - } - else - { - var root = EditorModes.GetRootElement(m_ActualView); - if (root.hierarchy.parent == visualTree) - { - root.RemoveFromHierarchy(); - panel.getViewDataDictionary = null; - panel.saveViewData = null; - } + root.RemoveFromHierarchy(); + panel.getViewDataDictionary = null; + panel.saveViewData = null; } if (GetPaneMethod("Update") != null) @@ -569,14 +526,7 @@ internal void DebugWindow(object userData) if (window == null) return; - if (window.m_RootVisualContainer != null) - { - UnityEditor.Experimental.UIElements.Debugger.UIElementsDebugger.OpenAndInspectWindow(window); - } - else - { - UIElementsDebugger.OpenAndInspectWindow(window); - } + UIElementsDebugger.OpenAndInspectWindow(window); } internal void Reload(object userData) diff --git a/Editor/Mono/Inspector/LightEditor.cs b/Editor/Mono/Inspector/LightEditor.cs index 55b7a05fbb..4ddb6d7064 100644 --- a/Editor/Mono/Inspector/LightEditor.cs +++ b/Editor/Mono/Inspector/LightEditor.cs @@ -40,6 +40,7 @@ public sealed class Settings public SerializedProperty flare { get; private set; } public SerializedProperty renderMode { get; private set; } public SerializedProperty cullingMask { get; private set; } + public SerializedProperty renderingLayerMask { get; private set; } public SerializedProperty lightmapping { get; private set; } public SerializedProperty areaSizeX { get; private set; } public SerializedProperty areaSizeY { get; private set; } @@ -97,6 +98,7 @@ private static class Styles public static readonly GUIContent Flare = EditorGUIUtility.TrTextContent("Flare", "Specifies the flare object to be used by the light to render lens flares in the scene."); public static readonly GUIContent RenderMode = EditorGUIUtility.TrTextContent("Render Mode", "Specifies the importance of the light which impacts lighting fidelity and performance. Options are Auto, Important, and Not Important. This only affects Forward Rendering."); public static readonly GUIContent CullingMask = EditorGUIUtility.TrTextContent("Culling Mask", "Specifies which layers will be affected or excluded from the light's effect on objects in the scene."); + public static readonly GUIContent RenderingLayerMask = EditorGUIUtility.TrTextContent("Rendering Layer Mask", "Mask that can be used with SRP when drawing shadows to filter renderers outside of the normal layering system."); public static readonly GUIContent AreaWidth = EditorGUIUtility.TrTextContent("Width", "Controls the width in units of the area light."); public static readonly GUIContent AreaHeight = EditorGUIUtility.TrTextContent("Height", "Controls the height in units of the area light."); @@ -187,6 +189,7 @@ public void OnEnable() flare = m_SerializedObject.FindProperty("m_Flare"); renderMode = m_SerializedObject.FindProperty("m_RenderMode"); cullingMask = m_SerializedObject.FindProperty("m_CullingMask"); + renderingLayerMask = m_SerializedObject.FindProperty("m_RenderingLayerMask"); lightmapping = m_SerializedObject.FindProperty("m_Lightmapping"); areaSizeX = m_SerializedObject.FindProperty("m_AreaSize.x"); areaSizeY = m_SerializedObject.FindProperty("m_AreaSize.y"); @@ -470,6 +473,27 @@ public void DrawCullingMask() EditorGUILayout.PropertyField(cullingMask, Styles.CullingMask); } + public void DrawRenderingLayerMask() + { + RenderPipelineAsset srpAsset = GraphicsSettings.renderPipelineAsset; + bool usingSRP = srpAsset != null; + if (!usingSRP) + return; + + EditorGUI.showMixedValue = renderingLayerMask.hasMultipleDifferentValues; + + var mask = renderingLayerMask.intValue; + var layerNames = srpAsset.renderingLayerMaskNames; + if (layerNames == null) + layerNames = RendererEditorBase.defaultRenderingLayerNames; + + var rect = EditorGUILayout.GetControlRect(); + EditorGUI.BeginProperty(rect, Styles.RenderingLayerMask, renderingLayerMask); + EditorGUI.MaskField(rect, Styles.RenderingLayerMask, mask, layerNames); + EditorGUI.EndProperty(); + EditorGUI.showMixedValue = false; + } + public void ApplyModifiedProperties() { m_SerializedObject.ApplyModifiedProperties(); @@ -742,6 +766,7 @@ public override void OnInspectorGUI() settings.DrawFlare(); settings.DrawRenderMode(); settings.DrawCullingMask(); + settings.DrawRenderingLayerMask(); EditorGUILayout.Space(); if (SceneView.lastActiveSceneView != null && SceneView.lastActiveSceneView.sceneLighting == false) diff --git a/Editor/Mono/Inspector/PreviewWindow.cs b/Editor/Mono/Inspector/PreviewWindow.cs index 15ffde94ae..aa8ee3978b 100644 --- a/Editor/Mono/Inspector/PreviewWindow.cs +++ b/Editor/Mono/Inspector/PreviewWindow.cs @@ -3,7 +3,7 @@ // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; -using UnityEngine.Experimental.UIElements; +using UnityEngine.UIElements; namespace UnityEditor { @@ -14,7 +14,7 @@ internal class PreviewWindow : InspectorWindow VisualElement m_previewElement; - VisualElement previewElement => m_previewElement ?? (m_previewElement = rootVisualContainer.Q("preview")); + VisualElement previewElement => m_previewElement ?? (m_previewElement = rootVisualElement.Q("preview")); public void SetParentInspector(InspectorWindow inspector) { @@ -31,11 +31,11 @@ protected override void OnEnable() AddInspectorWindow(this); var tpl = EditorGUIUtility.Load("UXML/InspectorWindow/PreviewWindow.uxml") as VisualTreeAsset; - var container = tpl.CloneTree(null); + var container = tpl.CloneTree(); container.AddToClassList("mainContainer"); - rootVisualContainer.shadow.Add(container); + rootVisualElement.hierarchy.Add(container); - rootVisualContainer.AddStyleSheetPath("StyleSheets/InspectorWindow/PreviewWindow.uss"); + rootVisualElement.AddStyleSheetPath("StyleSheets/InspectorWindow/PreviewWindow.uss"); RebuildContentsContainers(); } diff --git a/Editor/Mono/Inspector/QualitySettingsEditor.cs b/Editor/Mono/Inspector/QualitySettingsEditor.cs index 507fe01fe7..b925702d45 100644 --- a/Editor/Mono/Inspector/QualitySettingsEditor.cs +++ b/Editor/Mono/Inspector/QualitySettingsEditor.cs @@ -524,7 +524,13 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(pixelLightCountProperty); // still valid with SRP + EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(textureQualityProperty); + if (EditorGUI.EndChangeCheck() && usingSRP) + { + RenderPipelineManager.CleanupRenderPipeline(); + } + EditorGUILayout.PropertyField(anisotropicTexturesProperty); if (!usingSRP) diff --git a/Editor/Mono/Inspector/RendererEditorBase.cs b/Editor/Mono/Inspector/RendererEditorBase.cs index f567240b5d..339ab364cf 100644 --- a/Editor/Mono/Inspector/RendererEditorBase.cs +++ b/Editor/Mono/Inspector/RendererEditorBase.cs @@ -305,7 +305,7 @@ internal static string[] GetFieldsStringArray() } private static string[] m_DefaultRenderingLayerNames; - private static string[] defaultRenderingLayerNames + internal static string[] defaultRenderingLayerNames { get { diff --git a/Editor/Mono/Inspector/ScriptExecutionOrderInspector.cs b/Editor/Mono/Inspector/ScriptExecutionOrderInspector.cs index 8a9692060e..e46cb66d38 100644 --- a/Editor/Mono/Inspector/ScriptExecutionOrderInspector.cs +++ b/Editor/Mono/Inspector/ScriptExecutionOrderInspector.cs @@ -134,6 +134,7 @@ public void OnEnable() if (!m_Instances.Contains(this)) m_Instances.Add(this); + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } diff --git a/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs b/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs index fda108a9ea..6b9f103e66 100644 --- a/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs +++ b/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs @@ -87,6 +87,8 @@ private static class Styles public static GUIContent streamTangentText = EditorGUIUtility.TrTextContent("Tangent (TANGENT.xyzw)"); public static GUIContent streamApplyToAllSystemsText = EditorGUIUtility.TrTextContent("Apply to Systems", "Apply the vertex stream layout to all Particle Systems using this material"); + + public static string undoApplyCustomVertexStreams = L10n.Tr("Apply custom vertex streams from material"); } MaterialProperty blendMode = null; @@ -477,7 +479,7 @@ void DoVertexStreamsArea(Material material) // Display list of streams required to make this shader work bool useLighting = (material.GetFloat("_LightingEnabled") > 0.0f); bool useFlipbookBlending = (material.GetFloat("_FlipbookMode") > 0.0f); - bool useTangents = material.GetTexture("_BumpMap") && useLighting; + bool useTangents = useLighting && material.GetTexture("_BumpMap"); bool useGPUInstancing = ShaderUtil.HasProceduralInstancing(material.shader); if (useGPUInstancing && m_RenderersUsingThisMaterial.Count > 0) @@ -535,6 +537,8 @@ void DoVertexStreamsArea(Material material) // Set the streams on all systems using this material if (GUILayout.Button(Styles.streamApplyToAllSystemsText, EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { + Undo.RecordObjects(m_RenderersUsingThisMaterial.Where(r => r != null).ToArray(), Styles.undoApplyCustomVertexStreams); + foreach (ParticleSystemRenderer renderer in m_RenderersUsingThisMaterial) { if (renderer != null) @@ -717,7 +721,7 @@ void SetMaterialKeywords(Material material) // (MaterialProperty value might come from renderer material property block) bool useDistortion = !hasZWrite && (material.GetFloat("_DistortionEnabled") > 0.0f); SetKeyword(material, "_NORMALMAP", (useLighting || useDistortion) && material.GetTexture("_BumpMap")); - SetKeyword(material, "_METALLICGLOSSMAP", useLighting && (material.GetTexture("_MetallicGlossMap") != null)); + SetKeyword(material, "_METALLICGLOSSMAP", useLighting && material.GetTexture("_MetallicGlossMap")); material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.None; SetKeyword(material, "_EMISSION", material.GetFloat("_EmissionEnabled") > 0.0f); diff --git a/Editor/Mono/InternalEditorUtility.cs b/Editor/Mono/InternalEditorUtility.cs index 0e651502de..7c92ae9991 100644 --- a/Editor/Mono/InternalEditorUtility.cs +++ b/Editor/Mono/InternalEditorUtility.cs @@ -42,7 +42,7 @@ public static Texture2D FindIconForFile(string fileName) case "anim": return EditorGUIUtility.FindTexture(typeof(Animation)); case "meta": return EditorGUIUtility.FindTexture("MetaFile Icon"); case "mixer": return EditorGUIUtility.FindTexture(typeof(UnityEditor.Audio.AudioMixerController)); - case "uxml": return EditorGUIUtility.FindTexture(typeof(UnityEngine.Experimental.UIElements.VisualTreeAsset)); + case "uxml": return EditorGUIUtility.FindTexture(typeof(UnityEngine.UIElements.VisualTreeAsset)); case "uss": return EditorGUIUtility.FindTexture(typeof(StyleSheet)); case "ttf": case "otf": case "fon": case "fnt": diff --git a/Editor/Mono/Prefabs/PrefabUtility.bindings.cs b/Editor/Mono/Prefabs/PrefabUtility.bindings.cs index 08a6acc617..f62ec8e663 100644 --- a/Editor/Mono/Prefabs/PrefabUtility.bindings.cs +++ b/Editor/Mono/Prefabs/PrefabUtility.bindings.cs @@ -86,7 +86,7 @@ public sealed partial class PrefabUtility [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] - extern static private Object InstantiatePrefab_internal(Object target, Scene destinationScene); + extern static private Object InstantiatePrefab_internal(Object target, Scene destinationScene, Transform parent); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] diff --git a/Editor/Mono/Prefabs/PrefabUtility.cs b/Editor/Mono/Prefabs/PrefabUtility.cs index c670ce24a8..d9e97de39f 100644 --- a/Editor/Mono/Prefabs/PrefabUtility.cs +++ b/Editor/Mono/Prefabs/PrefabUtility.cs @@ -1342,13 +1342,18 @@ public static GameObject CreatePrefab(string path, GameObject go, ReplacePrefabO // Instantiates the given prefab. public static Object InstantiatePrefab(Object assetComponentOrGameObject) { - return InstantiatePrefab_internal(assetComponentOrGameObject, EditorSceneManager.GetTargetSceneForNewGameObjects()); + return InstantiatePrefab_internal(assetComponentOrGameObject, EditorSceneManager.GetTargetSceneForNewGameObjects(), null); } // Instantiates the given prefab in a given scene public static Object InstantiatePrefab(Object assetComponentOrGameObject, Scene destinationScene) { - return InstantiatePrefab_internal(assetComponentOrGameObject, destinationScene); + return InstantiatePrefab_internal(assetComponentOrGameObject, destinationScene, null); + } + + public static Object InstantiatePrefab(Object assetComponentOrGameObject, Transform parent) + { + return InstantiatePrefab_internal(assetComponentOrGameObject, EditorSceneManager.GetTargetSceneForNewGameObjects(), parent); } [Obsolete("Use SaveAsPrefabAsset with a path instead.")] diff --git a/Editor/Mono/RetainedMode.cs b/Editor/Mono/RetainedMode.cs index d484034930..5e8d7aeac8 100644 --- a/Editor/Mono/RetainedMode.cs +++ b/Editor/Mono/RetainedMode.cs @@ -13,10 +13,8 @@ using UnityEngine.UIElements.StyleSheets; using UnityEngine.Scripting; -using UXMLImporterImpl = UnityEditor.Experimental.UIElements.UXMLImporterImpl; +using UXMLImporterImpl = UnityEditor.UIElements.UXMLImporterImpl; -using ExperimentalUI = UnityEngine.Experimental.UIElements; -using EditorExperimentalUI = UnityEditor.Experimental.UIElements; namespace UnityEditor { @@ -38,16 +36,9 @@ static RetainedMode() UIElementsUtility.s_BeginContainerCallback = OnBeginContainer; UIElementsUtility.s_EndContainerCallback = OnEndContainer; - ExperimentalUI.UIElementsUtility.s_BeginContainerCallback = (v) => OnBeginContainer(null); - ExperimentalUI.UIElementsUtility.s_EndContainerCallback = (v) => OnEndContainer(null); - Panel.loadResourceFunc = StyleSheetResourceUtil.LoadResource; StyleSheetApplicator.getCursorIdFunc = UIElementsEditorUtility.GetCursorId; Panel.TimeSinceStartup = () => (long)(EditorApplication.timeSinceStartup * 1000.0f); - - ExperimentalUI.Panel.loadResourceFunc = StyleSheetResourceUtil.LoadResource; - ExperimentalUI.StyleSheets.StyleSheetApplicator.getCursorIdFunc = EditorExperimentalUI.UIElementsEditorUtility.GetCursorId; - ExperimentalUI.Panel.TimeSinceStartup = () => (long)(EditorApplication.timeSinceStartup * 1000.0f); } static void OnBeginContainer(IMGUIContainer c) @@ -72,78 +63,37 @@ static void UpdateSchedulers() { DataWatchService.sharedInstance.PollNativeData(); + UIElementsUtility.GetAllPanels(panelsIteration); + foreach (var panel in panelsIteration) { - UIElementsUtility.GetAllPanels(panelsIteration); - foreach (var panel in panelsIteration) - { - // Game panels' scheduler are ticked by the engine - if (panel.contextType != ContextType.Editor) - continue; - - // Dispatch all timer update messages to each scheduled item - panel.timerEventScheduler.UpdateScheduledEvents(); - panel.UpdateBindings(); - } - } - - //temporary Experimental wrapper - { - var iterator = ExperimentalUI.UIElementsUtility.GetPanelsIterator(); - while (iterator.MoveNext()) - { - var panel = iterator.Current.Value; + // Game panels' scheduler are ticked by the engine + if (panel.contextType != ContextType.Editor) + continue; - // Game panels' scheduler are ticked by the engine - if (panel.contextType != ExperimentalUI.ContextType.Editor) - continue; - - // Dispatch all timer update messages to each scheduled item - panel.timerEventScheduler.UpdateScheduledEvents(); - panel.UpdateBindings(); - } + // Dispatch all timer update messages to each scheduled item + panel.timerEventScheduler.UpdateScheduledEvents(); + panel.UpdateBindings(); } } [RequiredByNativeCode] static void RequestRepaintForPanels() { + var iterator = UIElementsUtility.GetPanelsIterator(); + while (iterator.MoveNext()) { - var iterator = UIElementsUtility.GetPanelsIterator(); - while (iterator.MoveNext()) - { - var panel = iterator.Current.Value; + var panel = iterator.Current.Value; - // Game panels' scheduler are ticked by the engine - if (panel.contextType != ContextType.Editor) - continue; + // Game panels' scheduler are ticked by the engine + if (panel.contextType != ContextType.Editor) + continue; - // Dispatch might have triggered a repaint request. - if (panel.isDirty) - { - var guiView = panel.ownerObject as GUIView; - if (guiView != null) - guiView.Repaint(); - } - } - } - - { - var iterator = ExperimentalUI.UIElementsUtility.GetPanelsIterator(); - while (iterator.MoveNext()) + // Dispatch might have triggered a repaint request. + if (panel.isDirty) { - var panel = iterator.Current.Value; - - // Game panels' scheduler are ticked by the engine - if (panel.contextType != ExperimentalUI.ContextType.Editor) - continue; - - // Dispatch might have triggered a repaint request. - if (panel.isDirty) - { - var guiView = panel.ownerObject as GUIView; - if (guiView != null) - guiView.Repaint(); - } + var guiView = panel.ownerObject as GUIView; + if (guiView != null) + guiView.Repaint(); } } } @@ -172,7 +122,6 @@ static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAsse // the inline stylesheet cache might get out of date. // Usually called by the USS importer, which might not get called here UnityEngine.UIElements.StyleSheets.StyleSheetCache.ClearCaches(); - ExperimentalUI.StyleSheets.StyleSheetCache.ClearCaches(); if (UxmlLiveReloadIsEnabled && Unsupported.IsDeveloperMode()) { // Delay the view reloading so we do not try to reload the view that @@ -192,26 +141,13 @@ private static void OneShotUxmlLiveReload() { try { + var it = UIElementsUtility.GetPanelsIterator(); + while (it.MoveNext()) { - var it = ExperimentalUI.UIElementsUtility.GetPanelsIterator(); - while (it.MoveNext()) - { - var view = it.Current.Value.ownerObject as HostView; - if (view != null && view.actualView != null && !(view.actualView is UIElementsDebugger)) - { - view.Reload(view.actualView); - } - } - } - { - var it = UIElementsUtility.GetPanelsIterator(); - while (it.MoveNext()) + var view = it.Current.Value.ownerObject as HostView; + if (view != null && view.actualView != null && !(view.actualView is UIElementsDebugger)) { - var view = it.Current.Value.ownerObject as HostView; - if (view != null && view.actualView != null && !(view.actualView is UIElementsDebugger)) - { - view.Reload(view.actualView); - } + view.Reload(view.actualView); } } } @@ -228,43 +164,22 @@ public static void FlagStyleSheetChange() { // clear caches that depend on loaded style sheets UnityEngine.UIElements.StyleSheets.StyleSheetCache.ClearCaches(); - ExperimentalUI.StyleSheets.StyleSheetCache.ClearCaches(); - - { - // for now we don't bother tracking which panel depends on which style sheet - var iterator = ExperimentalUI.UIElementsUtility.GetPanelsIterator(); - while (iterator.MoveNext()) - { - var panel = iterator.Current.Value; - // In-game doesn't support styling - if (panel.contextType != ExperimentalUI.ContextType.Editor) - continue; - - panel.DirtyStyleSheets(); - - var guiView = panel.ownerObject as GUIView; - if (guiView != null) - guiView.Repaint(); - } - } + // for now we don't bother tracking which panel depends on which style sheet + var iterator = UIElementsUtility.GetPanelsIterator(); + while (iterator.MoveNext()) { - // for now we don't bother tracking which panel depends on which style sheet - var iterator = UIElementsUtility.GetPanelsIterator(); - while (iterator.MoveNext()) - { - var panel = iterator.Current.Value; + var panel = iterator.Current.Value; - // In-game doesn't support styling - if (panel.contextType != ContextType.Editor) - continue; + // In-game doesn't support styling + if (panel.contextType != ContextType.Editor) + continue; - panel.DirtyStyleSheets(); + panel.DirtyStyleSheets(); - var guiView = panel.ownerObject as GUIView; - if (guiView != null) - guiView.Repaint(); - } + var guiView = panel.ownerObject as GUIView; + if (guiView != null) + guiView.Repaint(); } } } diff --git a/Editor/Mono/SceneView/SceneView.cs b/Editor/Mono/SceneView/SceneView.cs index fff8c31fb0..c9a32498a3 100644 --- a/Editor/Mono/SceneView/SceneView.cs +++ b/Editor/Mono/SceneView/SceneView.cs @@ -427,10 +427,12 @@ public SceneViewState sceneViewState Camera m_Camera; [Serializable] - public class SceneViewCameraSettings + public class CameraSettings { const float kAbsoluteSpeedMin = .01f; const float kAbsoluteSpeedMax = 99f; + const float kAbsoluteEasingDurationMin = .1f; + const float kAbsoluteEasingDurationMax = 2f; [SerializeField] float m_Speed; @@ -440,6 +442,10 @@ public class SceneViewCameraSettings float m_SpeedMin; [SerializeField] float m_SpeedMax; + [SerializeField] + bool m_EasingEnabled; + [SerializeField] + float m_EasingDuration; [SerializeField] float m_FieldOfView; @@ -452,12 +458,14 @@ public class SceneViewCameraSettings [SerializeField] bool m_OcclusionCulling; - public SceneViewCameraSettings() + public CameraSettings() { m_Speed = 1f; m_SpeedNormalized = .5f; m_SpeedMin = .01f; m_SpeedMax = 2f; + m_EasingEnabled = true; + m_EasingDuration = .4f; fieldOfView = kPerspectiveFov; m_DynamicClip = true; m_OcclusionCulling = false; @@ -519,6 +527,27 @@ public float speedMax } } + public bool easingEnabled + { + get { return m_EasingEnabled; } + set { m_EasingEnabled = value; } + } + + // How many seconds should the camera take to go from stand-still to initial full speed. When setting an animated value + // speed, use `1 / duration`. + public float easingDuration + { + get + { + return m_EasingDuration; + } + set + { + // Clamp and round to 1 decimal point + m_EasingDuration = (float)(Math.Round((double)Mathf.Clamp(value, kAbsoluteEasingDurationMin, kAbsoluteEasingDurationMax), 1)); + } + } + internal void SetSpeedMinMax(float[] floatValues) { // Round to nearest decimal: 2 decimal points when between [0.01, 0.1]; 1 decimal point when between [0.1, 10]; integral between [10, 99] @@ -574,17 +603,17 @@ public bool occlusionCulling } [SerializeField] - private SceneViewCameraSettings m_SceneViewCameraSettings; + private CameraSettings m_CameraSettings; - public SceneViewCameraSettings sceneViewCameraSettings + public CameraSettings cameraSettings { - get { return m_SceneViewCameraSettings; } - set { m_SceneViewCameraSettings = value; } + get { return m_CameraSettings; } + set { m_CameraSettings = value; } } - public void ResetSceneViewCameraSettings() + public void ResetCameraSettings() { - m_SceneViewCameraSettings = new SceneViewCameraSettings(); + m_CameraSettings = new CameraSettings(); } [SerializeField] @@ -942,8 +971,8 @@ internal void Awake() if (sceneViewState == null) m_SceneViewState = new SceneViewState(); - if (m_SceneViewCameraSettings == null) - m_SceneViewCameraSettings = new SceneViewCameraSettings(); + if (m_CameraSettings == null) + m_CameraSettings = new CameraSettings(); if (m_2DMode || EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) { @@ -1777,7 +1806,7 @@ void DoClearCamera(Rect cameraRect) // Clear (color/skybox) // We do funky FOV interpolation when switching between ortho and perspective. However, // for the skybox we always want to use the same FOV. - float skyboxFOV = GetVerticalFOV(m_SceneViewCameraSettings.fieldOfView); + float skyboxFOV = GetVerticalFOV(m_CameraSettings.fieldOfView); float realFOV = m_Camera.fieldOfView; var clearFlags = m_Camera.clearFlags; @@ -2491,14 +2520,14 @@ public float size internal float targetSize { get { return m_Size.target; } - set { m_Size.SetTarget(ValidateSceneSize(value), 1f / SceneViewMotion.movementEasingDuration); } + set { m_Size.target = ValidateSceneSize(value); } } float perspectiveFov { get { - return m_SceneViewCameraSettings.fieldOfView; + return m_CameraSettings.fieldOfView; } } @@ -2669,7 +2698,7 @@ void SetupCamera() m_Camera.orthographicSize = GetVerticalOrthoSize(); } - if (m_SceneViewCameraSettings.dynamicClip) + if (m_CameraSettings.dynamicClip) { float farClip = Mathf.Min(Mathf.Max(1000f, 2000f * size), k_MaxCameraFarClip); m_Camera.nearClipPlane = farClip * 0.000005f; @@ -2677,11 +2706,11 @@ void SetupCamera() } else { - m_Camera.nearClipPlane = m_SceneViewCameraSettings.nearClip; - m_Camera.farClipPlane = m_SceneViewCameraSettings.farClip; + m_Camera.nearClipPlane = m_CameraSettings.nearClip; + m_Camera.farClipPlane = m_CameraSettings.farClip; } - m_Camera.useOcclusionCulling = m_SceneViewCameraSettings.occlusionCulling; + m_Camera.useOcclusionCulling = m_CameraSettings.occlusionCulling; m_Camera.transform.position = m_Position.value + m_Camera.transform.rotation * new Vector3(0, 0, -cameraDistance); diff --git a/Editor/Mono/SceneView/SceneViewMotion.cs b/Editor/Mono/SceneView/SceneViewMotion.cs index 56cb4dd13b..f43648bb2c 100644 --- a/Editor/Mono/SceneView/SceneViewMotion.cs +++ b/Editor/Mono/SceneView/SceneViewMotion.cs @@ -19,34 +19,11 @@ internal static class SceneViewMotion static float k_FlySpeed = 9f; static float s_FlySpeedTarget = 0f; const float k_FlySpeedAcceleration = 1.8f; - const float k_DefaultFpsEaseDuration = .4f; static float s_StartZoom = 0f, s_ZoomSpeed = 0f; static float s_TotalMotion = 0f; static float s_FPSScrollWheelMultiplier = .01f; static bool s_Moving; - static AnimVector3 s_FlySpeed = new AnimVector3(Vector3.zero) { speed = 1f / k_DefaultFpsEaseDuration }; - - static SavedFloat s_EasingDuration = new SavedFloat("SceneViewMotion.easeDuration", k_DefaultFpsEaseDuration); - static SavedBool s_MovementEasing = new SavedBool("SceneViewMotion.movementEasing", true); - - // how many seconds should the camera take to go from stand-still to full speed. when setting an animated value - // speed, use `1 / duration`. - internal static float movementEasingDuration - { - get { return s_EasingDuration.value; } - set - { - // Clamp and round to 1 decimal point - s_EasingDuration.value = (float)(Math.Round((double)Mathf.Clamp(value, .1f, 3f), 1)); - s_FlySpeed.speed = 1f / s_EasingDuration.value; - } - } - - internal static bool movementEasingEnabled - { - get { return s_MovementEasing.value; } - set { s_MovementEasing.value = value; } - } + static AnimVector3 s_FlySpeed = new AnimVector3(Vector3.zero); enum MotionState { @@ -66,7 +43,6 @@ static void Init() if (s_Initialized) return; s_Initialized = true; - movementEasingDuration = movementEasingDuration; } public static void DoViewTool(SceneView view) @@ -131,7 +107,7 @@ static Vector3 GetMovementDirection() { s_Moving = s_Motion.sqrMagnitude > 0f; var deltaTime = CameraFlyModeContext.deltaTime; - var speedModifier = s_SceneView.sceneViewCameraSettings.speed; + var speedModifier = s_SceneView.cameraSettings.speed; if (Event.current.shift) speedModifier *= 5f; @@ -141,10 +117,15 @@ static Vector3 GetMovementDirection() else s_FlySpeedTarget = 0f; - if (movementEasingEnabled) + if (s_SceneView.cameraSettings.easingEnabled) + { + s_FlySpeed.speed = 1f / s_SceneView.cameraSettings.easingDuration; s_FlySpeed.target = s_Motion.normalized * s_FlySpeedTarget * speedModifier; + } else - s_FlySpeed.value = s_Motion.normalized * speedModifier * s_FlySpeedTarget; + { + s_FlySpeed.value = s_Motion.normalized * s_FlySpeedTarget * speedModifier; + } return s_FlySpeed.value * deltaTime; } @@ -399,9 +380,9 @@ private static void HandleScrollWheel(SceneView view, bool zoomTowardsCenter) if (Tools.s_LockedViewTool == ViewTool.FPS && s_Moving) { float scrollWheelDelta = Event.current.delta.y * s_FPSScrollWheelMultiplier; - view.sceneViewCameraSettings.speedNormalized -= scrollWheelDelta; + view.cameraSettings.speedNormalized -= scrollWheelDelta; - float cameraSpeed = view.sceneViewCameraSettings.speed; + float cameraSpeed = view.cameraSettings.speed; string cameraSpeedDisplayValue = cameraSpeed.ToString(cameraSpeed < 0.1f ? "F2" : cameraSpeed < 10f ? "F1" : "F0"); if (cameraSpeed < 0.1f) cameraSpeedDisplayValue = cameraSpeedDisplayValue.TrimStart(new Char[] {'0'}); diff --git a/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs b/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs index 01641a520a..2fa6d5a7a5 100644 --- a/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs +++ b/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs @@ -68,6 +68,10 @@ public static AssetSettingsProvider CreateProviderFromResourcePath(string settin public override void OnActivate(string searchContext, VisualElement rootElement) { + if (settingsEditor != null) + { + UnityEngine.Object.DestroyImmediate(settingsEditor); + } settingsEditor = m_EditorCreator?.Invoke(); base.OnActivate(searchContext, rootElement); } @@ -78,8 +82,8 @@ public override void OnDeactivate() { var info = settingsEditor.GetType().GetMethod("OnDisable"); info?.Invoke(settingsEditor, null); + UnityEngine.Object.DestroyImmediate(settingsEditor); } - settingsEditor = null; base.OnDeactivate(); } diff --git a/Editor/Mono/Settings/SettingsWindow.cs b/Editor/Mono/Settings/SettingsWindow.cs index 3b4521f886..ccaebabdc0 100644 --- a/Editor/Mono/Settings/SettingsWindow.cs +++ b/Editor/Mono/Settings/SettingsWindow.cs @@ -107,10 +107,15 @@ internal void OnEnable() Undo.undoRedoPerformed -= OnUndoRedoPerformed; Undo.undoRedoPerformed += OnUndoRedoPerformed; + + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; + EditorApplication.playModeStateChanged += OnPlayModeStateChanged; } internal void OnDisable() { + m_TreeView.currentProvider?.OnDeactivate(); + if (m_Splitter != null && m_Splitter.childCount >= 1) { var splitLeft = m_Splitter.Children().First(); @@ -123,6 +128,7 @@ internal void OnDisable() SettingsService.settingsProviderChanged -= OnSettingsProviderChanged; Undo.undoRedoPerformed -= OnUndoRedoPerformed; + EditorApplication.playModeStateChanged -= OnPlayModeStateChanged; } internal void OnInspectorUpdate() @@ -130,11 +136,26 @@ internal void OnInspectorUpdate() m_TreeView.currentProvider?.OnInspectorUpdate(); } - void OnUndoRedoPerformed() + private void OnUndoRedoPerformed() { Repaint(); } + private void OnPlayModeStateChanged(PlayModeStateChange state) + { + if (m_TreeView.currentProvider != null) + { + if (state == PlayModeStateChange.ExitingPlayMode) + { + ProviderChanged(m_TreeView.currentProvider, null); + } + else if (state == PlayModeStateChange.EnteredEditMode) + { + RestoreSelection(); + } + } + } + private void PrintProviderKeywords() { var sb = new StringBuilder(); diff --git a/Editor/Mono/UIElements/Controls/GradientField.cs b/Editor/Mono/UIElements/Controls/GradientField.cs index 0ef68e6428..7979995647 100644 --- a/Editor/Mono/UIElements/Controls/GradientField.cs +++ b/Editor/Mono/UIElements/Controls/GradientField.cs @@ -124,7 +124,8 @@ void OnDetach() void OnAttach() { - UpdateGradientTexture(); + if (panel != null) + UpdateGradientTexture(); } void ShowGradientPicker() diff --git a/Editor/Mono/UIElements/EditorWindowPersistentViewData.cs b/Editor/Mono/UIElements/EditorWindowPersistentViewData.cs index 5075d19ec7..1dfbf7b7f6 100644 --- a/Editor/Mono/UIElements/EditorWindowPersistentViewData.cs +++ b/Editor/Mono/UIElements/EditorWindowPersistentViewData.cs @@ -7,9 +7,9 @@ namespace UnityEditor.UIElements [LibraryFolderPath("UIElements/EditorWindows")] internal class EditorWindowViewData : ScriptableSingletonDictionary< EditorWindowViewData, - UnityEditor.Experimental.UIElements.SerializableJsonDictionary> + UnityEditor.UIElements.SerializableJsonDictionary> { - public static UnityEditor.Experimental.UIElements.SerializableJsonDictionary GetEditorData(EditorWindow window) + public static UnityEditor.UIElements.SerializableJsonDictionary GetEditorData(EditorWindow window) { string editorPrefFileName = window.GetType().ToString(); return instance[editorPrefFileName]; diff --git a/Editor/Mono/UIElements/Experimental/Controls/BaseCompositeField.cs b/Editor/Mono/UIElements/Experimental/Controls/BaseCompositeField.cs deleted file mode 100644 index 657683069a..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/BaseCompositeField.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - /// - /// This is the base class for the compound fields of type TMain. - /// - /// The type of the object to be represented by the fields (example: Vector3) - /// The type of a single field in the compound field. (example: for a Vector3, this is FloatField) - /// The basic type of an individual object contained in the TField. (example: for a FloatField, this is a float) - public abstract class BaseCompositeField : BaseField - where TField : TextValueField, new() - { - public new class UxmlTraits : BaseField.UxmlTraits {} - - internal struct FieldDescription - { - public delegate void WriteDelegate(ref TValue val, TFieldValue fieldValue); - - internal readonly string name; - internal readonly Func read; - internal readonly WriteDelegate write; - - public FieldDescription(string name, Func read, WriteDelegate write) - { - this.name = name; - this.read = read; - this.write = write; - } - } - - public override int focusIndex - { - get { return base.focusIndex; } - set - { - base.focusIndex = value; - if ((m_Fields != null) && (m_Fields.Count > 0)) - { - foreach (var field in m_Fields) - { - field.focusIndex = value; - } - } - } - } - protected List m_Fields; - internal abstract FieldDescription[] DescribeFields(); - - bool m_ShouldUpdateDisplay; - protected BaseCompositeField() - { - AddToClassList("compositeField"); - m_ShouldUpdateDisplay = true; - m_Fields = new List(); - FieldDescription[] fieldDescriptions = DescribeFields(); - foreach (var desc in fieldDescriptions) - { - var fieldContainer = new VisualElement(); - fieldContainer.AddToClassList("field"); - fieldContainer.Add(new Label(desc.name)); - var field = new TField(); - fieldContainer.Add(field); - field.OnValueChanged(e => - { - TValue cur = value; - desc.write(ref cur, e.newValue); - - // Here, just check and make sure the text is updated in the basic field and is the same as the value... - // For example, backspace done on a selected value will empty the field (text == "") but the value will be 0. - // Or : a text of "2+3" is valid until enter is pressed, so not equal to a value of "5". - if (e.newValue.ToString() != ((TField)e.currentTarget).text) - { - m_ShouldUpdateDisplay = false; - } - - value = cur; - m_ShouldUpdateDisplay = true; - }); - m_Fields.Add(field); - shadow.Add(fieldContainer); - } - - UpdateDisplay(); - } - - public override VisualElement contentContainer - { - get { return null; } - } - - private void UpdateDisplay() - { - if (m_Fields.Count != 0) - { - var i = 0; - FieldDescription[] fieldDescriptions = DescribeFields(); - foreach (var fd in fieldDescriptions) - { - m_Fields[i].value = (fd.read(m_Value)); - i++; - } - } - } - - public override void SetValueWithoutNotify(TValue newValue) - { - var displayNeedsUpdate = m_ShouldUpdateDisplay && !EqualityComparer.Default.Equals(m_Value, newValue); - - // Make sure to call the base class to set the value... - base.SetValueWithoutNotify(newValue); - - // Before Updating the display, just check if the value changed... - if (displayNeedsUpdate) - { - UpdateDisplay(); - } - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - // Focus first field if any - if (evt.GetEventTypeId() == FocusEvent.TypeId() && m_Fields.Count > 0) - m_Fields[0].Focus(); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/BasePopupField.cs b/Editor/Mono/UIElements/Experimental/Controls/BasePopupField.cs deleted file mode 100644 index b825eae0eb..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/BasePopupField.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - /// - /// This is the base class for all the popup field elements. - /// TValue and TChoice can be different, see MaskField, - /// or the same, see PopupField - /// - /// Used for the BaseField - /// Used for the choices list - public abstract class BasePopupField : BaseField - { - internal List m_Choices; - protected TextElement m_TextElement; - - internal Func m_FormatSelectedValueCallback; - internal Func m_FormatListItemCallback; - - // This is the value to display to the user - internal abstract string GetValueToDisplay(); - - internal abstract string GetListItemToDisplay(TValue item); - - // This method is used when the menu is built to fill up all the choices. - internal abstract void AddMenuItems(GenericMenu menu); - - internal virtual List choices - { - get { return m_Choices; } - set - { - if (value == null) - throw new ArgumentNullException("choices", "choices can't be null"); - - m_Choices = value; - } - } - - public override void SetValueWithoutNotify(TValue newValue) - { - base.SetValueWithoutNotify(newValue); - m_TextElement.text = GetValueToDisplay(); - } - - public string text - { - get { return m_TextElement.text; } - } - - protected BasePopupField() - { - m_TextElement = new TextElement(); - m_TextElement.pickingMode = PickingMode.Ignore; - Add(m_TextElement); - AddToClassList("popupField"); - - choices = new List(); - } - - protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) - { - base.ExecuteDefaultActionAtTarget(evt); - - if (((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse) || - ((evt.GetEventTypeId() == KeyDownEvent.TypeId()) && ((evt as KeyDownEvent)?.character == '\n') || ((evt as KeyDownEvent)?.character == ' '))) - { - ShowMenu(); - evt.StopPropagation(); - } - } - - private void ShowMenu() - { - var menu = new GenericMenu(); - AddMenuItems(menu); - var menuPosition = new Vector2(0.0f, layout.height); - menuPosition = this.LocalToWorld(menuPosition); - var menuRect = new Rect(menuPosition, Vector2.zero); - menu.DropDown(menuRect); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/BindingExtensions.cs b/Editor/Mono/UIElements/Experimental/Controls/BindingExtensions.cs deleted file mode 100644 index b6a89bd967..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/BindingExtensions.cs +++ /dev/null @@ -1,913 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Linq; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - internal class SerializedObjectBindEvent : EventBase - { - private SerializedObject m_BindObject; - public SerializedObject bindObject - { - get - { - return m_BindObject; - } - } - - protected override void Init() - { - base.Init(); - this.flags = EventFlags.Cancellable; // Also makes it not propagatable. - m_BindObject = null; - } - - public static SerializedObjectBindEvent GetPooled(SerializedObject obj) - { - SerializedObjectBindEvent e = GetPooled(); - e.m_BindObject = obj; - return e; - } - } - - internal class SerializedPropertyBindEvent : EventBase - { - private SerializedProperty m_BindProperty; - public SerializedProperty bindProperty - { - get - { - return m_BindProperty; - } - } - - protected override void Init() - { - base.Init(); - this.flags = EventFlags.Cancellable; // Also makes it not propagatable. - m_BindProperty = null; - } - - public static SerializedPropertyBindEvent GetPooled(SerializedProperty obj) - { - SerializedPropertyBindEvent e = GetPooled(); - e.m_BindProperty = obj; - return e; - } - } - - public static class BindingExtensions - { - // visual element style changes wrt its property state - internal static readonly string k_PrefabOverrideClassName = "unity-prefab-override"; - - public static void Bind(this VisualElement element, SerializedObject obj) - { - Bind(element, new SerializedObjectUpdateWrapper(obj), null); - } - - public static void Unbind(this VisualElement element) - { - RemoveBinding(element); - - for (int i = 0; i < element.shadow.childCount; ++i) - { - Unbind(element.shadow[i]); - } - } - - public static SerializedProperty BindProperty(this IBindable field, SerializedObject obj) - { - return BindPropertyWithParent(field, new SerializedObjectUpdateWrapper(obj), null); - } - - public static void BindProperty(this IBindable field, SerializedProperty property) - { - DoBindProperty(field, new SerializedObjectUpdateWrapper(property.serializedObject), property); - } - - private static void DoBindProperty(IBindable field, SerializedObjectUpdateWrapper obj, SerializedProperty property) - { - var fieldElement = field as VisualElement; - if (property == null || fieldElement == null) - { - // Object is null or property was not found, we have to make sure we delete any previous binding - RemoveBinding(fieldElement); - return; - } - - // This covers the case where a field is being manually bound to a property - field.bindingPath = property.propertyPath; - - if (property != null && fieldElement != null) - { - using (var evt = SerializedPropertyBindEvent.GetPooled(property)) - { - if (SendBindingEvent(evt, fieldElement)) - { - return; - } - } - } - - CreateBindingObjectForProperty(fieldElement, obj, property); - } - - private static void Bind(VisualElement element, SerializedObjectUpdateWrapper objWrapper, SerializedProperty parentProperty) - { - IBindable field = element as IBindable; - - using (var evt = SerializedObjectBindEvent.GetPooled(objWrapper.obj)) - { - if (SendBindingEvent(evt, element)) - { - return; - } - } - - if (field != null) - { - if (!string.IsNullOrEmpty(field.bindingPath)) - { - var foundProperty = BindPropertyWithParent(field, objWrapper, parentProperty); - if (foundProperty != null) - { - parentProperty = foundProperty; - } - } - } - - for (int i = 0; i < element.shadow.childCount; ++i) - { - Bind(element.shadow[i], objWrapper, parentProperty); - } - } - - private static SerializedProperty BindPropertyWithParent(IBindable field, SerializedObjectUpdateWrapper objWrapper, SerializedProperty parentProperty) - { - var property = parentProperty?.FindPropertyRelative(field.bindingPath); - - if (property == null) - { - property = objWrapper.obj?.FindProperty(field.bindingPath); - } - - DoBindProperty(field, objWrapper, property); - - return property; - } - - private static bool SendBindingEvent(TEventType evt, VisualElement target) where TEventType : EventBase, new() - { - evt.target = target; - evt.propagationPhase = PropagationPhase.AtTarget; - target.HandleEvent(evt); - return evt.isPropagationStopped; - } - - private static void RemoveBinding(VisualElement element) - { - IBindable field = element as IBindable; - if (element == null || !field.IsBound()) - { - return; - } - if (field != null) - { - field.binding?.Release(); - field.binding = null; - } - } - - /// Property getters - private static int GetIntPropertyValue(SerializedProperty p) { return p.intValue; } - private static bool GetBoolPropertyValue(SerializedProperty p) { return p.boolValue; } - private static float GetFloatPropertyValue(SerializedProperty p) { return p.floatValue; } - private static double GetDoublePropertyValue(SerializedProperty p) { return p.doubleValue; } - private static string GetStringPropertyValue(SerializedProperty p) { return p.stringValue; } - private static Color GetColorPropertyValue(SerializedProperty p) { return p.colorValue; } - private static UnityEngine.Object GetObjectRefPropertyValue(SerializedProperty p) {return p.objectReferenceValue; } - private static int GetLayerMaskPropertyValue(SerializedProperty p) {return p.intValue; } - private static Vector2 GetVector2PropertyValue(SerializedProperty p) { return p.vector2Value; } - private static Vector3 GetVector3PropertyValue(SerializedProperty p) { return p.vector3Value; } - private static Vector4 GetVector4PropertyValue(SerializedProperty p) { return p.vector4Value; } - private static Vector2Int GetVector2IntPropertyValue(SerializedProperty p) { return p.vector2IntValue; } - private static Vector3Int GetVector3IntPropertyValue(SerializedProperty p) { return p.vector3IntValue; } - private static Rect GetRectPropertyValue(SerializedProperty p) { return p.rectValue; } - private static RectInt GetRectIntPropertyValue(SerializedProperty p) { return p.rectIntValue; } - private static AnimationCurve GetAnimationCurvePropertyValue(SerializedProperty p) { return p.animationCurveValue; } - private static Bounds GetBoundsPropertyValue(SerializedProperty p) { return p.boundsValue; } - private static BoundsInt GetBoundsIntPropertyValue(SerializedProperty p) { return p.boundsIntValue; } - private static Gradient GetGradientPropertyValue(SerializedProperty p) { return p.gradientValue; } - private static Quaternion GetQuaternionPropertyValue(SerializedProperty p) { return p.quaternionValue; } - private static char GetCharacterPropertyValue(SerializedProperty p) { return (char)p.intValue; } - - - // Basic conversions - private static float GetDoublePropertyValueAsFloat(SerializedProperty p) { return (float)p.doubleValue; } - private static double GetFloatPropertyValueAsDouble(SerializedProperty p) { return (double)p.floatValue; } - private static string GetCharacterPropertyValueAsString(SerializedProperty p) { return new string((char)p.intValue, 1); } - - //this one is a bit more tricky - private static string GetEnumPropertyValueAsString(SerializedProperty p) { return p.enumDisplayNames[p.enumValueIndex]; } - - - /// Property setters - private static void SetIntPropertyValue(SerializedProperty p, int v) { p.intValue = v; } - private static void SetBoolPropertyValue(SerializedProperty p, bool v) { p.boolValue = v; } - private static void SetFloatPropertyValue(SerializedProperty p, float v) { p.floatValue = v; } - private static void SetDoublePropertyValue(SerializedProperty p, double v) { p.doubleValue = v; } - private static void SetStringPropertyValue(SerializedProperty p, string v) { p.stringValue = v; } - private static void SetColorPropertyValue(SerializedProperty p, Color v) { p.colorValue = v; } - private static void SetObjectRefPropertyValue(SerializedProperty p, UnityEngine.Object v) { p.objectReferenceValue = v; } - private static void SetLayerMaskPropertyValue(SerializedProperty p, int v) { p.intValue = v; } - private static void SetVector2PropertyValue(SerializedProperty p, Vector2 v) { p.vector2Value = v; } - private static void SetVector3PropertyValue(SerializedProperty p, Vector3 v) { p.vector3Value = v; } - private static void SetVector4PropertyValue(SerializedProperty p, Vector4 v) { p.vector4Value = v; } - private static void SetVector2IntPropertyValue(SerializedProperty p, Vector2Int v) { p.vector2IntValue = v; } - private static void SetVector3IntPropertyValue(SerializedProperty p, Vector3Int v) { p.vector3IntValue = v; } - private static void SetRectPropertyValue(SerializedProperty p, Rect v) { p.rectValue = v; } - private static void SetRectIntPropertyValue(SerializedProperty p, RectInt v) { p.rectIntValue = v; } - private static void SetAnimationCurvePropertyValue(SerializedProperty p, AnimationCurve v) { p.animationCurveValue = v; } - private static void SetBoundsPropertyValue(SerializedProperty p, Bounds v) { p.boundsValue = v; } - private static void SetBoundsIntPropertyValue(SerializedProperty p, BoundsInt v) { p.boundsIntValue = v; } - private static void SetGradientPropertyValue(SerializedProperty p, Gradient v) {p.gradientValue = v; } - private static void SetQuaternionPropertyValue(SerializedProperty p, Quaternion v) { p.quaternionValue = v; } - private static void SetCharacterPropertyValue(SerializedProperty p, char v) { p.intValue = v; } - - // Conversions - private static void SetDoublePropertyValueFromFloat(SerializedProperty p, float v) { p.doubleValue = v; } - private static void SetFloatPropertyValueFromDouble(SerializedProperty p, double v) { p.floatValue = (float)v; } - private static void SetCharacterPropertyValueFromString(SerializedProperty p, string v) - { - if (v.Length > 0) - { - p.intValue = v[0]; - } - } - - //this one is a bit more tricky - private static void SetEnumPropertyValueFromString(SerializedProperty p, string v) { p.enumValueIndex = FindStringIndex(p.enumDisplayNames, v); } - - // A No Linq implementation to avoid allocations - private static int FindStringIndex(string[] values, string v) - { - for (var i = 0; i < values.Length; ++i) - { - if (values[i] == v) - return i; - } - - return -1; - } - - // Equality comparers - internal static bool ValueEquals(TValue value, SerializedProperty p, Func propertyReadFunc) - { - var propVal = propertyReadFunc(p); - return EqualityComparer.Default.Equals(value, propVal); - } - - internal static bool ValueEquals(string value, SerializedProperty p, Func propertyReadFunc) - { - if (p.propertyType == SerializedPropertyType.Enum) - return p.enumDisplayNames[p.enumValueIndex] == value; - else - return p.ValueEquals(value); - } - - internal static bool ValueEquals(AnimationCurve value, SerializedProperty p, Func propertyReadFunc) - { - return p.ValueEquals(value); - } - - internal static bool ValueEquals(Gradient value, SerializedProperty p, Func propertyReadFunc) - { - return p.ValueEquals(value); - } - - internal static bool SlowEnumValueEquals(string value, SerializedProperty p, Func propertyReadFunc) - { - var propVal = propertyReadFunc(p); - return EqualityComparer.Default.Equals(value, propVal); - } - - private static void DefaultBind(VisualElement element, SerializedObjectUpdateWrapper objWrapper, SerializedProperty prop, - Func propertyReadFunc, Action propertyWriteFunc, - Func, bool> valueComparerFunc) - { - var field = element as INotifyValueChanged; - - if (field != null) - { - SerializedObjectBinding.CreateBind(field, objWrapper, prop, propertyReadFunc, - propertyWriteFunc, valueComparerFunc); - } - else - { - Debug.LogWarning(string.Format("Field type {0} is not compatible with {2} property \"{1}\"", - element.GetType().FullName, prop.propertyPath, prop.type)); - } - } - - private static void EnumBind(PopupField popup, SerializedObjectUpdateWrapper objWrapper, SerializedProperty prop) - { - SerializedEnumBinding.CreateBind(popup, objWrapper, prop); - } - - private static void CreateBindingObjectForProperty(VisualElement element, SerializedObjectUpdateWrapper objWrapper, SerializedProperty prop) - { - if (element is Foldout) - { - var foldout = element as Foldout; - SerializedObjectBinding.CreateBind( - foldout, objWrapper, prop, - p => p.isExpanded, - (p, v) => p.isExpanded = v, - ValueEquals); - - return; - } - - switch (prop.propertyType) - { - case SerializedPropertyType.Integer: - DefaultBind(element, objWrapper, prop, GetIntPropertyValue, SetIntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Boolean: - DefaultBind(element, objWrapper, prop, GetBoolPropertyValue, SetBoolPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Float: - if (prop.type == "float") - { - if (element is INotifyValueChanged) - { - DefaultBind(element, objWrapper, prop, GetFloatPropertyValueAsDouble, SetFloatPropertyValueFromDouble, ValueEquals); - } - else - { - DefaultBind(element, objWrapper, prop, GetFloatPropertyValue, SetFloatPropertyValue, ValueEquals); - } - } - else - { - if (element is INotifyValueChanged) - { - DefaultBind(element, objWrapper, prop, GetDoublePropertyValueAsFloat, SetDoublePropertyValueFromFloat, ValueEquals); - } - else - { - DefaultBind(element, objWrapper, prop, GetDoublePropertyValue, SetDoublePropertyValue, ValueEquals); - } - } - - break; - case SerializedPropertyType.String: - DefaultBind(element, objWrapper, prop, GetStringPropertyValue, SetStringPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Color: - DefaultBind(element, objWrapper, prop, GetColorPropertyValue, SetColorPropertyValue, ValueEquals); - break; - case SerializedPropertyType.ObjectReference: - DefaultBind(element, objWrapper, prop, GetObjectRefPropertyValue, SetObjectRefPropertyValue, ValueEquals); - break; - case SerializedPropertyType.LayerMask: - DefaultBind(element, objWrapper, prop, GetLayerMaskPropertyValue, SetLayerMaskPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Enum: - if (element is PopupField) - { - EnumBind((PopupField)element, objWrapper, prop); - } - else - { - DefaultBind(element, objWrapper, prop, GetEnumPropertyValueAsString, SetEnumPropertyValueFromString, SlowEnumValueEquals); - } - - break; - case SerializedPropertyType.Vector2: - DefaultBind(element, objWrapper, prop, GetVector2PropertyValue, SetVector2PropertyValue, ValueEquals); - break; - case SerializedPropertyType.Vector3: - DefaultBind(element, objWrapper, prop, GetVector3PropertyValue, SetVector3PropertyValue, ValueEquals); - break; - case SerializedPropertyType.Vector4: - DefaultBind(element, objWrapper, prop, GetVector4PropertyValue, SetVector4PropertyValue, ValueEquals); - break; - case SerializedPropertyType.Rect: - DefaultBind(element, objWrapper, prop, GetRectPropertyValue, SetRectPropertyValue, ValueEquals); - break; - case SerializedPropertyType.ArraySize: - DefaultBind(element, objWrapper, prop, GetIntPropertyValue, SetIntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.AnimationCurve: - DefaultBind(element, objWrapper, prop, GetAnimationCurvePropertyValue, SetAnimationCurvePropertyValue, ValueEquals); - break; - case SerializedPropertyType.Bounds: - DefaultBind(element, objWrapper, prop, GetBoundsPropertyValue, SetBoundsPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Gradient: - DefaultBind(element, objWrapper, prop, GetGradientPropertyValue, SetGradientPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Quaternion: - DefaultBind(element, objWrapper, prop, GetQuaternionPropertyValue, SetQuaternionPropertyValue, ValueEquals); - break; - case SerializedPropertyType.FixedBufferSize: - DefaultBind(element, objWrapper, prop, GetIntPropertyValue, SetIntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Vector2Int: - DefaultBind(element, objWrapper, prop, GetVector2IntPropertyValue, SetVector2IntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Vector3Int: - DefaultBind(element, objWrapper, prop, GetVector3IntPropertyValue, SetVector3IntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.RectInt: - DefaultBind(element, objWrapper, prop, GetRectIntPropertyValue, SetRectIntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.BoundsInt: - DefaultBind(element, objWrapper, prop, GetBoundsIntPropertyValue, SetBoundsIntPropertyValue, ValueEquals); - break; - case SerializedPropertyType.Character: - if (element is INotifyValueChanged) - { - DefaultBind(element, objWrapper, prop, GetCharacterPropertyValueAsString, SetCharacterPropertyValueFromString, ValueEquals); - } - else - { - DefaultBind(element, objWrapper, prop, GetCharacterPropertyValue, SetCharacterPropertyValue, ValueEquals); - } - break; - case SerializedPropertyType.ExposedReference: - case SerializedPropertyType.Generic: - // nothing to bind here - break; - default: - Debug.LogWarning(string.Format("Binding is not supported for {0} properties \"{1}\"", prop.type, - prop.propertyPath)); - break; - } - } - - private class SerializedObjectUpdateWrapper - { - SerializedObjectChangeTracker tracker; - public UInt64 LastRevision {get; private set; } - public SerializedObject obj {get; private set; } - - public SerializedObjectUpdateWrapper(SerializedObject so) - { - tracker = new SerializedObjectChangeTracker(so); - obj = so; - } - - private bool wasUpdated {get; set; } - - public void UpdateRevision() - { - tracker.UpdateTrackedVersion(); - LastRevision = tracker.CurrentRevision; - } - - public bool IsValid() - { - if (obj == null) - return false; - - return obj.isValid; - } - - public void UpdateIfNecessary() - { - if (!wasUpdated) - { - obj.UpdateIfRequiredOrScript(); - obj.UpdateExpandedState(); - UpdateRevision(); - wasUpdated = true; - } - } - - public void ResetUpdate() - { - wasUpdated = false; - } - } - - private abstract class SerializedObjectBindingBase : IBinding - { - public SerializedObjectUpdateWrapper boundObject; - public string boundPropertyPath; - public SerializedProperty boundProperty; - - protected bool isReleased { get; set; } - protected bool isUpdating { get; set; } - public abstract void Update(); - public abstract void Release(); - - public void PreUpdate() - { - boundObject.UpdateIfNecessary(); - } - - public virtual void ResetUpdate() - { - if (boundObject != null) - { - boundObject.ResetUpdate(); - } - } - - protected static void UpdateElementStyle(VisualElement element, SerializedProperty prop) - { - if (prop.serializedObject.targetObjects.Length == 1 && prop.isInstantiatedPrefab && prop.prefabOverride) - element.AddToClassList(BindingExtensions.k_PrefabOverrideClassName); - else - element.RemoveFromClassList(BindingExtensions.k_PrefabOverrideClassName); - } - - protected bool IsPropertyValid() - { - if (boundProperty != null) - { - return boundProperty.isValid; - } - return false; - } - } - - private abstract class SerializedObjectBindingToBaseField : SerializedObjectBindingBase where TField : class, INotifyValueChanged - { - private TField m_Field; - - protected TField field - { - get { return m_Field; } - set - { - m_Field?.RemoveOnValueChanged(FieldValueChanged); - - VisualElement ve = m_Field as VisualElement; - if (ve != null) - { - ve.UnregisterCallback(OnFieldAttached); - ve.UnregisterCallback(OnFieldDetached); - } - - m_Field = value; - UpdateFieldIsAttached(); - if (m_Field != null) - { - m_Field.OnValueChanged(FieldValueChanged); - - ve = m_Field as VisualElement; - if (ve != null) - { - ve.RegisterCallback(OnFieldAttached); - ve.RegisterCallback(OnFieldDetached); - } - FieldBinding = this; - } - } - } - - protected IBinding FieldBinding - { - get - { - var bindable = m_Field as IBindable; - return bindable?.binding; - } - set - { - var bindable = m_Field as IBindable; - if (bindable != null) - { - var previousBinding = bindable.binding; - bindable.binding = value; - if (previousBinding != this) - { - previousBinding?.Release(); - } - (m_Field as VisualElement)?.IncrementVersion(VersionChangeType.Bindings); - } - } - } - - protected bool isFieldAttached {get; private set; } - - private void FieldValueChanged(ChangeEvent evt) - { - if (isReleased || isUpdating) - return; - - var bindable = evt.target as IBindable; - var binding = bindable?.binding; - - if (binding == this && boundProperty != null && boundObject.IsValid()) - { - if (!isFieldAttached) - { - //we don't update when field is not attached to a panel - //but we don't kill binding either - return; - } - - UpdateLastFieldValue(); - - if (IsPropertyValid()) - { - if (SyncFieldValueToProperty()) - { - boundObject.UpdateRevision(); //we make sure to Poll the ChangeTracker here - boundObject.ResetUpdate(); - } - UpdateElementStyle(field as VisualElement, boundProperty); - return; - } - } - - // Something was wrong - Release(); - } - - private UInt64 lastUpdatedRevision = 0xFFFFFFFFFFFFFFFF; - - public void ResetCachedValues() - { - lastUpdatedRevision = 0xFFFFFFFFFFFFFFFF; - UpdateLastFieldValue(); - UpdateFieldIsAttached(); - } - - public override void Update() - { - if (isReleased) - return; - try - { - ResetUpdate(); - isUpdating = true; - - if (FieldBinding == this && boundObject.IsValid() && IsPropertyValid()) - { - if (lastUpdatedRevision == boundObject.LastRevision) - { - //nothing to do - return; - } - - lastUpdatedRevision = boundObject.LastRevision; - SyncPropertyToField(field, boundProperty); - return; - } - } - catch (ArgumentNullException) - { - //this can happen when serializedObject has been disposed of - } - finally - { - isUpdating = false; - } - // We unbind here - Release(); - } - - private void OnFieldAttached(AttachToPanelEvent evt) - { - isFieldAttached = true; - ResetCachedValues(); - } - - private void OnFieldDetached(DetachFromPanelEvent evt) - { - isFieldAttached = false; - } - - protected void UpdateFieldIsAttached() - { - VisualElement ve = m_Field as VisualElement; - - if (ve != null) - { - bool attached = ve.panel != null; - - if (isFieldAttached != attached) - { - isFieldAttached = attached; - if (attached) - { - ResetCachedValues(); - } - } - } - else - { - //we're not dealing with VisualElement - if (!isFieldAttached) - { - isFieldAttached = true; - ResetCachedValues(); - } - } - } - - // Read the value from the ui field and save it. - protected abstract void UpdateLastFieldValue(); - - protected abstract bool SyncFieldValueToProperty(); - protected abstract void SyncPropertyToField(TField c, SerializedProperty p); - } - - private class SerializedObjectBinding : SerializedObjectBindingToBaseField> - { - private Func propGetValue; - private Action propSetValue; - private Func, bool> propCompareValues; - - public static ObjectPool> s_Pool = - new ObjectPool>(32); - - //we need to keep a copy of the last value since some fields will allocate when getting the value - private TValue lastFieldValue; - - public static void CreateBind(INotifyValueChanged field, - SerializedObjectUpdateWrapper objWrapper, - SerializedProperty property, - Func propGetValue, - Action propSetValue, - Func, bool> propCompareValues) - { - var newBinding = s_Pool.Get(); - newBinding.isReleased = false; - newBinding.SetBinding(field, objWrapper, property, propGetValue, propSetValue, propCompareValues); - } - - private void SetBinding(INotifyValueChanged c, - SerializedObjectUpdateWrapper objWrapper, - SerializedProperty property, - Func getValue, - Action setValue, - Func, bool> compareValues) - { - this.field = c; - property.unsafeMode = true; - this.boundPropertyPath = property.propertyPath; - this.boundObject = objWrapper; - this.boundProperty = property; - this.propGetValue = getValue; - this.propSetValue = setValue; - this.propCompareValues = compareValues; - this.lastFieldValue = c.value; - - Update(); - } - - protected override void SyncPropertyToField(INotifyValueChanged c, SerializedProperty p) - { - if (!propCompareValues(lastFieldValue, p, propGetValue)) - { - lastFieldValue = propGetValue(p); - c.value = lastFieldValue; - } - } - - protected override void UpdateLastFieldValue() - { - lastFieldValue = field.value; - } - - protected override bool SyncFieldValueToProperty() - { - if (!propCompareValues(lastFieldValue, boundProperty, propGetValue)) - { - propSetValue(boundProperty, lastFieldValue); - boundProperty.m_SerializedObject.ApplyModifiedProperties(); - return true; - } - return false; - } - - public override void Release() - { - if (isReleased) - return; - - if (FieldBinding == this) - { - FieldBinding = null; - } - - boundObject = null; - boundProperty = null; - field = null; - propGetValue = null; - propSetValue = null; - propCompareValues = null; - lastFieldValue = default(TValue); - isReleased = true; - s_Pool.Release(this); - } - } - - // specific enum version that binds on the index property of the PopupField - private class SerializedEnumBinding : SerializedObjectBindingToBaseField> - { - public static ObjectPool s_Pool = - new ObjectPool(32); - - //we need to keep a copy of the last value since some fields will allocate when getting the value - private int lastFieldValueIndex; - - private List originalChoices; - private int originalIndex; - - public static void CreateBind(PopupField field, SerializedObjectUpdateWrapper objWrapper, - SerializedProperty property) - { - var newBinding = s_Pool.Get(); - newBinding.isReleased = false; - newBinding.SetBinding(field, objWrapper, property); - } - - private void SetBinding(PopupField c, SerializedObjectUpdateWrapper objWrapper, - SerializedProperty property) - { - this.field = c; - property.unsafeMode = true; - this.boundPropertyPath = property.propertyPath; - this.boundObject = objWrapper; - this.boundProperty = property; - this.originalChoices = field.choices; - this.originalIndex = field.index; - this.field.choices = property.enumLocalizedDisplayNames.ToList(); - this.lastFieldValueIndex = c.index; - - Update(); - } - - protected override void SyncPropertyToField(PopupField c, SerializedProperty p) - { - int propValueIndex = p.enumValueIndex; - if (propValueIndex != lastFieldValueIndex) - { - lastFieldValueIndex = propValueIndex; - c.index = propValueIndex; - } - } - - protected override void UpdateLastFieldValue() - { - lastFieldValueIndex = field.index; - } - - protected override bool SyncFieldValueToProperty() - { - if (lastFieldValueIndex != boundProperty.enumValueIndex) - { - boundProperty.enumValueIndex = lastFieldValueIndex; - boundProperty.m_SerializedObject.ApplyModifiedProperties(); - return true; - } - return false; - } - - public override void Release() - { - if (isReleased) - return; - - if (FieldBinding == this) - { - //we set the popup values to the original ones - try - { - var previousField = field; - field = null; - previousField.choices = originalChoices; - previousField.index = originalIndex; - } - catch (ArgumentException) - { - //we did our best - } - - FieldBinding = null; - } - - boundObject = null; - boundProperty = null; - field = null; - lastFieldValueIndex = -1; - isReleased = true; - s_Pool.Release(this); - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/BoundsField.cs b/Editor/Mono/UIElements/Experimental/Controls/BoundsField.cs deleted file mode 100644 index f659e91513..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/BoundsField.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class BoundsField : BaseField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits - { - UxmlFloatAttributeDescription m_CenterXValue = new UxmlFloatAttributeDescription { name = "cx" }; - UxmlFloatAttributeDescription m_CenterYValue = new UxmlFloatAttributeDescription { name = "cy" }; - UxmlFloatAttributeDescription m_CenterZValue = new UxmlFloatAttributeDescription { name = "cz" }; - - UxmlFloatAttributeDescription m_ExtentsXValue = new UxmlFloatAttributeDescription { name = "ex" }; - UxmlFloatAttributeDescription m_ExtentsYValue = new UxmlFloatAttributeDescription { name = "ey" }; - UxmlFloatAttributeDescription m_ExtentsZValue = new UxmlFloatAttributeDescription { name = "ez" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - BoundsField f = (BoundsField)ve; - f.SetValueWithoutNotify(new Bounds( - new Vector3(m_CenterXValue.GetValueFromBag(bag, cc), m_CenterYValue.GetValueFromBag(bag, cc), m_CenterZValue.GetValueFromBag(bag, cc)), - new Vector3(m_ExtentsXValue.GetValueFromBag(bag, cc), m_ExtentsYValue.GetValueFromBag(bag, cc), m_ExtentsZValue.GetValueFromBag(bag, cc)))); - } - } - - private Vector3Field m_CenterField; - private Vector3Field m_ExtentsField; - - public BoundsField() - { - m_CenterField = new Vector3Field(); - - m_CenterField.OnValueChanged(e => - { - Bounds current = value; - current.center = e.newValue; - value = current; - }); - - var centerGroup = new VisualElement(); - centerGroup.AddToClassList("group"); - centerGroup.Add(new Label("Center")); - centerGroup.Add(m_CenterField); - this.shadow.Add(centerGroup); - - m_ExtentsField = new Vector3Field(); - - m_ExtentsField.OnValueChanged(e => - { - Bounds current = value; - current.extents = e.newValue; - value = current; - }); - - var extentsGroup = new VisualElement(); - extentsGroup.AddToClassList("group"); - extentsGroup.contentContainer.Add(new Label("Extents")); - extentsGroup.contentContainer.Add(m_ExtentsField); - this.shadow.Add(extentsGroup); - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - // Focus first field if any - if (evt.GetEventTypeId() == FocusEvent.TypeId()) - { - m_CenterField.Focus(); - } - } - - public override void SetValueWithoutNotify(Bounds newValue) - { - base.SetValueWithoutNotify(newValue); - m_CenterField.SetValueWithoutNotify(m_Value.center); - m_ExtentsField.SetValueWithoutNotify(m_Value.extents); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/BoundsIntField.cs b/Editor/Mono/UIElements/Experimental/Controls/BoundsIntField.cs deleted file mode 100644 index c1c45773d0..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/BoundsIntField.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class BoundsIntField : BaseField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits - { - UxmlIntAttributeDescription m_PositionXValue = new UxmlIntAttributeDescription { name = "px" }; - UxmlIntAttributeDescription m_PositionYValue = new UxmlIntAttributeDescription { name = "py" }; - UxmlIntAttributeDescription m_PositionZValue = new UxmlIntAttributeDescription { name = "pz" }; - - UxmlIntAttributeDescription m_SizeXValue = new UxmlIntAttributeDescription { name = "sx" }; - UxmlIntAttributeDescription m_SizeYValue = new UxmlIntAttributeDescription { name = "sy" }; - UxmlIntAttributeDescription m_SizeZValue = new UxmlIntAttributeDescription { name = "sz" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var f = (BoundsIntField)ve; - f.SetValueWithoutNotify(new BoundsInt( - new Vector3Int(m_PositionXValue.GetValueFromBag(bag, cc), m_PositionYValue.GetValueFromBag(bag, cc), m_PositionZValue.GetValueFromBag(bag, cc)), - new Vector3Int(m_SizeXValue.GetValueFromBag(bag, cc), m_SizeYValue.GetValueFromBag(bag, cc), m_SizeZValue.GetValueFromBag(bag, cc)))); - } - } - - private Vector3IntField m_PositionField; - private Vector3IntField m_SizeField; - - public BoundsIntField() - { - m_PositionField = new Vector3IntField(); - - m_PositionField.OnValueChanged(e => - { - var current = value; - current.position = e.newValue; - value = current; - }); - - var centerGroup = new VisualElement(); - centerGroup.AddToClassList("group"); - centerGroup.Add(new Label("Position")); - centerGroup.Add(m_PositionField); - this.shadow.Add(centerGroup); - - m_SizeField = new Vector3IntField(); - - m_SizeField.OnValueChanged(e => - { - var current = value; - current.size = e.newValue; - value = current; - }); - - var extentsGroup = new VisualElement(); - extentsGroup.AddToClassList("group"); - extentsGroup.contentContainer.Add(new Label("Size")); - extentsGroup.contentContainer.Add(m_SizeField); - this.shadow.Add(extentsGroup); - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - // Focus first field if any - if (evt.GetEventTypeId() == FocusEvent.TypeId()) - { - m_PositionField.Focus(); - } - } - - public override void SetValueWithoutNotify(BoundsInt newValue) - { - base.SetValueWithoutNotify(newValue); - m_PositionField.SetValueWithoutNotify(m_Value.position); - m_SizeField.SetValueWithoutNotify(m_Value.size); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/ColorField.cs b/Editor/Mono/UIElements/Experimental/Controls/ColorField.cs deleted file mode 100644 index ebe1c93530..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/ColorField.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class ColorField : BaseField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits - { - UxmlColorAttributeDescription m_Value = new UxmlColorAttributeDescription { name = "value" }; - UxmlBoolAttributeDescription m_ShowEyeDropper = new UxmlBoolAttributeDescription { name = "show-eye-dropper", obsoleteNames = new[] { "showEyeDropper" }, defaultValue = true }; - UxmlBoolAttributeDescription m_ShowAlpha = new UxmlBoolAttributeDescription { name = "show-alpha", obsoleteNames = new[] { "showAlpha" }, defaultValue = true }; - UxmlBoolAttributeDescription m_Hdr = new UxmlBoolAttributeDescription { name = "hdr" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - ((ColorField)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - ((ColorField)ve).showEyeDropper = m_ShowEyeDropper.GetValueFromBag(bag, cc); - ((ColorField)ve).showAlpha = m_ShowAlpha.GetValueFromBag(bag, cc); - ((ColorField)ve).hdr = m_Hdr.GetValueFromBag(bag, cc); - } - } - - public bool showEyeDropper { get; set; } - public bool showAlpha { get; set; } - public bool hdr { get; set; } - - private bool m_SetKbControl; - private bool m_ResetKbControl; - - private IMGUIContainer m_ColorField; - - // Since the ColorField is containing a child in the focus ring, - // it must make sure the child focus follow the focusIndex - public override int focusIndex - { - get { return base.focusIndex; } - set - { - base.focusIndex = value; - if (m_ColorField != null) - { - m_ColorField.focusIndex = value; - } - } - } - - - public ColorField() - { - showEyeDropper = true; - showAlpha = true; - - // The focus on a color field is implemented like a BaseCompoundField : the ColorField and its inner child - // are both put in the focus ring. When the ColorField is receiving the Focus, it is "delegating" it to the inner child, - // which is, in this case, the IMGUIContainer. - m_ColorField = new IMGUIContainer(OnGUIHandler) { name = "InternalColorField", useUIElementsFocusStyle = true }; - Add(m_ColorField); - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(Color newValue) - { - if (value != newValue) - { - value = newValue; - } - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if (evt.GetEventTypeId() == FocusEvent.TypeId()) - { - m_SetKbControl = true; - // Make sure the inner IMGUIContainer is receiving the focus - m_ColorField.Focus(); - } - - if (evt.GetEventTypeId() == BlurEvent.TypeId()) - { - m_ResetKbControl = true; - } - } - - protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) - { - if (evt.GetEventTypeId() == KeyDownEvent.TypeId()) - { - m_ColorField.HandleEvent(evt); - } - } - - private void OnGUIHandler() - { - // Dirty repaint on eye dropper update to preview the color under the cursor - if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == EventCommandNames.EyeDropperUpdate) - { - IncrementVersion(VersionChangeType.Repaint); - } - - Color newColor = EditorGUILayout.ColorField(GUIContent.none, value, showEyeDropper, showAlpha, hdr); - value = newColor; - if (m_SetKbControl) - { - GUIUtility.SetKeyboardControlToFirstControlId(); - m_SetKbControl = false; - } - if (m_ResetKbControl) - { - GUIUtility.keyboardControl = 0; - m_ResetKbControl = false; - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/CompoundFields.cs b/Editor/Mono/UIElements/Experimental/Controls/CompoundFields.cs deleted file mode 100644 index 49dec0aac8..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/CompoundFields.cs +++ /dev/null @@ -1,222 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class RectField : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlFloatAttributeDescription m_XValue = new UxmlFloatAttributeDescription { name = "x" }; - UxmlFloatAttributeDescription m_YValue = new UxmlFloatAttributeDescription { name = "y" }; - UxmlFloatAttributeDescription m_WValue = new UxmlFloatAttributeDescription { name = "w" }; - UxmlFloatAttributeDescription m_HValue = new UxmlFloatAttributeDescription { name = "h" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - RectField r = (RectField)ve; - r.SetValueWithoutNotify(new Rect(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc), m_WValue.GetValueFromBag(bag, cc), m_HValue.GetValueFromBag(bag, cc))); - } - } - - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref Rect r, float v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref Rect r, float v) => r.y = v), - new FieldDescription("W", r => r.width, (ref Rect r, float v) => r.width = v), - new FieldDescription("H", r => r.height, (ref Rect r, float v) => r.height = v), - }; - } - } - - public class RectIntField : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlIntAttributeDescription m_XValue = new UxmlIntAttributeDescription { name = "x" }; - UxmlIntAttributeDescription m_YValue = new UxmlIntAttributeDescription { name = "y" }; - UxmlIntAttributeDescription m_WValue = new UxmlIntAttributeDescription { name = "w" }; - UxmlIntAttributeDescription m_HValue = new UxmlIntAttributeDescription { name = "h" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var r = (RectIntField)ve; - r.SetValueWithoutNotify(new RectInt(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc), m_WValue.GetValueFromBag(bag, cc), m_HValue.GetValueFromBag(bag, cc))); - } - } - - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref RectInt r, int v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref RectInt r, int v) => r.y = v), - new FieldDescription("W", r => r.width, (ref RectInt r, int v) => r.width = v), - new FieldDescription("H", r => r.height, (ref RectInt r, int v) => r.height = v), - }; - } - } - - public class Vector2Field : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlFloatAttributeDescription m_XValue = new UxmlFloatAttributeDescription { name = "x" }; - UxmlFloatAttributeDescription m_YValue = new UxmlFloatAttributeDescription { name = "y" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - Vector2Field f = (Vector2Field)ve; - f.value = new Vector2(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc)); - } - } - - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref Vector2 r, float v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref Vector2 r, float v) => r.y = v), - }; - } - } - - public class Vector3Field : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlFloatAttributeDescription m_XValue = new UxmlFloatAttributeDescription { name = "x" }; - UxmlFloatAttributeDescription m_YValue = new UxmlFloatAttributeDescription { name = "y" }; - UxmlFloatAttributeDescription m_ZValue = new UxmlFloatAttributeDescription { name = "z" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - Vector3Field f = (Vector3Field)ve; - f.value = new Vector3(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc), m_ZValue.GetValueFromBag(bag, cc)); - } - } - - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref Vector3 r, float v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref Vector3 r, float v) => r.y = v), - new FieldDescription("Z", r => r.z, (ref Vector3 r, float v) => r.z = v), - }; - } - } - - public class Vector4Field : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlFloatAttributeDescription m_XValue = new UxmlFloatAttributeDescription { name = "x" }; - UxmlFloatAttributeDescription m_YValue = new UxmlFloatAttributeDescription { name = "y" }; - UxmlFloatAttributeDescription m_ZValue = new UxmlFloatAttributeDescription { name = "z" }; - UxmlFloatAttributeDescription m_WValue = new UxmlFloatAttributeDescription { name = "w" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - Vector4Field f = (Vector4Field)ve; - f.value = new Vector4(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc), m_ZValue.GetValueFromBag(bag, cc), m_WValue.GetValueFromBag(bag, cc)); - } - } - - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref Vector4 r, float v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref Vector4 r, float v) => r.y = v), - new FieldDescription("Z", r => r.z, (ref Vector4 r, float v) => r.z = v), - new FieldDescription("W", r => r.w, (ref Vector4 r, float v) => r.w = v), - }; - } - } - - public class Vector2IntField : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlIntAttributeDescription m_XValue = new UxmlIntAttributeDescription { name = "x" }; - UxmlIntAttributeDescription m_YValue = new UxmlIntAttributeDescription { name = "y" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var f = (Vector2IntField)ve; - f.value = new Vector2Int(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc)); - } - } - - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref Vector2Int r, int v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref Vector2Int r, int v) => r.y = v), - }; - } - } - - public class Vector3IntField : BaseCompositeField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseCompositeField.UxmlTraits - { - UxmlIntAttributeDescription m_XValue = new UxmlIntAttributeDescription { name = "x" }; - UxmlIntAttributeDescription m_YValue = new UxmlIntAttributeDescription { name = "y" }; - UxmlIntAttributeDescription m_ZValue = new UxmlIntAttributeDescription { name = "z" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var f = (Vector3IntField)ve; - f.value = new Vector3Int(m_XValue.GetValueFromBag(bag, cc), m_YValue.GetValueFromBag(bag, cc), m_ZValue.GetValueFromBag(bag, cc)); - } - } - internal override FieldDescription[] DescribeFields() - { - return new[] - { - new FieldDescription("X", r => r.x, (ref Vector3Int r, int v) => r.x = v), - new FieldDescription("Y", r => r.y, (ref Vector3Int r, int v) => r.y = v), - new FieldDescription("Z", r => r.z, (ref Vector3Int r, int v) => r.z = v), - }; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/CurveField.cs b/Editor/Mono/UIElements/Experimental/Controls/CurveField.cs deleted file mode 100644 index 9bfd43d676..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/CurveField.cs +++ /dev/null @@ -1,526 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEditorInternal; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Experimental.UIElements.StyleSheets; -using Object = UnityEngine.Object; - -namespace UnityEditor.Experimental.UIElements -{ - public class CurveField : BaseField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits {} - - private const string k_CurveColorProperty = "curve-color"; - public Rect ranges { get; set; } - - StyleValue m_CurveColor; - private Color curveColor - { - get - { - return m_CurveColor.GetSpecifiedValueOrDefault(Color.green); - } - } - - private bool m_ValueNull; - private bool m_TextureDirty; - - public enum RenderMode - { - Texture, - Mesh, - Default = Texture - } - - RenderMode m_RenderMode = RenderMode.Default; - - public RenderMode renderMode - { - get { return m_RenderMode; } - set - { - if (m_RenderMode != value) - { - m_RenderMode = value; - - m_Content = new CurveFieldContent(); - if (renderMode == RenderMode.Mesh) - { - Insert(0, m_Content); - } - else - { - m_Content.RemoveFromHierarchy(); - m_Content = null; - } - - m_TextureDirty = true; - } - } - } - - internal static AnimationCurve CopyCurve(AnimationCurve other) - { - AnimationCurve curveCopy = new AnimationCurve(); - curveCopy.keys = other.keys; - curveCopy.preWrapMode = other.preWrapMode; - curveCopy.postWrapMode = other.postWrapMode; - return curveCopy; - } - - public override AnimationCurve value - { - get - { - if (m_ValueNull) return null; - - return CopyCurve(m_Value); - } - set - { - //I need to have total ownership of the curve, I won't be able to know if it is changed outside. so I'm duplicating it. - if (value != null || !m_ValueNull) // let's not reinitialize an initialized curve - { - if (panel != null) - { - using (ChangeEvent evt = ChangeEvent.GetPooled(m_Value, value)) - { - evt.target = this; - SetValueWithoutNotify(value); - SendEvent(evt); - } - } - else - { - SetValueWithoutNotify(value); - } - } - } - } - CurveFieldContent m_Content; - - public CurveField() - { - ranges = Rect.zero; - - m_Value = new AnimationCurve(new Keyframe[0]); - - VisualElement borderElement = new VisualElement() { name = "border", pickingMode = PickingMode.Ignore }; - Add(borderElement); - } - - void OnDetach() - { - if (m_Mesh != null) - Object.DestroyImmediate(m_Mesh); - if (style.backgroundImage.value != null) - Object.DestroyImmediate(style.backgroundImage.value); - m_Mesh = null; - style.backgroundImage = null; - m_TextureDirty = true; - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(AnimationCurve newValue) - { - value = newValue; - } - - public override void SetValueWithoutNotify(AnimationCurve newValue) - { - m_ValueNull = newValue == null; - if (!m_ValueNull) - { - m_Value.keys = newValue.keys; - m_Value.preWrapMode = newValue.preWrapMode; - m_Value.postWrapMode = newValue.postWrapMode; - } - else - { - m_Value.keys = new Keyframe[0]; - m_Value.preWrapMode = WrapMode.Once; - m_Value.postWrapMode = WrapMode.Once; - } - m_TextureDirty = true; - if (CurveEditorWindow.visible && Object.ReferenceEquals(CurveEditorWindow.curve, m_Value)) - { - CurveEditorWindow.curve = m_Value; - CurveEditorWindow.instance.Repaint(); - } - - IncrementVersion(VersionChangeType.Repaint); - - m_Content?.IncrementVersion(VersionChangeType.Repaint); - } - - protected override void OnStyleResolved(ICustomStyle style) - { - base.OnStyleResolved(style); - - Color color = curveColor; - style.ApplyCustomProperty(k_CurveColorProperty, ref m_CurveColor); - - if (color != curveColor && renderMode == RenderMode.Texture) - { - // The mesh texture is updated at each repaint, the standard texture should however be regenerated - m_TextureDirty = true; - } - } - - void ShowCurveEditor() - { - if (!enabledInHierarchy) - return; - - CurveEditorSettings settings = new CurveEditorSettings(); - if (m_Value == null) - m_Value = new AnimationCurve(); - CurveEditorWindow.instance.Show(OnCurveChanged, settings); - CurveEditorWindow.curve = m_Value; - - CurveEditorWindow.color = curveColor; - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse || (evt as KeyDownEvent)?.character == '\n') - ShowCurveEditor(); - else if (evt.GetEventTypeId() == DetachFromPanelEvent.TypeId()) - OnDetach(); - if (evt.GetEventTypeId() == GeometryChangedEvent.TypeId()) - m_TextureDirty = true; - } - - void OnCurveChanged(AnimationCurve curve) - { - CurveEditorWindow.curve = m_Value; - value = m_Value; - } - - public override void OnPersistentDataReady() - { - base.OnPersistentDataReady(); - m_TextureDirty = true; - } - - // Must be the same with AACurveField.shader - const float k_EdgeWidth = 2; - const float k_MinEdgeWidth = 1.75f; - const float k_HalfWidth = k_EdgeWidth * 0.5f; - const float k_VertexHalfWidth = k_HalfWidth + 1; - - const int k_HorizontalCurveResolution = 256; - - void FillCurveData() - { - AnimationCurve curve = value; - - if (m_Mesh == null) - { - m_Mesh = new Mesh(); - m_Mesh.hideFlags = HideFlags.HideAndDontSave; - - m_Content.SetMesh(m_Mesh); - } - - if (curve.keys.Length < 2) - return; - Vector3[] vertices = m_Mesh.vertices; - Vector3[] normals = m_Mesh.normals; - if (vertices == null || vertices.Length != k_HorizontalCurveResolution * 2) - { - vertices = new Vector3[k_HorizontalCurveResolution * 2]; - normals = new Vector3[k_HorizontalCurveResolution * 2]; - } - - float startTime = curve.keys[0].time; - float endTime = curve.keys[curve.keys.Length - 1].time; - float duration = endTime - startTime; - - float minValue = Mathf.Infinity; - float maxValue = -Mathf.Infinity; - - float[] timeCache = new float[k_HorizontalCurveResolution]; - int keyCount = curve.keys.Length; - int noKeySampleCount = k_HorizontalCurveResolution - keyCount; - - timeCache[0] = curve.keys[0].time; - - int usedSamples = 1; - for (int k = 1; k < keyCount; ++k) - { - float sliceStartTime = timeCache[usedSamples - 1]; - float sliceEndTime = curve.keys[k].time; - float sliceDuration = sliceEndTime - sliceStartTime; - int sliceSampleCount = Mathf.FloorToInt((float)noKeySampleCount * sliceDuration / duration); - if (k == keyCount - 1) - { - sliceSampleCount = k_HorizontalCurveResolution - usedSamples - 1; - } - - for (int i = 1; i < sliceSampleCount + 1; ++i) - { - float time = sliceStartTime + i * sliceDuration / (sliceSampleCount + 1); - timeCache[usedSamples + i - 1] = time; - } - - timeCache[usedSamples + sliceSampleCount] = curve.keys[k].time; - usedSamples += sliceSampleCount + 1; - } - - float[] valueCache = new float[k_HorizontalCurveResolution]; - - for (int i = 0; i < k_HorizontalCurveResolution; ++i) - { - float ct = timeCache[i]; - - float currentValue = curve.Evaluate(ct); - - if (currentValue > maxValue) - { - maxValue = currentValue; - } - if (currentValue < minValue) - { - minValue = currentValue; - } - - valueCache[i] = currentValue; - } - - Vector3 scale = new Vector3(m_Content.layout.width, m_Content.layout.height); - - vertices[0] = vertices[1] = Vector3.Scale(new Vector3(0, 1 - Mathf.InverseLerp(minValue, maxValue, valueCache[0]), 0), scale); - - Vector3 secondPoint = Vector3.Scale(new Vector3(1.0f / k_HorizontalCurveResolution, 1 - Mathf.InverseLerp(minValue, maxValue, valueCache[1]), 0), scale); - Vector3 prevDir = (secondPoint - vertices[0]).normalized; - - Vector3 norm = new Vector3(prevDir.y, -prevDir.x, 1); - - normals[0] = -norm * k_VertexHalfWidth; - normals[1] = norm * k_VertexHalfWidth; - - Vector3 currentPoint = secondPoint; - - for (int i = 1; i < k_HorizontalCurveResolution - 1; ++i) - { - vertices[i * 2] = vertices[i * 2 + 1] = currentPoint; - - Vector3 nextPoint = Vector3.Scale(new Vector3(Mathf.InverseLerp(startTime, endTime, timeCache[i + 1]), 1 - Mathf.InverseLerp(minValue, maxValue, valueCache[i + 1]), 0), scale); - - Vector3 nextDir = (nextPoint - currentPoint).normalized; - Vector3 dir = (prevDir + nextDir).normalized; - norm = new Vector3(dir.y, -dir.x, 1); - normals[i * 2] = -norm * k_VertexHalfWidth; - normals[i * 2 + 1] = norm * k_VertexHalfWidth; - - currentPoint = nextPoint; - prevDir = nextDir; - } - - vertices[(k_HorizontalCurveResolution - 1) * 2] = vertices[(k_HorizontalCurveResolution - 1) * 2 + 1] = currentPoint; - - norm = new Vector3(prevDir.y, -prevDir.x, 1); - normals[(k_HorizontalCurveResolution - 1) * 2] = -norm * k_VertexHalfWidth; - normals[(k_HorizontalCurveResolution - 1) * 2 + 1] = norm * k_VertexHalfWidth; - - m_Mesh.vertices = vertices; - m_Mesh.normals = normals; - - //fill triangle indices as it is a triangle strip - int[] indices = new int[(k_HorizontalCurveResolution * 2 - 2) * 3]; - - for (int i = 0; i < k_HorizontalCurveResolution * 2 - 2; ++i) - { - if ((i % 2) == 0) - { - indices[i * 3] = i; - indices[i * 3 + 1] = i + 1; - indices[i * 3 + 2] = i + 2; - } - else - { - indices[i * 3] = i + 1; - indices[i * 3 + 1] = i; - indices[i * 3 + 2] = i + 2; - } - } - - m_Mesh.triangles = indices; - } - - void SetupMeshRepaint() - { - if (m_TextureDirty || m_Mesh == null) - { - m_TextureDirty = false; - style.backgroundImage = null; - - FillCurveData(); - } - m_Content.curveColor = curveColor; - } - - void SetupStandardRepaint() - { - if (!m_TextureDirty) return; - - m_TextureDirty = false; - - int previewWidth = (int)layout.width; - int previewHeight = (int)layout.height; - - Rect rangeRect = new Rect(0, 0, 1, 1); - - if (ranges.width > 0 && ranges.height > 0) - { - rangeRect = ranges; - } - else if (!m_ValueNull && m_Value.keys.Length > 1) - { - float xMin = Mathf.Infinity; - float yMin = Mathf.Infinity; - float xMax = -Mathf.Infinity; - float yMax = -Mathf.Infinity; - - for (int i = 0; i < m_Value.keys.Length; ++i) - { - float y = m_Value.keys[i].value; - float x = m_Value.keys[i].time; - if (xMin > x) - { - xMin = x; - } - if (xMax < x) - { - xMax = x; - } - if (yMin > y) - { - yMin = y; - } - if (yMax < y) - { - yMax = y; - } - } - - if (yMin == yMax) - { - yMax = yMin + 1; - } - if (xMin == xMax) - { - xMax = xMin + 1; - } - - rangeRect = Rect.MinMaxRect(xMin, yMin, xMax, yMax); - } - - if (previewHeight > 0 && previewWidth > 0) - { - if (!m_ValueNull) - { - style.backgroundImage = AnimationCurvePreviewCache.GenerateCurvePreview( - previewWidth, - previewHeight, - rangeRect, - m_Value, - curveColor, - style.backgroundImage.value); - } - else - { - style.backgroundImage = null; - } - } - } - - Mesh m_Mesh = null; - protected override void DoRepaint(IStylePainter painter) - { - if (renderMode == RenderMode.Mesh) - { - SetupMeshRepaint(); - } - else - { - SetupStandardRepaint(); - } - } - - class CurveFieldContent : VisualElement - { - Material m_Mat; - Mesh m_Mesh; - - public Color curveColor { get; set; } - - public void SetMesh(Mesh mesh) - { - m_Mesh = mesh; - } - - public CurveFieldContent() - { - pickingMode = PickingMode.Ignore; - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if (evt.GetEventTypeId() == DetachFromPanelEvent.TypeId()) - OnDetach(); - } - - void OnDetach() - { - Object.DestroyImmediate(m_Mat); - m_Mat = null; - } - - protected override void DoRepaint(IStylePainter painter) - { - if (m_Mesh != null) - { - if (m_Mat == null) - { - m_Mat = new Material(EditorGUIUtility.LoadRequired("Shaders/UIElements/AACurveField.shader") as Shader); - - m_Mat.hideFlags = HideFlags.HideAndDontSave; - } - - float scale = worldTransform.MultiplyVector(Vector3.one).x; - - float realWidth = CurveField.k_EdgeWidth; - if (realWidth * scale < CurveField.k_MinEdgeWidth) - { - realWidth = CurveField.k_MinEdgeWidth / scale; - } - - // Send the view zoom factor so that the antialias width do not grow when zooming in. - m_Mat.SetFloat("_ZoomFactor", scale * realWidth / CurveField.k_EdgeWidth * EditorGUIUtility.pixelsPerPoint); - - // Send the view zoom correction so that the vertex shader can scale the edge triangles when below m_MinWidth. - m_Mat.SetFloat("_ZoomCorrection", realWidth / CurveField.k_EdgeWidth); - - m_Mat.SetColor("_Color", (QualitySettings.activeColorSpace == ColorSpace.Linear) ? curveColor.gamma : curveColor); - - var stylePainter = (IStylePainterInternal)painter; - var meshParams = MeshStylePainterParameters.GetDefault(m_Mesh, m_Mat); - stylePainter.DrawMesh(meshParams); - } - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/DoubleField.cs b/Editor/Mono/UIElements/Experimental/Controls/DoubleField.cs deleted file mode 100644 index 30df7e9921..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/DoubleField.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class DoubleField : TextValueField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : TextValueField.UxmlTraits - { - UxmlDoubleAttributeDescription m_Value = new UxmlDoubleAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - ((DoubleField)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - } - } - - public DoubleField() - : this(kMaxLengthNone) {} - - public DoubleField(int maxLength) - : base(maxLength) - { - formatString = EditorGUI.kDoubleFieldFormatString; - } - - protected override string allowedCharacters - { - get { return EditorGUI.s_AllowedCharactersForFloat; } - } - - public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, double startValue) - { - double sensitivity = NumericFieldDraggerUtility.CalculateFloatDragSensitivity(startValue); - float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow); - double v = value; - v += NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity; - v = MathUtils.RoundBasedOnMinimumDifference(v, sensitivity); - value = v; - } - - protected override string ValueToString(double v) - { - return v.ToString(formatString); - } - - protected override double StringToValue(string str) - { - double v; - EditorGUI.StringToDouble(str, out v); - return v; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/EnumField.cs b/Editor/Mono/UIElements/Experimental/Controls/EnumField.cs deleted file mode 100644 index 9a510795e5..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/EnumField.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class EnumField : BaseField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits - { - UxmlStringAttributeDescription m_Type = new UxmlStringAttributeDescription { name = "type", use = UxmlAttributeDescription.Use.Required}; - UxmlStringAttributeDescription m_Value = new UxmlStringAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - EnumField enumField = (EnumField)ve; - // Only works for the currently running assembly - enumField.m_EnumType = Type.GetType(m_Type.GetValueFromBag(bag, cc)); - if (enumField.m_EnumType != null) - { - string v = m_Value.GetValueFromBag(bag, cc); - - if (!Enum.IsDefined(enumField.m_EnumType, v)) - { - Debug.LogErrorFormat("Could not parse value of '{0}', because it isn't defined in the {1} enum.", v, enumField.m_EnumType.FullName); - enumField.SetValueWithoutNotify(null); - } - else - { - enumField.SetValueWithoutNotify((Enum)Enum.Parse(enumField.m_EnumType, v)); - } - } - } - } - - private Type m_EnumType; - private TextElement m_TextElement; - - public string text - { - get { return m_TextElement.text; } - } - - private void Initialize(Enum defaultValue) - { - m_TextElement = new TextElement(); - m_TextElement.pickingMode = PickingMode.Ignore; - Add(m_TextElement); - if (defaultValue != null) - { - Init(defaultValue); - } - } - - public EnumField() - { - Initialize(null); - } - - public EnumField(Enum defaultValue) - { - Initialize(defaultValue); - } - - public void Init(Enum defaultValue) - { - m_EnumType = defaultValue.GetType(); - SetValueWithoutNotify(defaultValue); - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(Enum newValue) - { - if (value != newValue) - { - value = newValue; - } - } - - public override void SetValueWithoutNotify(Enum newValue) - { - if (m_Value != newValue) - { - base.SetValueWithoutNotify(newValue); - m_TextElement.text = ObjectNames.NicifyVariableName(m_Value.ToString()); - } - } - - protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) - { - base.ExecuteDefaultActionAtTarget(evt); - - if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse || (evt as KeyDownEvent)?.character == '\n') - { - ShowMenu(); - evt.StopPropagation(); - } - } - - private void ShowMenu() - { - if (m_EnumType == null) - return; - - var menu = new GenericMenu(); - - foreach (Enum item in Enum.GetValues(m_EnumType)) - { - bool isSelected = item.CompareTo(value) == 0; - string label = ObjectNames.NicifyVariableName(item.ToString()); - menu.AddItem(new GUIContent(label), isSelected, - contentView => ChangeValueFromMenu(contentView), - item); - } - - var menuPosition = new Vector2(0.0f, layout.height); - menuPosition = this.LocalToWorld(menuPosition); - var menuRect = new Rect(menuPosition, Vector2.zero); - menu.DropDown(menuRect); - } - - private void ChangeValueFromMenu(object menuItem) - { - value = menuItem as Enum; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/FloatField.cs b/Editor/Mono/UIElements/Experimental/Controls/FloatField.cs deleted file mode 100644 index 80704b1811..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/FloatField.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class FloatField : TextValueField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : TextValueField.UxmlTraits - { - UxmlFloatAttributeDescription m_Value = new UxmlFloatAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - ((FloatField)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - } - } - - public FloatField() - : this(kMaxLengthNone) {} - - public FloatField(int maxLength) - : base(maxLength) - { - formatString = EditorGUI.kFloatFieldFormatString; - } - - protected override string allowedCharacters - { - get { return EditorGUI.s_AllowedCharactersForFloat; } - } - - public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, float startValue) - { - double sensitivity = NumericFieldDraggerUtility.CalculateFloatDragSensitivity(startValue); - float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow); - double v = value; - v += NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity; - v = MathUtils.RoundBasedOnMinimumDifference(v, sensitivity); - value = MathUtils.ClampToFloat(v); - } - - protected override string ValueToString(float v) - { - return v.ToString(formatString); - } - - protected override float StringToValue(string str) - { - double v; - EditorGUI.StringToDouble(str, out v); - return MathUtils.ClampToFloat(v); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/GradientField.cs b/Editor/Mono/UIElements/Experimental/Controls/GradientField.cs deleted file mode 100644 index 10177ce0e4..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/GradientField.cs +++ /dev/null @@ -1,155 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEditorInternal; -using UnityEngine.Experimental.UIElements; -using Object = UnityEngine.Object; - -namespace UnityEditor.Experimental.UIElements -{ - public class GradientField : BaseField - { - static readonly GradientColorKey k_WhiteKeyBegin = new GradientColorKey(Color.white, 0); - static readonly GradientColorKey k_WhiteKeyEnd = new GradientColorKey(Color.white, 1); - static readonly GradientAlphaKey k_AlphaKeyBegin = new GradientAlphaKey(1, 0); - static readonly GradientAlphaKey k_AlphaKeyEnd = new GradientAlphaKey(1, 1); - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits {} - - private bool m_ValueNull; - public override Gradient value - { - get - { - if (m_ValueNull) return null; - - return GradientCopy(m_Value); - } - set - { - if (value != null || !m_ValueNull) // let's not reinitialize an initialized gradient - { - if (panel != null) - { - using (ChangeEvent evt = ChangeEvent.GetPooled(m_Value, value)) - { - evt.target = this; - SetValueWithoutNotify(value); - SendEvent(evt); - } - } - else - { - SetValueWithoutNotify(value); - } - } - } - } - - internal static Gradient GradientCopy(Gradient other) - { - Gradient gradientCopy = new Gradient(); - gradientCopy.colorKeys = other.colorKeys; - gradientCopy.alphaKeys = other.alphaKeys; - gradientCopy.mode = other.mode; - return gradientCopy; - } - - public GradientField() - { - VisualElement borderElement = new VisualElement() { name = "border", pickingMode = PickingMode.Ignore }; - Add(borderElement); - - m_Value = new Gradient(); - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse || (evt as KeyDownEvent)?.character == '\n') - ShowGradientPicker(); - else if (evt.GetEventTypeId() == DetachFromPanelEvent.TypeId()) - OnDetach(); - else if (evt.GetEventTypeId() == AttachToPanelEvent.TypeId()) - OnAttach(); - } - - void OnDetach() - { - if (style.backgroundImage.value != null) - { - Object.DestroyImmediate(style.backgroundImage.value); - style.backgroundImage = null; - } - } - - void OnAttach() - { - UpdateGradientTexture(); - } - - void ShowGradientPicker() - { - GradientPicker.Show(m_Value, true, OnGradientChanged); - } - - public override void OnPersistentDataReady() - { - base.OnPersistentDataReady(); - UpdateGradientTexture(); - } - - void UpdateGradientTexture() - { - if (m_ValueNull) - { - style.backgroundImage = null; - } - else - { - Texture2D gradientTexture = UnityEditorInternal.GradientPreviewCache.GenerateGradientPreview(value, style.backgroundImage.value); - - style.backgroundImage = gradientTexture; - - IncrementVersion(VersionChangeType.Repaint); // since the Texture2D object can be reused, force dirty because the backgroundImage change will only trigger the Dirty if the Texture2D objects are different. - } - } - - void OnGradientChanged(Gradient newValue) - { - value = newValue; - - GradientPreviewCache.ClearCache(); // needed because GradientEditor itself uses the cache and will no invalidate it on changes. - IncrementVersion(VersionChangeType.Repaint); - } - - public override void SetValueWithoutNotify(Gradient newValue) - { - m_ValueNull = newValue == null; - if (!m_ValueNull) - { - m_Value.colorKeys = newValue.colorKeys; - m_Value.alphaKeys = newValue.alphaKeys; - m_Value.mode = newValue.mode; - } - else // restore the internal gradient to the default state. - { - m_Value.colorKeys = new[] { k_WhiteKeyBegin, k_WhiteKeyEnd }; - m_Value.alphaKeys = new[] { k_AlphaKeyBegin, k_AlphaKeyEnd }; - m_Value.mode = GradientMode.Blend; - } - UpdateGradientTexture(); - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(Gradient newValue) - { - value = newValue; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/IntegerField.cs b/Editor/Mono/UIElements/Experimental/Controls/IntegerField.cs deleted file mode 100644 index d9aee658ab..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/IntegerField.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class IntegerField : TextValueField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : TextValueField.UxmlTraits - { - UxmlIntAttributeDescription m_Value = new UxmlIntAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - ((IntegerField)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - } - } - - public IntegerField() - : this(kMaxLengthNone) {} - - public IntegerField(int maxLength) - : base(maxLength) - { - formatString = EditorGUI.kIntFieldFormatString; - } - - protected override string allowedCharacters - { - get { return EditorGUI.s_AllowedCharactersForInt; } - } - - public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, int startValue) - { - double sensitivity = NumericFieldDraggerUtility.CalculateIntDragSensitivity(startValue); - float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow); - long v = value; - v += (long)Math.Round(NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity); - value = MathUtils.ClampToInt(v); - } - - protected override string ValueToString(int v) - { - return v.ToString(formatString); - } - - protected override int StringToValue(string str) - { - long v; - EditorGUI.StringToLong(text, out v); - return MathUtils.ClampToInt(v); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/LayerField.cs b/Editor/Mono/UIElements/Experimental/Controls/LayerField.cs deleted file mode 100644 index d4dfd4841f..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/LayerField.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEditorInternal; - -namespace UnityEditor.Experimental.UIElements -{ - public class LayerField : PopupField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : PopupField.UxmlTraits - { - UxmlIntAttributeDescription m_Value = new UxmlIntAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var lf = (LayerField)ve; - lf.SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - } - } - - internal override string GetValueToDisplay() - { - return InternalEditorUtility.GetLayerName(m_Value); - } - - public override int value - { - get { return base.value; } - set - { - if (m_Choices.Contains(value)) - { - base.value = value; - } - } - } - - public override Func formatSelectedValueCallback - { - get { return null; } - set - { - Debug.LogWarning(L10n.Tr("LayerField doesn't support the formatting of the selected value.")); - m_FormatSelectedValueCallback = null; - } - } - - public override Func formatListItemCallback - { - get { return null; } - set - { - Debug.LogWarning(L10n.Tr("LayerField doesn't support the formatting of the list items.")); - m_FormatListItemCallback = null; - } - } - - public override void SetValueWithoutNotify(int newValue) - { - if (m_Choices.Contains(newValue)) - { - base.SetValueWithoutNotify(newValue); - } - } - - static List InitializeLayers() - { - var listOfIndex = new List(); - for (var i = 0; i < 32; i++) - { - if (InternalEditorUtility.GetLayerName(i).Length != 0) - { - listOfIndex.Add(i); - } - } - return listOfIndex; - } - - public LayerField() : base(InitializeLayers()) - { - } - - public LayerField(int defaultValue) : this() - { - SetValueWithoutNotify(defaultValue); - } - - internal override void AddMenuItems(GenericMenu menu) - { - choices = InitializeLayers(); - string[] layerList = InternalEditorUtility.GetLayersWithId(); - for (var i = 0; i < layerList.Length; i++) - { - var item = layerList[i]; - var menuItemIndex = m_Choices[i]; - var isSelected = (menuItemIndex == value); - menu.AddItem(new GUIContent(item), isSelected, - () => ChangeValueFromMenu(menuItemIndex)); - } - menu.AddItem(new GUIContent(""), false, null); - menu.AddItem(new GUIContent(L10n.Tr("Add Layer...")), false, OpenLayerInspector); - } - - void ChangeValueFromMenu(int menuItemIndex) - { - value = menuItemIndex; - } - - static void OpenLayerInspector() - { - TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.Layers); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/LayerMaskField.cs b/Editor/Mono/UIElements/Experimental/Controls/LayerMaskField.cs deleted file mode 100644 index c45001e5fe..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/LayerMaskField.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class LayerMaskField : MaskField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : MaskField.UxmlTraits {} - - public override Func formatSelectedValueCallback - { - get { return null; } - set - { - Debug.LogWarning(L10n.Tr("LayerMaskField doesn't support the formatting of the selected value.")); - m_FormatSelectedValueCallback = null; - } - } - - public override Func formatListItemCallback - { - get { return null; } - set - { - Debug.LogWarning(L10n.Tr("LayerMaskField doesn't support the formatting of the list items.")); - m_FormatListItemCallback = null; - } - } - - void UpdateLayersInfo() - { - // Get the layers : names and values - string[] layerNames = null; - int[] layerValues = null; - TagManager.GetDefinedLayers(ref layerNames, ref layerValues); - - // Create the appropriate lists... - choices = new List(layerNames); - choicesMasks = new List(layerValues); - } - - public LayerMaskField(int defaultMask) : this() - { - SetValueWithoutNotify(defaultMask); - } - - public LayerMaskField() - { - UpdateLayersInfo(); - } - - internal override void AddMenuItems(GenericMenu menu) - { - // We must update the choices and the values since we don't know if they changed... - UpdateLayersInfo(); - - // Create the menu the usual way... - base.AddMenuItems(menu); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/LongField.cs b/Editor/Mono/UIElements/Experimental/Controls/LongField.cs deleted file mode 100644 index 050990a1ce..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/LongField.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class LongField : TextValueField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : TextValueField.UxmlTraits - { - UxmlLongAttributeDescription m_Value = new UxmlLongAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - ((LongField)ve).SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - } - } - - public LongField() - : this(kMaxLengthNone) {} - - public LongField(int maxLength) - : base(maxLength) - { - formatString = EditorGUI.kIntFieldFormatString; - } - - protected override string allowedCharacters - { - get { return EditorGUI.s_AllowedCharactersForInt; } - } - - public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, long startValue) - { - double sensitivity = NumericFieldDraggerUtility.CalculateIntDragSensitivity(startValue); - float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow); - long v = value; - v += (long)Math.Round(NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity); - value = v; - } - - protected override string ValueToString(long v) - { - return v.ToString(formatString); - } - - protected override long StringToValue(string str) - { - long v; - EditorGUI.StringToLong(text, out v); - return v; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/MaskField.cs b/Editor/Mono/UIElements/Experimental/Controls/MaskField.cs deleted file mode 100644 index ff5c82e292..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/MaskField.cs +++ /dev/null @@ -1,428 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Profiling; - -namespace UnityEditor.Experimental.UIElements -{ - public class MaskField : BasePopupField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BasePopupField.UxmlTraits - { - UxmlStringAttributeDescription m_MaskChoices = new UxmlStringAttributeDescription { name = "choices" }; - UxmlIntAttributeDescription m_MaskValue = new UxmlIntAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var f = (MaskField)ve; - string choicesFromBag = m_MaskChoices.GetValueFromBag(bag, cc); - // Here the choices is comma separated in the string... - string[] choices = choicesFromBag.Split(','); - - if (choices.Length != 0) - { - List listOfChoices = new List(); - foreach (var choice in choices) - { - listOfChoices.Add(choice.Trim()); - } - f.choices = listOfChoices; - } - // The mask is simply an int - f.SetValueWithoutNotify(m_MaskValue.GetValueFromBag(bag, cc)); - } - } - - static int s_NothingIndex = 0; - static int s_EverythingIndex = 1; - static int s_TotalIndex = 2; - - // This is the list of string representing all the user choices - List m_UserChoices; - - // This is the list of masks for every specific choices... if null, the mask will be computed with the default values - // More details about this : - // In IMGUI, the MaskField is only allowing the creation of the field with an array of choices that will have a mask - // based on power of 2 value starting from 1. - // However, the LayerMaskField is created based on the Layers and do not necessarily has power of 2 consecutive masks. - // Therefore, this specific internal field (in IMGUI...) is requiring a specific array to contain the mask value of the - // actual list of choices. - List m_UserChoicesMasks; - - // This is containing a mask to cover all the choices from the list. Computed with the help of m_UserChoicesMasks - // or based on the power of 2 mask values. - int m_FullChoiceMask; - - internal override List choices - { - get { return m_UserChoices; } - set - { - if (value == null) - { - throw new ArgumentNullException("choices", "choices can't be null"); - } - - // Keep the original list in a separate user list ... - if (m_UserChoices == null) - { - m_UserChoices = new List(); - } - else - { - m_UserChoices.Clear(); - } - m_UserChoices.AddRange(value); - - // Now, add the nothing and everything choices... - if (m_Choices == null) - { - m_Choices = new List(); - } - else - { - m_Choices.Clear(); - } - m_Choices.Add(L10n.Tr("Nothing")); - m_Choices.Add(L10n.Tr("Everything")); - m_Choices.AddRange(m_UserChoices); - - ComputeFullChoiceMask(); - - // Make sure to update the text displayed - SetValueWithoutNotify(m_Value); - } - } - internal virtual List choicesMasks - { - get { return m_UserChoicesMasks; } - set - { - if (value == null) - { - m_UserChoicesMasks = null; - } - else - { - // Keep the original list in a separate user list ... - if (m_UserChoicesMasks == null) - { - m_UserChoicesMasks = new List(); - } - else - { - m_UserChoicesMasks.Clear(); - } - m_UserChoicesMasks.AddRange(value); - ComputeFullChoiceMask(); - // Make sure to update the text displayed - SetValueWithoutNotify(m_Value); - } - } - } - - public virtual Func formatSelectedValueCallback - { - get { return m_FormatSelectedValueCallback; } - set - { - m_FormatSelectedValueCallback = value; - m_TextElement.text = GetValueToDisplay(); - } - } - - public virtual Func formatListItemCallback - { - get { return m_FormatListItemCallback; } - set { m_FormatListItemCallback = value; } - } - - public override void SetValueWithoutNotify(int newValue) - { - base.SetValueWithoutNotify(UpdateMaskIfEverything(newValue)); - } - - internal override string GetListItemToDisplay(int itemIndex) - { - string displayedValue = GetDisplayedValue(itemIndex); - if (ShouldFormatListItem(itemIndex)) - displayedValue = m_FormatListItemCallback(displayedValue); - - return displayedValue; - } - - internal override string GetValueToDisplay() - { - string displayedValue = GetDisplayedValue(m_Value); - if (ShouldFormatSelectedValue()) - displayedValue = m_FormatSelectedValueCallback(displayedValue); - return displayedValue; - } - - // Trick to get the number of selected values... - // A power of 2 number means only 1 selected... - internal bool IsPowerOf2(int itemIndex) - { - return ((itemIndex & (itemIndex - 1)) == 0); - } - - internal bool ShouldFormatListItem(int itemIndex) - { - return itemIndex != 0 && itemIndex != -1 && m_FormatListItemCallback != null; - } - - internal bool ShouldFormatSelectedValue() - { - return m_Value != 0 && m_Value != -1 && m_FormatSelectedValueCallback != null && IsPowerOf2(m_Value); - } - - internal string GetDisplayedValue(int itemIndex) - { - var newValueToShowUser = ""; - - switch (itemIndex) - { - case 0: - newValueToShowUser = m_Choices[s_NothingIndex]; - break; - - case ~0: - newValueToShowUser = m_Choices[s_EverythingIndex]; - break; - - default: - // Show up the right selected value - if (IsPowerOf2(itemIndex)) - { - var indexOfValue = 0; - if (m_UserChoicesMasks != null) - { - // Find the actual index of the selected choice... - foreach (int itemMask in m_UserChoicesMasks) - { - if ((itemMask & itemIndex) == itemIndex) - { - indexOfValue = m_UserChoicesMasks.IndexOf(itemMask); - break; - } - } - } - else - { - while ((1 << indexOfValue) != itemIndex) - { - indexOfValue++; - } - } - - // To get past the Nothing + Everything choices... - indexOfValue += s_TotalIndex; - if (indexOfValue < m_Choices.Count) - { - newValueToShowUser = m_Choices[indexOfValue]; - } - } - else - { - newValueToShowUser = L10n.Tr("Mixed ..."); - } - break; - } - return newValueToShowUser; - } - - internal override void AddMenuItems(GenericMenu menu) - { - foreach (var item in m_Choices) - { - var maskOfItem = GetMaskValueOfItem(item); - var isSelected = false; - switch (maskOfItem) - { - case 0: - if (value == 0) - { - isSelected = true; - } - break; - - case ~0: - if (value == ~0) - { - isSelected = true; - } - break; - - default: - if ((maskOfItem & value) == maskOfItem) - { - isSelected = true; - } - break; - } - - menu.AddItem(new GUIContent(GetListItemToDisplay(maskOfItem)), isSelected, () => ChangeValueFromMenu(item)); - } - } - - void ComputeFullChoiceMask() - { - // Compute the full mask for all the items... it is not necessarily ~0 (which is all bits set to 1) - if (m_UserChoices.Count == 0) - { - m_FullChoiceMask = 0; - } - else - { - if ((m_UserChoicesMasks != null) && (m_UserChoicesMasks.Count == m_UserChoices.Count)) - { - if (m_UserChoices.Count >= (sizeof(int) * 8)) - { - m_FullChoiceMask = ~0; - } - else - { - m_FullChoiceMask = 0; - foreach (int itemMask in m_UserChoicesMasks) - { - m_FullChoiceMask |= itemMask; - } - } - } - else - { - if (m_UserChoices.Count >= (sizeof(int) * 8)) - { - m_FullChoiceMask = ~0; - } - else - { - m_FullChoiceMask = (1 << m_UserChoices.Count) - 1; - } - } - } - } - - private MaskField(List choices, Func formatSelectedValueCallback = null, Func formatListItemCallback = null) - { - this.choices = choices; - m_FormatListItemCallback = formatListItemCallback; - m_FormatSelectedValueCallback = formatSelectedValueCallback; - } - - public MaskField(List choices, int defaultMask, Func formatSelectedValueCallback = null, Func formatListItemCallback = null) : - this(choices, formatSelectedValueCallback, formatListItemCallback) - { - SetValueWithoutNotify(defaultMask); - } - - public MaskField() - { - } - - // Returns the mask to be used for the item... - int GetMaskValueOfItem(string item) - { - var maskValue = 0; - var indexOfItem = m_Choices.IndexOf(item); - switch (indexOfItem) - { - case 0: // Nothing - maskValue = 0; - break; - case 1: // Everything - maskValue = ~0; - break; - default: // All others - if (indexOfItem > 0) - { - if ((m_UserChoicesMasks != null) && (m_UserChoicesMasks.Count == m_UserChoices.Count)) - { - maskValue = m_UserChoicesMasks[(indexOfItem - s_TotalIndex)]; - } - else - { - maskValue = 1 << (indexOfItem - s_TotalIndex); - } - } - else - { - // If less than 0, it means the item was not found... - maskValue = 0; - } - - break; - } - return maskValue; - } - - // Based on the current mask, this is updating the value of the actual mask to use vs the full mask. - // This is returning ~0 if all the values are selected... - int UpdateMaskIfEverything(int currentMask) - { - int newMask = currentMask; - // If the mask is full, put back the Everything flag. - if (m_FullChoiceMask != 0) - { - if ((currentMask & m_FullChoiceMask) == m_FullChoiceMask) - { - newMask = ~0; - } - else - { - newMask &= m_FullChoiceMask; - } - } - - return newMask; - } - - private void ChangeValueFromMenu(string menuItem) - { - var newMask = value; - var maskFromItem = GetMaskValueOfItem(menuItem); - switch (maskFromItem) - { - // Nothing - case 0: - newMask = 0; - break; - - // Everything - case ~0: - newMask = ~0; - break; - - default: - // Make sure to have only the real selected one... - newMask &= m_FullChoiceMask; - - // Add or remove the newly selected... - if ((newMask & maskFromItem) == maskFromItem) - { - newMask &= ~maskFromItem; - } - else - { - newMask |= maskFromItem; - } - - // If the mask is full, put back the Everything flag. - newMask = UpdateMaskIfEverything(newMask); - break; - } - // Finally, make sure to update the value of the mask... - value = newMask; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/ObjectField.cs b/Editor/Mono/UIElements/Experimental/Controls/ObjectField.cs deleted file mode 100644 index 08d6283a15..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/ObjectField.cs +++ /dev/null @@ -1,256 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using Object = UnityEngine.Object; - -namespace UnityEditor.Experimental.UIElements -{ - public class ObjectField : BaseField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : BaseField.UxmlTraits - { - UxmlBoolAttributeDescription m_AllowSceneObjects = new UxmlBoolAttributeDescription { name = "allow-scene-objects", obsoleteNames = new[] { "allowSceneObjects" }, defaultValue = true }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - ((ObjectField)ve).allowSceneObjects = m_AllowSceneObjects.GetValueFromBag(bag, cc); - } - } - - public override void SetValueWithoutNotify(Object newValue) - { - var valueChanged = !EqualityComparer.Default.Equals(this.value, newValue); - - base.SetValueWithoutNotify(newValue); - - if (valueChanged) - { - m_ObjectFieldDisplay.Update(); - } - } - - private Type m_objectType; - - public Type objectType - { - get { return m_objectType; } - set - { - if (m_objectType != value) - { - m_objectType = value; - m_ObjectFieldDisplay.Update(); - } - } - } - - public bool allowSceneObjects { get; set; } - - private class ObjectFieldDisplay : VisualElement - { - private readonly ObjectField m_ObjectField; - private readonly Image m_ObjectIcon; - private readonly Label m_ObjectLabel; - - public ObjectFieldDisplay(ObjectField objectField) - { - m_ObjectIcon = new Image {scaleMode = ScaleMode.ScaleAndCrop, pickingMode = PickingMode.Ignore}; - m_ObjectLabel = new Label {pickingMode = PickingMode.Ignore}; - m_ObjectField = objectField; - - Update(); - - Add(m_ObjectIcon); - Add(m_ObjectLabel); - } - - public void Update() - { - GUIContent content = EditorGUIUtility.ObjectContent(m_ObjectField.value, m_ObjectField.objectType); - m_ObjectIcon.image = content.image; - m_ObjectLabel.text = content.text; - } - - protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) - { - base.ExecuteDefaultActionAtTarget(evt); - - if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse) - OnMouseDown(evt as MouseDownEvent); - else if ((evt as KeyDownEvent)?.character == '\n') - OnKeyboardEnter(); - else if (evt.GetEventTypeId() == DragUpdatedEvent.TypeId()) - OnDragUpdated(evt); - else if (evt.GetEventTypeId() == DragPerformEvent.TypeId()) - OnDragPerform(evt); - else if (evt.GetEventTypeId() == DragLeaveEvent.TypeId()) - OnDragLeave(); - } - - private void OnDragLeave() - { - // Make sure we've cleared the accept drop look, whether we we in a drop operation or not. - RemoveFromClassList("acceptDrop"); - } - - private void OnMouseDown(MouseDownEvent evt) - { - Object actualTargetObject = m_ObjectField.value; - Component com = actualTargetObject as Component; - if (com) - actualTargetObject = com.gameObject; - - if (actualTargetObject == null) - return; - - // One click shows where the referenced object is, or pops up a preview - if (evt.clickCount == 1) - { - // ping object - bool anyModifiersPressed = evt.shiftKey || evt.ctrlKey; - if (!anyModifiersPressed && actualTargetObject) - { - EditorGUIUtility.PingObject(actualTargetObject); - } - evt.StopPropagation(); - } - // Double click opens the asset in external app or changes selection to referenced object - else if (evt.clickCount == 2) - { - if (actualTargetObject) - { - AssetDatabase.OpenAsset(actualTargetObject); - GUIUtility.ExitGUI(); - } - evt.StopPropagation(); - } - } - - private void OnKeyboardEnter() - { - m_ObjectField.ShowObjectSelector(); - } - - private Object DNDValidateObject() - { - Object[] references = DragAndDrop.objectReferences; - Object validatedObject = EditorGUI.ValidateObjectFieldAssignment(references, m_ObjectField.objectType, null, EditorGUI.ObjectFieldValidatorOptions.None); - - if (validatedObject != null) - { - // If scene objects are not allowed and object is a scene object then clear - if (!m_ObjectField.allowSceneObjects && !EditorUtility.IsPersistent(validatedObject)) - validatedObject = null; - } - return validatedObject; - } - - private void OnDragUpdated(EventBase evt) - { - Object validatedObject = DNDValidateObject(); - if (validatedObject != null) - { - DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - AddToClassList("acceptDrop"); - - evt.StopPropagation(); - } - } - - private void OnDragPerform(EventBase evt) - { - Object validatedObject = DNDValidateObject(); - if (validatedObject != null) - { - DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - m_ObjectField.value = validatedObject; - - DragAndDrop.AcceptDrag(); - RemoveFromClassList("acceptDrop"); - - evt.StopPropagation(); - } - } - } - - private class ObjectFieldSelector : VisualElement - { - private readonly ObjectField m_ObjectField; - - public ObjectFieldSelector(ObjectField objectField) - { - m_ObjectField = objectField; - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if ((evt as MouseDownEvent)?.button == (int)MouseButton.LeftMouse) - m_ObjectField.ShowObjectSelector(); - } - } - - public override int focusIndex - { - get { return base.focusIndex; } - set - { - base.focusIndex = value; - if (m_ObjectFieldDisplay != null) - { - m_ObjectFieldDisplay.focusIndex = value; - } - } - } - - private readonly ObjectFieldDisplay m_ObjectFieldDisplay; - - public ObjectField() - { - allowSceneObjects = true; - - m_ObjectFieldDisplay = new ObjectFieldDisplay(this) {focusIndex = 0}; - var objectSelector = new ObjectFieldSelector(this); - - Add(m_ObjectFieldDisplay); - Add(objectSelector); - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(Object newValue) - { - if (newValue != value) - { - value = newValue; - } - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if (evt.GetEventTypeId() == FocusEvent.TypeId()) - m_ObjectFieldDisplay.Focus(); - } - - private void OnObjectChanged(Object obj) - { - value = obj; - } - - internal void ShowObjectSelector() - { - ObjectSelector.get.Show(value, objectType, null, allowSceneObjects, null, OnObjectChanged, OnObjectChanged); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/PopupField.cs b/Editor/Mono/UIElements/Experimental/Controls/PopupField.cs deleted file mode 100644 index 3f5247cc0f..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/PopupField.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class PopupField : BasePopupField - { - public virtual Func formatSelectedValueCallback - { - get { return m_FormatSelectedValueCallback; } - set - { - m_FormatSelectedValueCallback = value; - m_TextElement.text = GetValueToDisplay(); - } - } - - public virtual Func formatListItemCallback - { - get { return m_FormatListItemCallback; } - set { m_FormatListItemCallback = value; } - } - - internal override string GetValueToDisplay() - { - if (m_FormatSelectedValueCallback != null) - return m_FormatSelectedValueCallback(value); - return value.ToString(); - } - - internal override string GetListItemToDisplay(T value) - { - if (m_FormatListItemCallback != null) - return m_FormatListItemCallback(value); - return value.ToString(); - } - - public override T value - { - get { return base.value; } - set - { - int newIndex = m_Choices.IndexOf(value); - if (newIndex < 0) - { - throw new ArgumentException(string.Format("Value {0} is not present in the list of possible values", value)); - } - m_Index = newIndex; - - base.value = value; - } - } - - public override void SetValueWithoutNotify(T newValue) - { - int newIndex = m_Choices.IndexOf(newValue); - if (newIndex < 0) - { - throw new ArgumentException(string.Format("Value {0} is not present in the list of possible values", newValue)); - } - m_Index = newIndex; - - base.SetValueWithoutNotify(newValue); - } - - private int m_Index = -1; - public int index - { - get { return m_Index; } - set - { - if (value != m_Index) - { - if (value >= m_Choices.Count || value < 0) - throw new ArgumentException(string.Format("Index {0} is beyond the scope of possible value", value)); - m_Index = value; - this.value = m_Choices[m_Index]; - } - } - } - - protected PopupField(List choices, Func formatSelectedValueCallback = null, Func formatListItemCallback = null) - { - this.choices = choices; - m_FormatSelectedValueCallback = formatSelectedValueCallback; - m_FormatListItemCallback = formatListItemCallback; - } - - public PopupField(List choices, T defaultValue, Func formatSelectedValueCallback = null, Func formatListItemCallback = null) : - this(choices, formatSelectedValueCallback, formatListItemCallback) - { - if (defaultValue == null) - throw new ArgumentNullException("defaultValue", "defaultValue can't be null"); - - if (!m_Choices.Contains(defaultValue)) - throw new ArgumentException(string.Format("Default value {0} is not present in the list of possible values", defaultValue)); - - // Note: idx will be set when setting value - SetValueWithoutNotify(defaultValue); - } - - public PopupField(List choices, int defaultIndex, Func formatSelectedValueCallback = null, Func formatListItemCallback = null) : - this(choices, formatSelectedValueCallback, formatListItemCallback) - { - if (defaultIndex >= m_Choices.Count || defaultIndex < 0) - throw new ArgumentException(string.Format("Default Index {0} is beyond the scope of possible value", value)); - - // Note: value will be set when setting idx - index = defaultIndex; - } - - internal override void AddMenuItems(GenericMenu menu) - { - foreach (T item in m_Choices) - { - bool isSelected = EqualityComparer.Default.Equals(item, value); - menu.AddItem(new GUIContent(GetListItemToDisplay(item)), isSelected, - () => ChangeValueFromMenu(item)); - } - } - - private void ChangeValueFromMenu(T menuItem) - { - value = menuItem; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/PropertyControl.cs b/Editor/Mono/UIElements/Experimental/Controls/PropertyControl.cs deleted file mode 100644 index 8136226ed6..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/PropertyControl.cs +++ /dev/null @@ -1,312 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - static class BuiltInTypeConverter - { - static Dictionary s_TypeDictionary; - - static BuiltInTypeConverter() - { - if (s_TypeDictionary == null) - { - s_TypeDictionary = new Dictionary(); - s_TypeDictionary.Add("bool", typeof(long)); - s_TypeDictionary.Add("byte", typeof(byte)); - s_TypeDictionary.Add("sbyte", typeof(sbyte)); - s_TypeDictionary.Add("char", typeof(char)); - s_TypeDictionary.Add("decimal", typeof(decimal)); - s_TypeDictionary.Add("double", typeof(double)); - s_TypeDictionary.Add("float", typeof(float)); - s_TypeDictionary.Add("int", typeof(int)); - s_TypeDictionary.Add("uint", typeof(uint)); - s_TypeDictionary.Add("long", typeof(long)); - s_TypeDictionary.Add("ulong", typeof(ulong)); - s_TypeDictionary.Add("object", typeof(object)); - s_TypeDictionary.Add("short", typeof(short)); - s_TypeDictionary.Add("ushort", typeof(ushort)); - s_TypeDictionary.Add("string", typeof(string)); - } - } - - public static Type GetTypeFromName(string typeName) - { - Type t; - if (!s_TypeDictionary.TryGetValue(typeName, out t)) - { - t = Type.GetType(typeName); - } - - return t; - } - } - internal class PropertyControl : BaseField - { - public new class UxmlFactory : UxmlFactory, UxmlTraits> - { - public override string uxmlName - { - get - { - string name = typeof(PropertyControl).Name; - if (name.Contains("`")) - { - name = name.Substring(0, name.IndexOf("`")); - } - return name; - } - } - - public override string uxmlQualifiedName - { - get { return uxmlNamespace + "." + uxmlName; } - } - - public override bool AcceptsAttributeBag(IUxmlAttributes bag, CreationContext cc) - { - string type = m_Traits.GetValueType(bag, cc); - if (BuiltInTypeConverter.GetTypeFromName(type) == typeof(TType)) - { - return true; - } - - return false; - } - } - - public new class UxmlTraits : BaseField.UxmlTraits - { - UxmlStringAttributeDescription m_TypeOf = new UxmlStringAttributeDescription { name = "value-type", obsoleteNames = new[] {"typeOf"}, use = UxmlAttributeDescription.Use.Required }; - UxmlStringAttributeDescription m_Value = new UxmlStringAttributeDescription { name = "value" }; - UxmlStringAttributeDescription m_Label = new UxmlStringAttributeDescription { name = "label" }; - - public UxmlTraits() - { - m_TypeOf.restriction = new UxmlEnumeration - { - values = Enum.GetValues(typeof(DataType)).Cast() - .Where(dt => dt != DataType.Unsupported) - .Select(dt => dt.ToString()).ToList() - }; - } - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var initValue = m_Value.GetValueFromBag(bag, cc); - var text = m_Label.GetValueFromBag(bag, cc); - ((PropertyControl)ve).SetValueWithoutNotify(((PropertyControl)ve).StringToValue(initValue)); - ((PropertyControl)ve).label = text; - } - - public string GetValueType(IUxmlAttributes bag, CreationContext cc) - { - return m_TypeOf.GetValueFromBag(bag, cc); - } - } - - enum DataType - { - Long, - Double, - Int, - Float, - String, - Unsupported - } - - private Func GetValueDelegate; - private Action SetValueDelegate; - - private Label m_Label; - private BaseField m_Field; - - public PropertyControl() - : this("") - {} - - public PropertyControl(string labelText) - { - Init("", labelText); - } - - private void Init(string initialValue, string labelText) - { - CacheType(); - - AddToClassList("propertyControl"); - m_Label = new Label(labelText); - - Add(m_Label); - CreateControl(); - SetValueWithoutNotify(StringToValue(initialValue)); - - EnableMouseDraggerForNumericType(); - } - - DataType dataType { get; set; } - - private void CacheType() - { - var ttype = typeof(TType); - if (ttype == typeof(long)) - dataType = DataType.Long; - else if (ttype == typeof(int)) - dataType = DataType.Int; - else if (ttype == typeof(float)) - dataType = DataType.Float; - else if (ttype == typeof(double)) - dataType = DataType.Double; - else if (ttype == typeof(string)) - dataType = DataType.String; - else - { - dataType = DataType.Unsupported; - throw new NotSupportedException($"Unsupported type for PropertyControl {ttype}"); - } - } - - private void EnableMouseDraggerForNumericType() - { - switch (dataType) - { - case DataType.Long: - AddLabelDragger(); - break; - case DataType.Int: - AddLabelDragger(); - break; - case DataType.Float: - AddLabelDragger(); - break; - case DataType.Double: - AddLabelDragger(); - break; - default: - break; - } - } - - private void AddLabelDragger() - { - var dragger = new FieldMouseDragger((IValueField)m_Field); - dragger.SetDragZone(m_Label); - - m_Label.AddToClassList("propertyControlDragger"); - } - - private static TTo ConvertType(TFrom value) - { - return (TTo)Convert.ChangeType(value, typeof(TTo)); - } - - private void CreateControl() where TControlType : BaseField, new() - { - var c = new TControlType(); - GetValueDelegate = () => ConvertType(c.value); - SetValueDelegate = (x) => c.value = ConvertType(x); - m_Field = c as BaseField; - } - - private void CreateControl() - { - switch (dataType) - { - case DataType.Long: - CreateControl(); - break; - case DataType.Int: - CreateControl(); - break; - case DataType.Float: - CreateControl(); - break; - case DataType.Double: - CreateControl(); - break; - case DataType.String: - CreateControl(); - break; - } - - if (m_Field == null) - throw new NotSupportedException($"Unsupported type attribute: {typeof(TType)}"); - - m_Field.AddToClassList("propertyControlControl"); - m_Field.OnValueChanged(OnFieldValueChanged); - Add(m_Field); - } - - public string label - { - get { return m_Label.text; } - set { m_Label.text = value; } - } - - private TType StringToValue(string str) - { - switch (dataType) - { - case DataType.Long: - case DataType.Int: - { - long v; - EditorGUI.StringToLong(str, out v); - return ConvertType(v); - } - case DataType.Double: - case DataType.Float: - { - double v; - EditorGUI.StringToDouble(str, out v); - return ConvertType(v); - } - } - return ConvertType(str); - } - - private void OnFieldValueChanged(ChangeEvent evt) - { - using (ChangeEvent newEvent = ChangeEvent.GetPooled(evt.previousValue, evt.newValue)) - { - newEvent.target = this; - SendEvent(newEvent); - } - } - - public override void SetValueWithoutNotify(TType newValue) - { - m_Field.SetValueWithoutNotify(newValue); - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(TType newValue) - { - value = newValue; - } - - public override TType value - { - get { return GetValueDelegate(); } - set { SetValueDelegate(value); } - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - // Delegate focus to the control - if (evt.GetEventTypeId() == FocusEvent.TypeId()) - m_Field.Focus(); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/TagField.cs b/Editor/Mono/UIElements/Experimental/Controls/TagField.cs deleted file mode 100644 index 85e5c19b64..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/TagField.cs +++ /dev/null @@ -1,111 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEditorInternal; - -namespace UnityEditor.Experimental.UIElements -{ - public class TagField : PopupField - { - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : PopupField.UxmlTraits - { - UxmlStringAttributeDescription m_Value = new UxmlStringAttributeDescription { name = "value" }; - - public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) - { - base.Init(ve, bag, cc); - - var tagField = (TagField)ve; - tagField.SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc)); - } - } - - internal override string GetValueToDisplay() - { - return m_Value; - } - - public override string value - { - get { return base.value; } - set - { - // Allow the setting of value outside of Tags, but do nothing with them... - if (m_Choices.Contains(value)) - { - base.value = value; - } - } - } - - public override void SetValueWithoutNotify(string newValue) - { - // Allow the setting of value outside of Tags, but do nothing with them... - if (m_Choices.Contains(newValue)) - { - base.SetValueWithoutNotify(newValue); - } - } - - public override Func formatSelectedValueCallback - { - get { return null; } - set - { - Debug.LogWarning(L10n.Tr("TagField doesn't support the formatting of the selected value.")); - m_FormatSelectedValueCallback = null; - } - } - - public override Func formatListItemCallback - { - get { return null; } - set - { - Debug.LogWarning(L10n.Tr("TagField doesn't support the formatting of the list items.")); - m_FormatListItemCallback = null; - } - } - - static List InitializeTags() - { - return new List(InternalEditorUtility.tags); - } - - public TagField() : base(InitializeTags()) {} - - public TagField(string defaultValue) : this() - { - SetValueWithoutNotify(defaultValue); - } - - internal override void AddMenuItems(GenericMenu menu) - { - choices = InitializeTags(); - foreach (var menuItem in choices) - { - var isSelected = (menuItem == value); - menu.AddItem(new GUIContent(menuItem), isSelected, () => ChangeValueFromMenu(menuItem)); - } - menu.AddItem(new GUIContent(""), false, null); // This is a separator... - menu.AddItem(new GUIContent(L10n.Tr("Add Tag...")), false, OpenTagInspector); - } - - void ChangeValueFromMenu(string menuItem) - { - value = menuItem; - } - - static void OpenTagInspector() - { - TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.Tags); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Controls/TextValueField.cs b/Editor/Mono/UIElements/Experimental/Controls/TextValueField.cs deleted file mode 100644 index b8ec857cfc..0000000000 --- a/Editor/Mono/UIElements/Experimental/Controls/TextValueField.cs +++ /dev/null @@ -1,153 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public enum DeltaSpeed - { - Fast, - Normal, - Slow - } - - public interface IValueField - { - T value { get; set; } - - void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, T startValue); - } - - // Implements a control with a value of type T backed by a text. - public abstract class TextValueField : TextInputFieldBase, IValueField - { - public new class UxmlTraits : TextInputFieldBase.UxmlTraits {} - - protected TextValueField(int maxLength) - : base(maxLength, Char.MinValue) - { - m_UpdateTextFromValue = true; - SetValueWithoutNotify(default(T)); - } - - private bool m_UpdateTextFromValue; - - public override T value - { - get { return base.value; } - set - { - base.value = value; - if (m_UpdateTextFromValue) - text = ValueToString(m_Value); - } - } - - private void UpdateValueFromText() - { - T newValue = StringToValue(text); - value = newValue; - } - - public override void SetValueWithoutNotify(T newValue) - { - base.SetValueWithoutNotify(newValue); - if (!isDelayed && m_UpdateTextFromValue) - { - // Value is the same but the text might not be in sync - // In the case of an expression like 2+2, the text might not be equal to the result - text = ValueToString(m_Value); - } - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public override void SetValueAndNotify(T newValue) - { - if (!EqualityComparer.Default.Equals(value, newValue)) - { - value = newValue; - } - } - - internal override bool AcceptCharacter(char c) - { - return c != 0 && allowedCharacters.IndexOf(c) != -1; - } - - protected abstract string allowedCharacters { get; } - - public string formatString { get; set; } - - public abstract void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, T startValue); - - protected abstract string ValueToString(T value); - - protected abstract T StringToValue(string str); - - protected internal override void ExecuteDefaultActionAtTarget(EventBase evt) - { - base.ExecuteDefaultActionAtTarget(evt); - - bool hasChanged = false; - if (evt.GetEventTypeId() == KeyDownEvent.TypeId()) - { - KeyDownEvent kde = evt as KeyDownEvent; - if (kde.character == '\n') - { - UpdateValueFromText(); - } - else - { - hasChanged = true; - } - } - else if (evt.GetEventTypeId() == ExecuteCommandEvent.TypeId()) - { - ExecuteCommandEvent commandEvt = evt as ExecuteCommandEvent; - string cmdName = commandEvt.commandName; - if (cmdName == EventCommandNames.Paste || cmdName == EventCommandNames.Cut) - { - hasChanged = true; - } - } - - if (!isDelayed && hasChanged) - { - // Prevent text from changing when the value change - // This allow expression (2+2) or string like 00123 to remain as typed in the TextField until enter is pressed - m_UpdateTextFromValue = false; - try - { - UpdateValueFromText(); - } - finally - { - m_UpdateTextFromValue = true; - } - } - } - - protected internal override void ExecuteDefaultAction(EventBase evt) - { - base.ExecuteDefaultAction(evt); - - if (evt.GetEventTypeId() == BlurEvent.TypeId()) - { - if (string.IsNullOrEmpty(text)) - { - // Make sure that empty field gets the default value - value = default(T); - } - else - { - UpdateValueFromText(); - } - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/EditorContextualMenuManager.cs b/Editor/Mono/UIElements/Experimental/EditorContextualMenuManager.cs deleted file mode 100644 index 599abe328d..0000000000 --- a/Editor/Mono/UIElements/Experimental/EditorContextualMenuManager.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - class EditorContextualMenuManager : ContextualMenuManager - { - public override void DisplayMenuIfEventMatches(EventBase evt, IEventHandler eventHandler) - { - if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer) - { - if (evt.GetEventTypeId() == MouseDownEvent.TypeId()) - { - MouseDownEvent e = evt as MouseDownEvent; - - if (e.button == (int)MouseButton.RightMouse || - (e.button == (int)MouseButton.LeftMouse && e.modifiers == EventModifiers.Control)) - { - DisplayMenu(evt, eventHandler); - evt.StopPropagation(); - return; - } - } - } - else - { - if (evt.GetEventTypeId() == MouseUpEvent.TypeId()) - { - MouseUpEvent e = evt as MouseUpEvent; - if (e.button == (int)MouseButton.RightMouse) - { - DisplayMenu(evt, eventHandler); - evt.StopPropagation(); - return; - } - } - } - - if (evt.GetEventTypeId() == KeyUpEvent.TypeId()) - { - KeyUpEvent e = evt as KeyUpEvent; - if (e.keyCode == KeyCode.Menu) - { - DisplayMenu(evt, eventHandler); - evt.StopPropagation(); - } - } - } - - protected internal override void DoDisplayMenu(DropdownMenu menu, EventBase triggerEvent) - { - menu.DoDisplayEditorMenu(triggerEvent); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/EditorCursor.cs b/Editor/Mono/UIElements/Experimental/EditorCursor.cs deleted file mode 100644 index b01eb0916d..0000000000 --- a/Editor/Mono/UIElements/Experimental/EditorCursor.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - internal class EditorCursorManager : ICursorManager - { - public void SetCursor(CursorStyle cursor) - { - if (GUIView.current == null) - { - // Cannot set the cursor if the current view is null. - return; - } - - if (cursor.texture != null) - { - EditorGUIUtility.SetCurrentViewCursor(cursor.texture, cursor.hotspot, MouseCursor.CustomCursor); - } - else - { - EditorGUIUtility.SetCurrentViewCursor(null, Vector2.zero, (MouseCursor)cursor.defaultCursorId); - } - } - - public void ResetCursor() - { - if (GUIView.current == null) - { - // Cannot clear the cursor if the current view is null. - return; - } - EditorGUIUtility.ClearCurrentViewCursor(); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/EditorMenuExtensions.cs b/Editor/Mono/UIElements/Experimental/EditorMenuExtensions.cs deleted file mode 100644 index af126c40e7..0000000000 --- a/Editor/Mono/UIElements/Experimental/EditorMenuExtensions.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - static class EditorMenuExtensions - { - static GenericMenu PrepareMenu(DropdownMenu menu, EventBase triggerEvent) - { - menu.PrepareForDisplay(triggerEvent); - - var genericMenu = new GenericMenu(); - foreach (var item in menu.MenuItems()) - { - var action = item as DropdownMenu.MenuAction; - if (action != null) - { - if ((action.status & DropdownMenu.MenuAction.StatusFlags.Hidden) == DropdownMenu.MenuAction.StatusFlags.Hidden) - { - continue; - } - - bool isChecked = (action.status & DropdownMenu.MenuAction.StatusFlags.Checked) == DropdownMenu.MenuAction.StatusFlags.Checked; - - if ((action.status & DropdownMenu.MenuAction.StatusFlags.Disabled) == DropdownMenu.MenuAction.StatusFlags.Disabled) - { - genericMenu.AddDisabledItem(new GUIContent(action.name)); - } - else - { - genericMenu.AddItem(new GUIContent(action.name), isChecked, () => - { - action.Execute(); - }); - } - } - else - { - var separator = item as DropdownMenu.Separator; - if (separator != null) - { - genericMenu.AddSeparator(separator.subMenuPath); - } - } - } - - return genericMenu; - } - - public static void DoDisplayEditorMenu(this DropdownMenu menu, Vector2 position) - { - PrepareMenu(menu, null).DropDown(new Rect(position, Vector2.zero)); - } - - public static void DoDisplayEditorMenu(this DropdownMenu menu, EventBase triggerEvent) - { - GenericMenu genericMenu = PrepareMenu(menu, triggerEvent); - - Vector2 position = Vector2.zero; - if (triggerEvent is IMouseEvent) - { - position = ((IMouseEvent)triggerEvent).mousePosition; - } - else if (triggerEvent.target is VisualElement) - { - position = ((VisualElement)triggerEvent.target).layout.center; - } - - genericMenu.DropDown(new Rect(position, Vector2.zero)); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/EditorWindowPersistentViewData.cs b/Editor/Mono/UIElements/Experimental/EditorWindowPersistentViewData.cs deleted file mode 100644 index 91542ac827..0000000000 --- a/Editor/Mono/UIElements/Experimental/EditorWindowPersistentViewData.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using UnityEditor; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using SerializableJsonDictionary = UnityEditor.Experimental.UIElements.SerializableJsonDictionary; - -namespace UnityEditor.Experimental.UIElements -{ - [LibraryFolderPath("UIElements/EditorWindows")] - internal class EditorWindowPersistentViewData : ScriptableSingletonDictionary< - EditorWindowPersistentViewData, - SerializableJsonDictionary> - { - public static SerializableJsonDictionary GetEditorData(EditorWindow window) - { - string editorPrefFileName = window.GetType().ToString(); - return instance[editorPrefFileName]; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/FieldMouseDragger.cs b/Editor/Mono/UIElements/Experimental/FieldMouseDragger.cs deleted file mode 100644 index e5776aac28..0000000000 --- a/Editor/Mono/UIElements/Experimental/FieldMouseDragger.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class FieldMouseDragger - { - public FieldMouseDragger(IValueField drivenField) - { - m_DrivenField = drivenField; - m_DragElement = null; - m_DragHotZone = new Rect(0, 0, -1, -1); - dragging = false; - } - - IValueField m_DrivenField; - VisualElement m_DragElement; - Rect m_DragHotZone; - - public bool dragging; - public T startValue; - - public void SetDragZone(VisualElement dragElement) - { - SetDragZone(dragElement, new Rect(0, 0, -1, -1)); - } - - public void SetDragZone(VisualElement dragElement, Rect hotZone) - { - if (m_DragElement != null) - { - m_DragElement.UnregisterCallback(UpdateValueOnMouseDown); - m_DragElement.UnregisterCallback(UpdateValueOnMouseMove); - m_DragElement.UnregisterCallback(UpdateValueOnMouseUp); - m_DragElement.UnregisterCallback(UpdateValueOnKeyDown); - } - - m_DragElement = dragElement; - m_DragHotZone = hotZone; - - if (m_DragElement != null) - { - dragging = false; - m_DragElement.RegisterCallback(UpdateValueOnMouseDown); - m_DragElement.RegisterCallback(UpdateValueOnMouseMove); - m_DragElement.RegisterCallback(UpdateValueOnMouseUp); - m_DragElement.RegisterCallback(UpdateValueOnKeyDown); - } - } - - void UpdateValueOnMouseDown(MouseDownEvent evt) - { - if (evt.button == 0 && (m_DragHotZone.width < 0 || m_DragHotZone.height < 0 || m_DragHotZone.Contains(m_DragElement.WorldToLocal(evt.mousePosition)))) - { - m_DragElement.CaptureMouse(); - - // Make sure no other elements can capture the mouse! - evt.StopPropagation(); - - dragging = true; - startValue = m_DrivenField.value; - - EditorGUIUtility.SetWantsMouseJumping(1); - } - } - - void UpdateValueOnMouseMove(MouseMoveEvent evt) - { - if (dragging) - { - DeltaSpeed s = evt.shiftKey ? DeltaSpeed.Fast : (evt.altKey ? DeltaSpeed.Slow : DeltaSpeed.Normal); - m_DrivenField.ApplyInputDeviceDelta(evt.mouseDelta, s, startValue); - } - } - - void UpdateValueOnMouseUp(MouseUpEvent evt) - { - if (dragging) - { - dragging = false; - MouseCaptureController.ReleaseMouse(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - } - - void UpdateValueOnKeyDown(KeyDownEvent evt) - { - if (dragging && evt.keyCode == KeyCode.Escape) - { - dragging = false; - m_DrivenField.value = startValue; - MouseCaptureController.ReleaseMouse(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/PanelDebug.cs b/Editor/Mono/UIElements/Experimental/PanelDebug.cs deleted file mode 100644 index 64a7ad2615..0000000000 --- a/Editor/Mono/UIElements/Experimental/PanelDebug.cs +++ /dev/null @@ -1,183 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - internal class PanelDebug : IPanelDebug - { - private HashSet m_Debuggers = new HashSet(); - private List m_RepaintDatas = new List(); - private IPanel m_Panel; - private bool m_IsShowingOverlay = false; - - public bool showOverlay - { - get - { - foreach (var debugger in m_Debuggers) - { - if (debugger.showOverlay) - return true; - } - - return false; - } - } - - public uint highlightedElement { get; private set; } = 0; - - public PanelDebug(IPanel panel) - { - m_Panel = panel; - } - - public void AttachDebugger(IPanelDebugger debugger) - { - if (m_Debuggers.Add(debugger)) - { - debugger.panelDebug = this; - m_Panel.visualTree.MarkDirtyRepaint(); - } - } - - public void DetachDebugger(IPanelDebugger debugger) - { - debugger.panelDebug = null; - m_Debuggers.Remove(debugger); - m_Panel.visualTree.MarkDirtyRepaint(); - } - - public void Refresh() - { - if (showOverlay) - { - RecordRepaintData(m_Panel.visualTree); - DrawRepaintData(); - m_IsShowingOverlay = true; - } - else if (m_IsShowingOverlay) - { - // Clear the overlay - m_IsShowingOverlay = false; - m_Panel.visualTree.MarkDirtyRepaint(); - } - - foreach (var debugger in m_Debuggers) - { - debugger.Refresh(); - } - } - - public bool InterceptEvents(Event ev) - { - bool intercepted = false; - foreach (var debugger in m_Debuggers) - { - intercepted |= debugger.InterceptEvents(ev); - } - - return intercepted; - } - - public void SetHighlightElement(VisualElement ve) - { - var controlId = ve != null ? ve.controlid : 0; - if (highlightedElement != controlId) - { - highlightedElement = controlId; - m_Panel.visualTree.MarkDirtyRepaint(); - } - } - - private void RecordRepaintData(VisualElement ve) - { - m_RepaintDatas.Add(new RepaintData(ve.controlid, - ve.worldBound, - Color.HSVToRGB(ve.controlid * 11 % 32 / 32.0f, .6f, 1.0f))); - - for (int i = 0; i < ve.shadow.childCount; i++) - { - var child = ve.shadow[i]; - RecordRepaintData(child); - } - } - - public void DrawRepaintData() - { - RepaintData onTopElement = null; - foreach (var repaintData in m_RepaintDatas) - { - var color = repaintData.color; - if (highlightedElement != 0) - if (highlightedElement != repaintData.controlId) - { - color = Color.gray; - } - else - { - onTopElement = repaintData; - continue; - } - DrawRect(repaintData.contentRect, color); - } - - m_RepaintDatas.Clear(); - if (onTopElement != null) - DrawRect(onTopElement.contentRect, onTopElement.color); - } - - public static void DrawRect(Rect sp, Color c) - { - sp.xMin++; - sp.xMax--; - sp.yMin++; - sp.yMax--; - - HandleUtility.ApplyWireMaterial(); - GL.PushMatrix(); - GL.Begin(GL.LINES); - - GL.Color(c); - GL.Vertex3(sp.xMin, sp.yMin, 0); - GL.Color(c); - GL.Vertex3(sp.xMax, sp.yMin, 0); - - GL.Color(c); - GL.Vertex3(sp.xMax, sp.yMin, 0); - GL.Color(c); - GL.Vertex3(sp.xMax, sp.yMax, 0); - - GL.Color(c); - GL.Vertex3(sp.xMax, sp.yMax, 0); - GL.Color(c); - GL.Vertex3(sp.xMin, sp.yMax, 0); - - GL.Color(c); - GL.Vertex3(sp.xMin, sp.yMax, 0); - GL.Color(c); - GL.Vertex3(sp.xMin, sp.yMin, 0); - GL.End(); - GL.PopMatrix(); - } - - private class RepaintData - { - public readonly Color color; - public readonly Rect contentRect; - public readonly uint controlId; - - public RepaintData(uint controlId, Rect contentRect, Color color) - { - this.contentRect = contentRect; - this.color = color; - this.controlId = controlId; - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/SerializableJsonDictionary.cs b/Editor/Mono/UIElements/Experimental/SerializableJsonDictionary.cs deleted file mode 100644 index d3ba806c25..0000000000 --- a/Editor/Mono/UIElements/Experimental/SerializableJsonDictionary.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -namespace UnityEditor.Experimental.UIElements -{ - internal class SerializableJsonDictionary : UnityEditor.UIElements.SerializableJsonDictionary - { - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/IToolbarMenuElement.cs b/Editor/Mono/UIElements/Experimental/Toolbar/IToolbarMenuElement.cs deleted file mode 100644 index 02229cf103..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/IToolbarMenuElement.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System.Linq; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public interface IToolbarMenuElement - { - DropdownMenu menu { get; } - } - - public static class ToolbarMenuElementExtensions - { - public static void ShowMenu(this IToolbarMenuElement tbe) - { - if (!tbe.menu.MenuItems().Any()) - return; - - var ve = tbe as VisualElement; - if (ve == null) - return; - - Vector2 pos = new Vector2(ve.layout.xMin, ve.layout.yMax); - pos = ve.parent.LocalToWorld(pos); - - tbe.menu.DoDisplayEditorMenu(pos); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/Toolbar.cs b/Editor/Mono/UIElements/Experimental/Toolbar/Toolbar.cs deleted file mode 100644 index acc41fb541..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/Toolbar.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class Toolbar : VisualElement - { - public new class UxmlFactory : UxmlFactory {} - - internal static void SetToolbarStyleSheet(VisualElement ve) - { - ve.AddStyleSheetPath("StyleSheets/ToolbarCommon.uss"); - ve.AddStyleSheetPath("StyleSheets/Toolbar" + (EditorGUIUtility.isProSkin ? "Dark" : "Light") + ".uss"); - } - - public Toolbar() - { - SetToolbarStyleSheet(this); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarButton.cs b/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarButton.cs deleted file mode 100644 index 4ecb87e6aa..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarButton.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class ToolbarButton : Button - { - public new class UxmlFactory : UxmlFactory {} - public new class UxmlTraits : Button.UxmlTraits {} - - const string k_ClassName = "toolbarButton"; - public ToolbarButton(Action clickEvent) : - base(clickEvent) - { - Toolbar.SetToolbarStyleSheet(this); - AddToClassList(k_ClassName); - } - - public ToolbarButton() : this(() => {}) - { - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarMenu.cs b/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarMenu.cs deleted file mode 100644 index 40f83c6f23..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarMenu.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public abstract class ToolbarMenuBase : TextElement, IToolbarMenuElement - { - Clickable clickable; - - public DropdownMenu menu { get; } - - protected ToolbarMenuBase(string classList) : - this() - { - Toolbar.SetToolbarStyleSheet(this); - AddToClassList(classList); - } - - ToolbarMenuBase() - { - clickable = new Clickable(this.ShowMenu); - this.AddManipulator(clickable); - menu = new DropdownMenu(); - } - } - - public class ToolbarMenu : ToolbarMenuBase - { - public new class UxmlFactory : UxmlFactory {} - public new class UxmlTraits : TextElement.UxmlTraits {} - - const string k_ClassName = "toolbarMenu"; - public ToolbarMenu() : - base(k_ClassName) - { - } - } - - public class ToolbarPopup : ToolbarMenuBase - { - public new class UxmlFactory : UxmlFactory {} - public new class UxmlTraits : TextElement.UxmlTraits {} - - const string k_ClassName = "toolbarPopup"; - public ToolbarPopup() : - base(k_ClassName) - { - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarPopupSearchField.cs b/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarPopupSearchField.cs deleted file mode 100644 index 5dc36e7c9b..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarPopupSearchField.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class ToolbarPopupSearchField : ToolbarSearchField, IToolbarMenuElement - { - public new class UxmlFactory : UxmlFactory {} - - const string k_SearchButtonClassName = "toolbarSearchFieldPopup"; - - public DropdownMenu menu { get; } - - public ToolbarPopupSearchField() : - base(k_SearchButtonClassName) - { - menu = new DropdownMenu(); - m_SearchButton.clickable.clicked += this.ShowMenu; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSearchField.cs b/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSearchField.cs deleted file mode 100644 index 2ed54290a1..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSearchField.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class ToolbarSearchField : VisualElement, INotifyValueChanged - { - public new class UxmlFactory : UxmlFactory {} - - const string k_ClassName = "toolbarSearchField"; - - const string k_SearchButtonClassName = "toolbarSearchFieldButton"; - - const string k_EmptyEndClassName = "toolbarSearchFieldEnd"; - const string k_CancelButtonEndClassName = "toolbarSearchFieldCancelButton"; - - protected Button m_SearchButton; - Button m_CancelButton; - TextField m_TextField; - - string m_CurrentText; - - public string value - { - get - { - return m_CurrentText; - } - set - { - if (m_CurrentText == value) - return; - - if (panel != null) - { - using (ChangeEvent evt = ChangeEvent.GetPooled(m_CurrentText, value)) - { - evt.target = this; - SetValueWithoutNotify(value); - SendEvent(evt); - } - } - else - { - SetValueWithoutNotify(value); - } - } - } - - public ToolbarSearchField() : - this(k_SearchButtonClassName) - { - Toolbar.SetToolbarStyleSheet(this); - } - - protected ToolbarSearchField(string searchButtonStyleClassName) - { - m_CurrentText = String.Empty; - - AddToClassList(k_ClassName); - - m_SearchButton = new Button(() => {}); - m_SearchButton.AddToClassList(searchButtonStyleClassName); - shadow.Add(m_SearchButton); - - m_TextField = new TextField(); - m_SearchButton.shadow.Add(m_TextField); - m_TextField.OnValueChanged(OnTextChanged); - m_TextField.RegisterCallback(OnTextFieldKeyDown); - - m_CancelButton = new Button(() => {}); - m_CancelButton.AddToClassList(k_EmptyEndClassName); - shadow.Add(m_CancelButton); - } - - void OnTextChanged(ChangeEvent change) - { - value = change.newValue; - } - - void ClearTextField() - { - value = String.Empty; - } - - void OnTextFieldKeyDown(KeyDownEvent evt) - { - if (evt.keyCode == KeyCode.Escape) - ClearTextField(); - } - - void OnCancelButtonClick() - { - ClearTextField(); - } - - public void SetValueWithoutNotify(string newValue) - { - if (m_CurrentText == newValue) - return; - - if (string.IsNullOrEmpty(m_CurrentText) && !string.IsNullOrEmpty(newValue)) - { - m_CancelButton.RemoveFromClassList(k_EmptyEndClassName); - m_CancelButton.AddToClassList(k_CancelButtonEndClassName); - m_CancelButton.clickable.clicked += OnCancelButtonClick; - } - else if (!string.IsNullOrEmpty(m_CurrentText) && string.IsNullOrEmpty(newValue)) - { - m_CancelButton.AddToClassList(k_EmptyEndClassName); - m_CancelButton.RemoveFromClassList(k_CancelButtonEndClassName); - m_CancelButton.clickable.clicked -= OnCancelButtonClick; - } - - m_CurrentText = newValue; - m_TextField.value = m_CurrentText; - } - - [Obsolete("This method is replaced by simply using this.value. The default behaviour has been changed to notify when changed. If the behaviour is not to be notified, SetValueWithoutNotify() must be used.", false)] - public void SetValueAndNotify(string newValue) - { - } - - public void OnValueChanged(EventCallback> callback) - { - RegisterCallback(callback); - } - - public void RemoveOnValueChanged(EventCallback> callback) - { - UnregisterCallback(callback); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSpacer.cs b/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSpacer.cs deleted file mode 100644 index 53c49176b8..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarSpacer.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class ToolbarSpacer : VisualElement - { - public new class UxmlFactory : UxmlFactory {} - - const string k_ClassName = "toolbarSpacer"; - public ToolbarSpacer() - { - Toolbar.SetToolbarStyleSheet(this); - AddToClassList(k_ClassName); - } - } - - public class ToolbarFlexSpacer : ToolbarSpacer - { - public new class UxmlFactory : UxmlFactory {} - - const string k_ClassName = "toolbarFlexSpacer"; - public ToolbarFlexSpacer() - { - ClearClassList(); - AddToClassList(k_ClassName); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarToggle.cs b/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarToggle.cs deleted file mode 100644 index b112a7cce0..0000000000 --- a/Editor/Mono/UIElements/Experimental/Toolbar/ToolbarToggle.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - public class ToolbarToggle : Toggle - { - public new class UxmlFactory : UxmlFactory {} - public new class UxmlTraits : Toggle.UxmlTraits {} - - const string k_ClassName = "toolbarButton"; - public ToolbarToggle() - { - Toolbar.SetToolbarStyleSheet(this); - AddToClassList(k_ClassName); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/Tooltip.cs b/Editor/Mono/UIElements/Experimental/Tooltip.cs deleted file mode 100644 index 3aa5dc1da0..0000000000 --- a/Editor/Mono/UIElements/Experimental/Tooltip.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Experimental.UIElements.StyleEnums; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEditor.Experimental.UIElements -{ - static class Tooltip - { - internal static void SetTooltip(float mouseX, float mouseY) - { - //mouseX,mouseY are screen relative. - GUIView view = GUIView.mouseOverView; - if (view != null && view.uieMode == GUIView.UIElementsMode.Experimental && view.experimentalVisualTree != null && view.experimentalVisualTree.panel != null) - { - var panel = view.experimentalVisualTree.panel; - - // Pick expect view relative coordinates. - VisualElement target = panel.Pick(new Vector2(mouseX, mouseY) - view.screenPosition.position); - if (target != null) - { - using (var tooltipEvent = TooltipEvent.GetPooled()) - { - tooltipEvent.target = target; - tooltipEvent.tooltip = null; - tooltipEvent.rect = Rect.zero; - target.SendEvent(tooltipEvent); - - if (!string.IsNullOrEmpty(tooltipEvent.tooltip) && !tooltipEvent.isDefaultPrevented) - { - Rect rect = tooltipEvent.rect; - rect.position += view.screenPosition.position; //SetMouseTooltip expects Screen relative coordinates. - - GUIStyle.SetMouseTooltip(tooltipEvent.tooltip, rect); - } - } - } - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/UIElementsEditorUtility.cs b/Editor/Mono/UIElements/Experimental/UIElementsEditorUtility.cs deleted file mode 100644 index 4d92682374..0000000000 --- a/Editor/Mono/UIElements/Experimental/UIElementsEditorUtility.cs +++ /dev/null @@ -1,60 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Experimental.UIElements.StyleSheets; - -namespace UnityEditor.Experimental.UIElements -{ - public static class UIElementsEditorUtility - { - internal static readonly string s_DefaultCommonStyleSheetPath = "StyleSheets/Experimental/DefaultCommon.uss"; - internal static readonly string s_DefaultCommonDarkStyleSheetPath = "StyleSheets/Experimental/DefaultCommonDark.uss"; - internal static readonly string s_DefaultCommonLightStyleSheetPath = "StyleSheets/Experimental/DefaultCommonLight.uss"; - - public static CursorStyle CreateDefaultCursorStyle(MouseCursor mouseCursor) - { - return new CursorStyle() { texture = null, hotspot = Vector2.zero, defaultCursorId = (int)mouseCursor }; - } - - internal static int GetCursorId(UnityEngine.UIElements.StyleSheet sheet, UnityEngine.UIElements.StyleValueHandle handle) - { - return StyleSheetCache.GetEnumValue(sheet, handle); - } - - internal static void AddDefaultEditorStyleSheets(VisualElement p) - { - if (p.styleSheets == null) - { - p.AddStyleSheetPath(s_DefaultCommonStyleSheetPath); - if (EditorGUIUtility.isProSkin) - { - p.AddStyleSheetPath(s_DefaultCommonDarkStyleSheetPath); - } - else - { - p.AddStyleSheetPath(s_DefaultCommonLightStyleSheetPath); - } - } - } - - internal static void ForceDarkStyleSheet(VisualElement ele) - { - if (!EditorGUIUtility.isProSkin) - { - var e = ele; - while (e != null) - { - if (e.HasStyleSheetPath(s_DefaultCommonLightStyleSheetPath)) - { - e.ReplaceStyleSheetPath(s_DefaultCommonLightStyleSheetPath, s_DefaultCommonDarkStyleSheetPath); - break; - } - e = e.parent; - } - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/UXMLEditorFactories.cs b/Editor/Mono/UIElements/Experimental/UXMLEditorFactories.cs deleted file mode 100644 index 84295d7209..0000000000 --- a/Editor/Mono/UIElements/Experimental/UXMLEditorFactories.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - internal class UXMLEditorFactories - { - private static bool s_Registered; - - internal static void RegisterAll() - { - if (s_Registered) - return; - - s_Registered = true; - - IUxmlFactory[] factories = - { - // Primitives - new TextElement.UxmlFactory(), - new FloatField.UxmlFactory(), - new DoubleField.UxmlFactory(), - new IntegerField.UxmlFactory(), - new LongField.UxmlFactory(), - new CurveField.UxmlFactory(), - new ObjectField.UxmlFactory(), - new ColorField.UxmlFactory(), - new EnumField.UxmlFactory(), - new MaskField.UxmlFactory(), - new LayerMaskField.UxmlFactory(), - new LayerField.UxmlFactory(), - new TagField.UxmlFactory(), - new GradientField.UxmlFactory(), - - // Compounds - new RectField.UxmlFactory(), - new Vector2Field.UxmlFactory(), - new Vector3Field.UxmlFactory(), - new Vector4Field.UxmlFactory(), - new BoundsField.UxmlFactory(), - new PropertyControl.UxmlFactory(), - new PropertyControl.UxmlFactory(), - new PropertyControl.UxmlFactory(), - new PropertyControl.UxmlFactory(), - new PropertyControl.UxmlFactory(), - - new RectIntField.UxmlFactory(), - new Vector2IntField.UxmlFactory(), - new Vector3IntField.UxmlFactory(), - new BoundsIntField.UxmlFactory(), - new VisualSplitter.UxmlFactory(), - // Toolbar - new Toolbar.UxmlFactory(), - new ToolbarButton.UxmlFactory(), - new ToolbarToggle.UxmlFactory(), - new ToolbarSpacer.UxmlFactory(), - new ToolbarFlexSpacer.UxmlFactory(), - new ToolbarMenu.UxmlFactory(), - new ToolbarPopup.UxmlFactory(), - new ToolbarSearchField.UxmlFactory(), - new ToolbarPopupSearchField.UxmlFactory(), - // Bound - //new PropertyField.UxmlFactory(), - //new InspectorElement.UxmlFactory(), - }; - - foreach (IUxmlFactory factory in factories) - { - VisualElementFactoryRegistry.RegisterFactory(factory); - } - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/UXMLSchemaGenerator.cs b/Editor/Mono/UIElements/Experimental/UXMLSchemaGenerator.cs deleted file mode 100644 index 5f3cebe70a..0000000000 --- a/Editor/Mono/UIElements/Experimental/UXMLSchemaGenerator.cs +++ /dev/null @@ -1,590 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Xml; -using System.Xml.Schema; -using UnityEditor.ProjectWindowCallback; -using UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public class UxmlNamespacePrefixAttribute : Attribute - { - public string ns { get; } - public string prefix { get; } - - public UxmlNamespacePrefixAttribute(string ns, string prefix) - { - this.ns = ns; - this.prefix = prefix; - } - } - - class UxmlSchemaGenerator - { - // Folder, relative to the project root. - internal const string k_SchemaFolder = "UIElementsSchema"; - - [MenuItem("Assets/Update UIElements Schema", false, 800)] - static void CreateTemplateMenuItem() - { - UpdateSchemaFiles(); - } - - public static void UpdateSchemaFiles() - { - Directory.CreateDirectory(k_SchemaFolder); - using (var it = GenerateSchemaFiles(k_SchemaFolder + "/").GetEnumerator()) - { - while (it.MoveNext()) - { - string fileName = it.Current; - if (it.MoveNext()) - { - string data = it.Current; - var action = ScriptableObject.CreateInstance(); - action.filecontent = data; - - ProjectWindowUtil.EndNameEditAction(action, 0, fileName, null); - Selection.activeObject = EditorUtility.InstanceIDToObject(0); - } - } - } - } - - internal static Dictionary GetNamespacePrefixDictionary() - { - return SchemaInfo.s_NamespacePrefix; - } - - sealed class UTF8StringWriter : StringWriter - { - public override Encoding Encoding - { - get { return Encoding.UTF8; } - } - } - - class SchemaInfo - { - public SchemaInfo(string uxmlNamespace) - { - schema = new XmlSchema(); - schema.ElementFormDefault = XmlSchemaForm.Qualified; - if (uxmlNamespace != String.Empty) - { - schema.TargetNamespace = uxmlNamespace; - } - - namepacePrefix = GetPrefixForNamespace(uxmlNamespace); - - importNamespaces = new HashSet(); - } - - public XmlSchema schema { get; set; } - public string namepacePrefix { get; set; } - public HashSet importNamespaces { get; set; } - - internal static Dictionary s_NamespacePrefix; - - static string GetPrefixForNamespace(string ns) - { - if (s_NamespacePrefix == null) - { - s_NamespacePrefix = new Dictionary(); - - s_NamespacePrefix.Add(String.Empty, "global"); - s_NamespacePrefix.Add(typeof(VisualElement).Namespace, "engine"); - s_NamespacePrefix.Add(typeof(UxmlSchemaGenerator).Namespace, "editor"); - - AppDomain currentDomain = AppDomain.CurrentDomain; - HashSet userAssemblies = new HashSet(ScriptingRuntime.GetAllUserAssemblies()); - foreach (Assembly assembly in currentDomain.GetAssemblies()) - { - if (!userAssemblies.Contains(assembly.GetName().Name + ".dll")) - continue; - - try - { - foreach (object nsPrefixAttributeObject in assembly.GetCustomAttributes(typeof(UxmlNamespacePrefixAttribute), false)) - { - UxmlNamespacePrefixAttribute nsPrefixAttribute = (UxmlNamespacePrefixAttribute)nsPrefixAttributeObject; - s_NamespacePrefix[nsPrefixAttribute.ns] = nsPrefixAttribute.prefix; - } - } - catch (TypeLoadException e) - { - Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", assembly.FullName, e); - } - } - } - - string prefix; - if (s_NamespacePrefix.TryGetValue(ns ?? String.Empty, out prefix)) - { - return prefix; - } - - s_NamespacePrefix[ns] = String.Empty; - return String.Empty; - } - } - - const string k_XmlSchemaNamespace = "http://www.w3.org/2001/XMLSchema"; - const string k_TypeSuffix = "Type"; - - class FactoryProcessingHelper - { - public class AttributeRecord - { - public XmlQualifiedName name { get; set; } - public UxmlAttributeDescription desc { get; set; } - } - - public Dictionary attributeTypeNames; - - HashSet m_KnownTypes; - - public FactoryProcessingHelper() - { - attributeTypeNames = new Dictionary(); - m_KnownTypes = new HashSet(); - } - - public void RegisterElementType(string elementName, string elementNameSpace) - { - m_KnownTypes.Add(new XmlQualifiedName(elementName, elementNameSpace)); - } - - public bool IsKnownElementType(string elementName, string elementNameSpace) - { - return m_KnownTypes.Contains(new XmlQualifiedName(elementName, elementNameSpace)); - } - } - - const string k_SchemaFileExtension = ".xsd"; - const string k_MainSchemaFileName = "UIElements" + k_SchemaFileExtension; - const string k_GlobalNamespaceSchemaFileName = "GlobalNamespace" + k_SchemaFileExtension; - - internal static IEnumerable GenerateSchemaFiles(string baseDir = null) - { - Dictionary schemas = new Dictionary(); - List deferredFactories = new List(); - FactoryProcessingHelper processingData = new FactoryProcessingHelper(); - - if (baseDir == null) - { - baseDir = Application.temporaryCachePath + "/"; - } - VisualElementFactoryRegistry.DiscoverFactories(); - - // Convert the factories into schemas info. - foreach (var factories in VisualElementFactoryRegistry.factories) - { - if (factories.Value.Count == 0) - continue; - - // Only process the first factory, as the other factories define the same element. - IUxmlFactory factory = factories.Value[0]; - if (!ProcessFactory(factory, schemas, processingData)) - { - // Could not process the factory now, because it depends on a yet unprocessed factory. - // Defer its processing. - deferredFactories.Add(factory); - } - } - - List deferredFactoriesCopy; - do - { - deferredFactoriesCopy = new List(deferredFactories); - foreach (var factory in deferredFactoriesCopy) - { - deferredFactories.Remove(factory); - if (!ProcessFactory(factory, schemas, processingData)) - { - // Could not process the factory now, because it depends on a yet unprocessed factory. - // Defer its processing again. - deferredFactories.Add(factory); - } - } - } - while (deferredFactoriesCopy.Count > deferredFactories.Count); - - if (deferredFactories.Count > 0) - { - Debug.Log("Some factories could not be processed because their base type is missing."); - } - - // Compile schemas. - XmlSchemaSet schemaSet = new XmlSchemaSet(); - XmlSchema masterSchema = new XmlSchema(); - masterSchema.ElementFormDefault = XmlSchemaForm.Qualified; - - XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); - nsmgr.AddNamespace("xs", k_XmlSchemaNamespace); - - File.Delete(baseDir + k_MainSchemaFileName); - - foreach (var schema in schemas) - { - if (schema.Value.schema.TargetNamespace != null) - { - nsmgr.AddNamespace(schema.Value.namepacePrefix, schema.Value.schema.TargetNamespace); - - // Import schema into the master schema. - XmlSchemaImport import = new XmlSchemaImport(); - import.Namespace = schema.Value.schema.TargetNamespace; - string schemaLocation = GetFileNameForNamespace(schema.Value.schema.TargetNamespace); - File.Delete(baseDir + schemaLocation); - import.SchemaLocation = schemaLocation; - masterSchema.Includes.Add(import); - } - else - { - XmlSchemaInclude include = new XmlSchemaInclude(); - string schemaLocation = GetFileNameForNamespace(null); - File.Delete(baseDir + schemaLocation); - include.SchemaLocation = schemaLocation; - masterSchema.Includes.Add(include); - } - - // Import referenced schemas into this XSD - foreach (string ns in schema.Value.importNamespaces) - { - if (ns != schema.Value.schema.TargetNamespace && ns != k_XmlSchemaNamespace) - { - XmlSchemaImport import = new XmlSchemaImport(); - import.Namespace = ns; - import.SchemaLocation = GetFileNameForNamespace(ns); - schema.Value.schema.Includes.Add(import); - } - } - - schemaSet.Add(schema.Value.schema); - } - schemaSet.Add(masterSchema); - schemaSet.Compile(); - - // Now generate the schema textual data. - foreach (XmlSchema compiledSchema in schemaSet.Schemas()) - { - string schemaName = compiledSchema.TargetNamespace; - - // Three possible cases: - // TargetNamespace == null and Items.Count == 0: the main schema, that include/import all other schema files - // TargetNamespace == null and Items.Count != 0: the schema file for the global namespace - // TargetNamespace != null: the schema file for TargetNamespace - if (schemaName == null && compiledSchema.Items.Count == 0) - { - schemaName = k_MainSchemaFileName; - } - else - { - schemaName = GetFileNameForNamespace(compiledSchema.TargetNamespace); - } - - yield return baseDir + schemaName; - - StringWriter strWriter = new UTF8StringWriter(); - compiledSchema.Write(strWriter, nsmgr); - yield return strWriter.ToString(); - } - } - - internal static string GetFileNameForNamespace(string ns) - { - return String.IsNullOrEmpty(ns) ? k_GlobalNamespaceSchemaFileName : ns + k_SchemaFileExtension; - } - - static bool ProcessFactory(IUxmlFactory factory, Dictionary schemas, FactoryProcessingHelper processingData) - { - if (factory.substituteForTypeName != null && factory.substituteForTypeName != String.Empty) - { - if (!processingData.IsKnownElementType(factory.substituteForTypeName, factory.substituteForTypeNamespace)) - { - // substituteForTypeName is not yet known. Defer processing to later. - return false; - } - } - - string uxmlNamespace = factory.uxmlNamespace; - SchemaInfo schemaInfo; - if (!schemas.TryGetValue(uxmlNamespace, out schemaInfo)) - { - schemaInfo = new SchemaInfo(uxmlNamespace); - schemas[uxmlNamespace] = schemaInfo; - } - - XmlSchemaType type = AddElementTypeToXmlSchema(factory, schemaInfo, processingData); - AddElementToXmlSchema(factory, schemaInfo, type); - - processingData.RegisterElementType(factory.uxmlName, factory.uxmlNamespace); - - return true; - } - - static XmlSchemaParticle MakeChoiceSequence(IEnumerable elements) - { - if (!elements.Any()) - { - return null; - } - else - { - XmlSchemaSequence sequence = new XmlSchemaSequence(); - sequence.MinOccurs = 0; - sequence.MaxOccursString = "unbounded"; - - if (elements.Count() == 1) - { - IEnumerator enumerator = elements.GetEnumerator(); - enumerator.MoveNext(); - XmlSchemaElement elementRef = new XmlSchemaElement(); - elementRef.RefName = new XmlQualifiedName(enumerator.Current.elementName, enumerator.Current.elementNamespace); - sequence.Items.Add(elementRef); - } - else - { - XmlSchemaChoice choice = new XmlSchemaChoice(); - - foreach (UxmlChildElementDescription element in elements) - { - XmlSchemaElement elementRef = new XmlSchemaElement(); - elementRef.RefName = new XmlQualifiedName(element.elementName, element.elementNamespace); - choice.Items.Add(elementRef); - } - sequence.Items.Add(choice); - } - - return sequence; - } - } - - static XmlSchemaType AddElementTypeToXmlSchema(IUxmlFactory factory, SchemaInfo schemaInfo, FactoryProcessingHelper processingData) - { - // We always have complex types with complex content. - XmlSchemaComplexType elementType = new XmlSchemaComplexType(); - elementType.Name = factory.uxmlName + k_TypeSuffix; - - XmlSchemaComplexContent content = new XmlSchemaComplexContent(); - elementType.ContentModel = content; - - // We only support restrictions of base types. - XmlSchemaComplexContentRestriction restriction = new XmlSchemaComplexContentRestriction(); - content.Content = restriction; - - if (factory.substituteForTypeName == String.Empty) - { - restriction.BaseTypeName = new XmlQualifiedName("anyType", k_XmlSchemaNamespace); - } - else - { - restriction.BaseTypeName = new XmlQualifiedName(factory.substituteForTypeName + k_TypeSuffix, factory.substituteForTypeNamespace); - schemaInfo.importNamespaces.Add(factory.substituteForTypeNamespace); - } - - if (factory.canHaveAnyAttribute) - { - XmlSchemaAnyAttribute anyAttribute = new XmlSchemaAnyAttribute(); - anyAttribute.ProcessContents = XmlSchemaContentProcessing.Lax; - restriction.AnyAttribute = anyAttribute; - } - - foreach (UxmlAttributeDescription attrDesc in factory.uxmlAttributesDescription) - { - XmlQualifiedName typeName = AddAttributeTypeToXmlSchema(schemaInfo, attrDesc, factory, processingData); - if (typeName != null) - { - AddAttributeToXmlSchema(restriction, attrDesc, typeName); - schemaInfo.importNamespaces.Add(attrDesc.typeNamespace); - } - } - - bool hasChildElements = false; - foreach (UxmlChildElementDescription childDesc in factory.uxmlChildElementsDescription) - { - hasChildElements = true; - schemaInfo.importNamespaces.Add(childDesc.elementNamespace); - } - - if (hasChildElements) - { - restriction.Particle = MakeChoiceSequence(factory.uxmlChildElementsDescription); - } - - schemaInfo.schema.Items.Add(elementType); - return elementType; - } - - static void AddElementToXmlSchema(IUxmlFactory factory, SchemaInfo schemaInfo, XmlSchemaType type) - { - XmlSchemaElement element = new XmlSchemaElement(); - element.Name = factory.uxmlName; - - if (type != null) - { - element.SchemaTypeName = new XmlQualifiedName(type.Name, factory.uxmlNamespace); - } - - if (factory.substituteForTypeName != String.Empty) - { - element.SubstitutionGroup = new XmlQualifiedName(factory.substituteForTypeName, factory.substituteForTypeNamespace); - } - - schemaInfo.schema.Items.Add(element); - } - - static XmlQualifiedName AddAttributeTypeToXmlSchema(SchemaInfo schemaInfo, UxmlAttributeDescription description, IUxmlFactory factory, FactoryProcessingHelper processingData) - { - if (description.name == null) - { - return null; - } - - string attrTypeName = factory.uxmlQualifiedName + "_" + description.name + "_" + k_TypeSuffix; - string attrTypeNameInBaseElement = factory.substituteForTypeQualifiedName + "_" + description.name + "_" + k_TypeSuffix; - - FactoryProcessingHelper.AttributeRecord attrRecord; - if (processingData.attributeTypeNames.TryGetValue(attrTypeNameInBaseElement, out attrRecord)) - { - // If restriction != baseElement.restriction, we need to declare a new type. - // Note: we do not support attributes having a less restrictive restriction than its base type. - if ((description.restriction == null && attrRecord.desc.restriction == null) || - (description.restriction != null && description.restriction.Equals(attrRecord.desc.restriction))) - { - // Register attrTypeName -> attrRecord for potential future derived elements. - processingData.attributeTypeNames.Add(attrTypeName, attrRecord); - return attrRecord.name; - } - } - - XmlQualifiedName xqn; - FactoryProcessingHelper.AttributeRecord attributeRecord; - - if (description.restriction == null) - { - // Type is a built-in type. - xqn = new XmlQualifiedName(description.type, description.typeNamespace); - attributeRecord = new FactoryProcessingHelper.AttributeRecord { name = xqn, desc = description }; - processingData.attributeTypeNames.Add(attrTypeName, attributeRecord); - return xqn; - } - - string attrTypeNameForSchema = factory.uxmlName + "_" + description.name + "_" + k_TypeSuffix; - xqn = new XmlQualifiedName(attrTypeNameForSchema, schemaInfo.schema.TargetNamespace); - - XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType(); - simpleType.Name = attrTypeNameForSchema; - - UxmlEnumeration enumRestriction = description.restriction as UxmlEnumeration; - if (enumRestriction != null) - { - XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); - simpleType.Content = restriction; - restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace); - - foreach (var v in enumRestriction.values) - { - XmlSchemaEnumerationFacet enumValue = new XmlSchemaEnumerationFacet(); - enumValue.Value = v; - restriction.Facets.Add(enumValue); - } - } - else - { - UxmlValueMatches regexRestriction = description.restriction as UxmlValueMatches; - if (regexRestriction != null) - { - XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); - simpleType.Content = restriction; - restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace); - - XmlSchemaPatternFacet pattern = new XmlSchemaPatternFacet(); - pattern.Value = regexRestriction.regex; - restriction.Facets.Add(pattern); - } - else - { - UxmlValueBounds bounds = description.restriction as UxmlValueBounds; - if (bounds != null) - { - XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); - simpleType.Content = restriction; - restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace); - - XmlSchemaFacet facet; - if (bounds.excludeMin) - { - facet = new XmlSchemaMinExclusiveFacet(); - } - else - { - facet = new XmlSchemaMinInclusiveFacet(); - } - facet.Value = bounds.min; - restriction.Facets.Add(facet); - - if (bounds.excludeMax) - { - facet = new XmlSchemaMaxExclusiveFacet(); - } - else - { - facet = new XmlSchemaMaxInclusiveFacet(); - } - facet.Value = bounds.max; - restriction.Facets.Add(facet); - } - else - { - Debug.Log("Unsupported restriction type."); - } - } - } - - schemaInfo.schema.Items.Add(simpleType); - attributeRecord = new FactoryProcessingHelper.AttributeRecord { name = xqn, desc = description }; - processingData.attributeTypeNames.Add(attrTypeName, attributeRecord); - return xqn; - } - - static void AddAttributeToXmlSchema(XmlSchemaComplexContentRestriction restriction, UxmlAttributeDescription description, XmlQualifiedName typeName) - { - XmlSchemaAttribute attr = new XmlSchemaAttribute(); - attr.Name = description.name; - attr.SchemaTypeName = typeName; - - switch (description.use) - { - case UxmlAttributeDescription.Use.Optional: - attr.Use = XmlSchemaUse.Optional; - attr.DefaultValue = description.defaultValueAsString; - break; - - case UxmlAttributeDescription.Use.Prohibited: - attr.Use = XmlSchemaUse.Prohibited; - break; - - case UxmlAttributeDescription.Use.Required: - attr.Use = XmlSchemaUse.Required; - break; - - default: - attr.Use = XmlSchemaUse.None; - break; - } - - restriction.Attributes.Add(attr); - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/VisualSplitter.cs b/Editor/Mono/UIElements/Experimental/VisualSplitter.cs deleted file mode 100644 index 520693e9ff..0000000000 --- a/Editor/Mono/UIElements/Experimental/VisualSplitter.cs +++ /dev/null @@ -1,202 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; - -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Experimental.UIElements.StyleEnums; - -namespace UnityEditor.Experimental.UIElements -{ - internal class VisualSplitter : VisualElement - { - const int kDefaultSplitSize = 10; - public int splitSize = kDefaultSplitSize; - - public new class UxmlFactory : UxmlFactory {} - - public new class UxmlTraits : VisualElement.UxmlTraits {} - - private class SplitManipulator : MouseManipulator - { - private int m_ActiveVisualElementIndex = -1; - private int m_NextVisualElementIndex = -1; - - private List m_AffectedElements; - - bool m_Active; - - public SplitManipulator() - { - activators.Add(new ManipulatorActivationFilter {button = MouseButton.LeftMouse}); - } - - protected override void RegisterCallbacksOnTarget() - { - target.RegisterCallback(OnMouseDown, TrickleDown.TrickleDown); - target.RegisterCallback(OnMouseMove, TrickleDown.TrickleDown); - target.RegisterCallback(OnMouseUp, TrickleDown.TrickleDown); - } - - protected override void UnregisterCallbacksFromTarget() - { - target.UnregisterCallback(OnMouseDown, TrickleDown.TrickleDown); - target.UnregisterCallback(OnMouseMove, TrickleDown.TrickleDown); - target.UnregisterCallback(OnMouseUp, TrickleDown.TrickleDown); - } - - protected void OnMouseDown(MouseDownEvent e) - { - if (CanStartManipulation(e)) - { - VisualSplitter visualSplitter = target as VisualSplitter; - FlexDirection flexDirection = visualSplitter.style.flexDirection; - - if (m_AffectedElements != null) - { - VisualElementListPool.Release(m_AffectedElements); - } - m_AffectedElements = visualSplitter.GetAffectedVisualElements(); - - for (int i = 0; i < m_AffectedElements.Count - 1; ++i) - { - VisualElement visualElement = m_AffectedElements[i]; - - Rect splitterRect = visualSplitter.GetSplitterRect(visualElement); - - if (splitterRect.Contains(e.localMousePosition)) - { - bool isReverse = flexDirection == FlexDirection.RowReverse || flexDirection == FlexDirection.ColumnReverse; - - if (isReverse) - { - m_ActiveVisualElementIndex = i + 1; - m_NextVisualElementIndex = i; - } - else - { - m_ActiveVisualElementIndex = i; - m_NextVisualElementIndex = i + 1; - } - - m_Active = true; - target.CaptureMouse(); - e.StopPropagation(); - } - } - } - } - - protected void OnMouseMove(MouseMoveEvent e) - { - if (m_Active) - { - // These calculations should only work if flex-basis is auto. - // However, Yoga implementation of flex-basis 0 is broken and behaves much like - // flex-basis auto, so it currently works with flex-basis 0 too. - - VisualSplitter visualSplitter = target as VisualSplitter; - VisualElement visualElement = m_AffectedElements[m_ActiveVisualElementIndex]; - VisualElement nextVisualElement = m_AffectedElements[m_NextVisualElementIndex]; - - FlexDirection flexDirection = visualSplitter.style.flexDirection; - bool isVertical = flexDirection == FlexDirection.Column || flexDirection == FlexDirection.ColumnReverse; - - float relativeMousePosition; - if (isVertical) - { - relativeMousePosition = (e.localMousePosition.y - visualElement.layout.yMin - visualElement.style.minHeight) / - (visualElement.layout.height + nextVisualElement.layout.height - - visualElement.style.minHeight - nextVisualElement.style.minHeight); - } - else - { - relativeMousePosition = (e.localMousePosition.x - visualElement.layout.xMin - visualElement.style.minWidth) / - (visualElement.layout.width + nextVisualElement.layout.width - - visualElement.style.minWidth - nextVisualElement.style.minWidth); - } - - relativeMousePosition = Math.Max(0.0f, Math.Min(1.0f, relativeMousePosition)); - - float totalFlex = visualElement.style.flexGrow + nextVisualElement.style.flexGrow; - visualElement.style.flexGrow = relativeMousePosition * totalFlex; - nextVisualElement.style.flexGrow = (1.0f - relativeMousePosition) * totalFlex; - - e.StopPropagation(); - } - } - - protected void OnMouseUp(MouseUpEvent e) - { - if (m_Active && CanStopManipulation(e)) - { - m_Active = false; - target.ReleaseMouse(); - e.StopPropagation(); - - m_ActiveVisualElementIndex = -1; - m_NextVisualElementIndex = -1; - } - } - } - - public VisualSplitter() - { - this.AddManipulator(new SplitManipulator()); - } - - public List GetAffectedVisualElements() - { - List elements = VisualElementListPool.Get(); - for (int i = 0; i < shadow.childCount; ++i) - { - VisualElement element = shadow[i]; - if (element.style.positionType == PositionType.Relative) - elements.Add(element); - } - - return elements; - } - - protected override void DoRepaint(IStylePainter painter) - { - for (int i = 0; i < shadow.childCount - 1; ++i) - { - VisualElement visualElement = shadow[i]; - bool isVertical = style.flexDirection == FlexDirection.Column || style.flexDirection == FlexDirection.ColumnReverse; - - EditorGUIUtility.AddCursorRect(GetSplitterRect(visualElement), isVertical ? MouseCursor.ResizeVertical : MouseCursor.SplitResizeLeftRight); - } - } - - public Rect GetSplitterRect(VisualElement visualElement) - { - Rect rect = visualElement.layout; - if (style.flexDirection == FlexDirection.Row) - { - rect.xMin = visualElement.layout.xMax - splitSize * 0.5f; - rect.xMax = visualElement.layout.xMax + splitSize * 0.5f; - } - else if (style.flexDirection == FlexDirection.RowReverse) - { - rect.xMin = visualElement.layout.xMin - splitSize * 0.5f; - rect.xMax = visualElement.layout.xMin + splitSize * 0.5f; - } - else if (style.flexDirection == FlexDirection.Column) - { - rect.yMin = visualElement.layout.yMax - splitSize * 0.5f; - rect.yMax = visualElement.layout.yMax + splitSize * 0.5f; - } - else if (style.flexDirection == FlexDirection.ColumnReverse) - { - rect.yMin = visualElement.layout.yMin - splitSize * 0.5f; - rect.yMax = visualElement.layout.yMin + splitSize * 0.5f; - } - - return rect; - } - } -} diff --git a/Editor/Mono/UIElements/Experimental/VisualTreeAssetEditor.cs b/Editor/Mono/UIElements/Experimental/VisualTreeAssetEditor.cs deleted file mode 100644 index dd9f1f6885..0000000000 --- a/Editor/Mono/UIElements/Experimental/VisualTreeAssetEditor.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEditor; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using Object = UnityEngine.Object; - -namespace UnityEditor.Experimental.UIElements -{ - [CustomEditor(typeof(VisualTreeAsset))] - internal class VisualTreeAssetEditor : ScriptableObjectAssetEditor - { - private Panel m_Panel; - private VisualElement m_Tree; - private VisualTreeAsset m_LastTree; - private Texture2D m_FileTypeIcon; - - protected void OnEnable() - { - m_FileTypeIcon = EditorGUIUtility.FindTexture(typeof(VisualTreeAsset)); - } - - protected void OnDestroy() - { - m_Panel = null; - if (m_LastTree != null) - { - UIElementsUtility.RemoveCachedPanel(m_LastTree.GetInstanceID()); - } - } - - public override bool HasPreviewGUI() - { - return true; - } - - private void RenderIcon(Rect iconRect) - { - Debug.Assert(m_FileTypeIcon != null); - GUI.DrawTexture(iconRect, m_FileTypeIcon, ScaleMode.ScaleToFit); - } - - public void Render(VisualTreeAsset vta, Rect r, GUIStyle background) - { - if (Event.current.type != EventType.Repaint || r.width < 100 && r.height < 100) - return; - - bool dirty = false; - if (vta != m_LastTree || !m_LastTree) - { - m_LastTree = vta; - m_Tree = vta.CloneTree(null); - m_Tree.StretchToParentSize(); - dirty = true; - } - - if (m_Panel == null) - { - m_Panel = UIElementsUtility.FindOrCreatePanel(m_LastTree, ContextType.Editor, new DataWatchService()); - if (m_Panel.visualTree.styleSheets == null) - { - UIElementsEditorUtility.AddDefaultEditorStyleSheets(m_Panel.visualTree); - m_Panel.visualTree.LoadStyleSheetsFromPaths(); - } - m_Panel.allowPixelCaching = false; - dirty = true; - } - - if (dirty) - { - m_Panel.visualTree.Clear(); - m_Panel.visualTree.Add(m_Tree); - } - - EditorGUI.DrawRect(r, EditorGUIUtility.kViewBackgroundColor); - - m_Panel.visualTree.layout = GUIClip.UnclipToWindow(r); - m_Panel.visualTree.IncrementVersion(VersionChangeType.Repaint); - - var oldState = SavedGUIState.Create(); - int clips = GUIClip.Internal_GetCount(); - while (clips > 0) - { - GUIClip.Pop(); - clips--; - } - - m_Panel.Repaint(Event.current); - - oldState.ApplyAndForget(); - } - - public override void OnPreviewGUI(Rect r, GUIStyle background) - { - const int k_IconSize = 64; - - base.OnPreviewGUI(r, background); - if (r.width > k_IconSize || r.height > k_IconSize) - Render(target as VisualTreeAsset, r, background); - else - RenderIcon(r); - } - } -} diff --git a/Editor/Mono/UIElements/Tooltip.cs b/Editor/Mono/UIElements/Tooltip.cs index b8830517da..f9f7a034c9 100644 --- a/Editor/Mono/UIElements/Tooltip.cs +++ b/Editor/Mono/UIElements/Tooltip.cs @@ -15,7 +15,7 @@ internal static void SetTooltip(float mouseX, float mouseY) { //mouseX,mouseY are screen relative. GUIView view = GUIView.mouseOverView; - if (view != null && view.uieMode != GUIView.UIElementsMode.Experimental && view.visualTree != null && view.visualTree.panel != null) + if (view != null && view.visualTree != null && view.visualTree.panel != null) { var panel = view.visualTree.panel; @@ -40,9 +40,6 @@ internal static void SetTooltip(float mouseX, float mouseY) } } } - - //temporary for backwards compatibility - UnityEditor.Experimental.UIElements.Tooltip.SetTooltip(mouseX, mouseY); } } } diff --git a/Editor/Mono/UIElements/UIElementsEditorWindowCreator/UxmlTemplateCreator.cs b/Editor/Mono/UIElements/UIElementsEditorWindowCreator/UxmlTemplateCreator.cs index 5e6206a09d..b3f0df9ae8 100644 --- a/Editor/Mono/UIElements/UIElementsEditorWindowCreator/UxmlTemplateCreator.cs +++ b/Editor/Mono/UIElements/UIElementsEditorWindowCreator/UxmlTemplateCreator.cs @@ -61,7 +61,7 @@ public static string CreateUXMLTemplate(string folder) {3}"" > -", UnityEditor.Experimental.UIElements.UXMLImporterImpl.k_RootNode, xmlnsList, schemaDirectory, schemaLocationList); +", UnityEditor.UIElements.UXMLImporterImpl.k_RootNode, xmlnsList, schemaDirectory, schemaLocationList); return uxmlTemplate; } diff --git a/Editor/Mono/UIElements/UIElementsViewImporter.cs b/Editor/Mono/UIElements/UIElementsViewImporter.cs index 99855bcfd3..3f97a49839 100644 --- a/Editor/Mono/UIElements/UIElementsViewImporter.cs +++ b/Editor/Mono/UIElements/UIElementsViewImporter.cs @@ -14,12 +14,11 @@ using UnityEditor.StyleSheets; using UnityEngine; +using UnityEngine.UIElements; + using StyleSheet = UnityEngine.UIElements.StyleSheet; -using VisualTreeAsset = UnityEngine.Experimental.UIElements.VisualTreeAsset; -using TemplateAsset = UnityEngine.Experimental.UIElements.TemplateAsset; -using VisualElementAsset = UnityEngine.UIElements.VisualElementAsset; -namespace UnityEditor.Experimental.UIElements +namespace UnityEditor.UIElements { // Make sure UXML is imported after assets than can be addressed in USS [ScriptedImporter(version: 6, ext: "uxml", importQueueOffset: 1000)] @@ -51,7 +50,7 @@ public override void OnImportAsset(AssetImportContext args) } } - class UXMLImporterImpl : StyleValueImporter + internal class UXMLImporterImpl : StyleValueImporter { internal struct Error { diff --git a/Editor/Mono/UIElements/UXMLEditorFactories.cs b/Editor/Mono/UIElements/UXMLEditorFactories.cs index 1549f914c1..8db3afffdb 100644 --- a/Editor/Mono/UIElements/UXMLEditorFactories.cs +++ b/Editor/Mono/UIElements/UXMLEditorFactories.cs @@ -2,7 +2,7 @@ // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License -using UnityEditor.Experimental.UIElements; +using UnityEditor.UIElements; using UnityEngine.UIElements; namespace UnityEditor.UIElements diff --git a/Editor/Mono/UIElements/VisualTreeAssetEditor.cs b/Editor/Mono/UIElements/VisualTreeAssetEditor.cs index a64497cca4..c84c67039a 100644 --- a/Editor/Mono/UIElements/VisualTreeAssetEditor.cs +++ b/Editor/Mono/UIElements/VisualTreeAssetEditor.cs @@ -8,8 +8,6 @@ using UnityEngine.UIElements; using Object = UnityEngine.Object; -using VisualTreeAsset = UnityEngine.Experimental.UIElements.VisualTreeAsset; - namespace UnityEditor.UIElements { [CustomEditor(typeof(VisualTreeAsset))] diff --git a/Modules/AssetBundle/Managed/AssetBundle.bindings.cs b/Modules/AssetBundle/Managed/AssetBundle.bindings.cs index 3fd9f51cf8..f7cfe65ab3 100644 --- a/Modules/AssetBundle/Managed/AssetBundle.bindings.cs +++ b/Modules/AssetBundle/Managed/AssetBundle.bindings.cs @@ -40,6 +40,7 @@ public enum AssetBundleLoadResult [NativeHeader("AssetBundleScriptingClasses.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleSaveAndLoadHelper.h")] [NativeHeader("Modules/AssetBundle/Public/AssetBundleUtility.h")] + [NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadAssetUtility.h")] [ExcludeFromPreset] public partial class AssetBundle : Object { diff --git a/Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs b/Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs index 45e8916c8a..eaa2337fa7 100644 --- a/Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs +++ b/Modules/AssetPipelineEditor/ImportSettings/ModelImporterMaterialEditor.cs @@ -190,6 +190,10 @@ internal override void OnEnable() private void BuildMaterialsCache() { + // do not set if multiple selection. + if (m_Materials.hasMultipleDifferentValues) + return; + m_MaterialsCache.Clear(); for (int materialIdx = 0; materialIdx < m_Materials.arraySize; ++materialIdx) { @@ -204,6 +208,10 @@ private void BuildMaterialsCache() private void BuildExternalObjectsCache() { + // do not set if multiple selection. + if (m_ExternalObjects.hasMultipleDifferentValues) + return; + m_ExternalObjectsCache.Clear(); for (int externalObjectIdx = 0, count = m_ExternalObjects.arraySize; externalObjectIdx < count; ++externalObjectIdx) { @@ -483,7 +491,7 @@ void DoMaterialsGUI() } // hidden for multi-selection - if (m_ImportMaterials.boolValue && targets.Length == 1 && m_Materials.arraySize > 0 && m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues) + if (m_ImportMaterials.boolValue && targets.Length == 1 && m_Materials.arraySize > 0 && m_MaterialLocation.intValue != 0 && !m_MaterialLocation.hasMultipleDifferentValues && !m_Materials.hasMultipleDifferentValues && !m_ExternalObjects.hasMultipleDifferentValues) { GUILayout.Label(Styles.ExternalMaterialMappings, EditorStyles.boldLabel); diff --git a/Modules/Audio/Public/ScriptBindings/AudioClipExtensions.bindings.cs b/Modules/Audio/Public/ScriptBindings/AudioClipExtensions.bindings.cs index f7a9ed54c7..1e003d4020 100644 --- a/Modules/Audio/Public/ScriptBindings/AudioClipExtensions.bindings.cs +++ b/Modules/Audio/Public/ScriptBindings/AudioClipExtensions.bindings.cs @@ -21,16 +21,17 @@ internal static class AudioClipExtensions { public static AudioSampleProvider CreateAudioSampleProvider( this AudioClip audioClip, ulong startSampleFrameIndex = 0, - long endSampleFrameIndex = 0, bool loop = false) + long endSampleFrameIndex = 0, bool loop = false, bool allowDrop = false) { return AudioSampleProvider.Lookup( Internal_CreateAudioClipSampleProvider( - audioClip, startSampleFrameIndex, endSampleFrameIndex, loop), null, 0); + audioClip, startSampleFrameIndex, endSampleFrameIndex, loop, allowDrop), + null, 0); } [NativeMethod(IsFreeFunction = true, ThrowsException = true)] extern private static uint Internal_CreateAudioClipSampleProvider( - AudioClip audioClip, ulong start, long end, bool loop); + AudioClip audioClip, ulong start, long end, bool loop, bool allowDrop); } } diff --git a/Modules/Audio/Public/csas/Managed/DSPCommandBlock.cs b/Modules/Audio/Public/csas/Managed/DSPCommandBlock.cs index 4af753da58..95f488a76c 100644 --- a/Modules/Audio/Public/csas/Managed/DSPCommandBlock.cs +++ b/Modules/Audio/Public/csas/Managed/DSPCommandBlock.cs @@ -7,6 +7,7 @@ using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine.Experimental.Audio; +using UnityEngine; [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.UNode.Audio")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Unity.UNode.Audio.Tests")] @@ -161,12 +162,100 @@ public void Disconnect(DSPNode output, int outputPort, DSPNode input, int inputP public void SetAttenuation(DSPConnection connection, float value, uint interpolationLength = 0) { - Internal_SetAttenuation(ref this, ref connection, value, interpolationLength); + unsafe + { + Internal_SetAttenuation(ref this, ref connection, (void*)&value, 1, interpolationLength); + } + } + + public void SetAttenuation(DSPConnection connection, float value1, float value2, uint interpolationLength = 0) + { + unsafe + { + float* buffer = stackalloc float[2]; + buffer[0] = value1; + buffer[1] = value2; + Internal_SetAttenuation(ref this, ref connection, buffer, 2, interpolationLength); + } + } + + public void SetAttenuation(DSPConnection connection, float value1, float value2, float value3, uint interpolationLength = 0) + { + unsafe + { + float* buffer = stackalloc float[3]; + buffer[0] = value1; + buffer[1] = value2; + buffer[2] = value3; + Internal_SetAttenuation(ref this, ref connection, buffer, 3, interpolationLength); + } + } + + public void SetAttenuation(DSPConnection connection, float value1, float value2, float value3, float value4, uint interpolationLength = 0) + { + unsafe + { + float* buffer = stackalloc float[4]; + buffer[0] = value1; + buffer[1] = value2; + buffer[2] = value3; + buffer[3] = value4; + Internal_SetAttenuation(ref this, ref connection, buffer, 4, interpolationLength); + } + } + + public unsafe void SetAttenuation(DSPConnection connection, float* value, byte dimension, uint interpolationLength = 0) + { + Internal_SetAttenuation(ref this, ref connection, value, dimension, interpolationLength); } public void AddAttenuationKey(DSPConnection connection, ulong dspClock, float value) { - Internal_AddAttenuationKey(ref this, ref connection, dspClock, value); + unsafe + { + Internal_AddAttenuationKey(ref this, ref connection, dspClock, &value, 1); + } + } + + public void AddAttenuationKey(DSPConnection connection, ulong dspClock, float value1, float value2) + { + unsafe + { + float* buffer = stackalloc float[2]; + buffer[0] = value1; + buffer[1] = value2; + Internal_AddAttenuationKey(ref this, ref connection, dspClock, buffer, 2); + } + } + + public void AddAttenuationKey(DSPConnection connection, ulong dspClock, float value1, float value2, float value3) + { + unsafe + { + float* buffer = stackalloc float[3]; + buffer[0] = value1; + buffer[1] = value2; + buffer[2] = value3; + Internal_AddAttenuationKey(ref this, ref connection, dspClock, buffer, 3); + } + } + + public void AddAttenuationKey(DSPConnection connection, ulong dspClock, float value1, float value2, float value3, float value4) + { + unsafe + { + float* buffer = stackalloc float[4]; + buffer[0] = value1; + buffer[1] = value2; + buffer[2] = value3; + buffer[3] = value4; + Internal_AddAttenuationKey(ref this, ref connection, dspClock, buffer, 4); + } + } + + public unsafe void AddAttenuationKey(DSPConnection connection, ulong dspClock, float* value, byte dimension) + { + Internal_AddAttenuationKey(ref this, ref connection, dspClock, value, dimension); } public void SustainAttenuation(DSPConnection connection, ulong dspClock) diff --git a/Modules/Audio/Public/csas/Managed/DSPGraph.cs b/Modules/Audio/Public/csas/Managed/DSPGraph.cs index 0c52a2d1c9..411bb62c00 100644 --- a/Modules/Audio/Public/csas/Managed/DSPGraph.cs +++ b/Modules/Audio/Public/csas/Managed/DSPGraph.cs @@ -108,7 +108,14 @@ public unsafe void ReadMix(NativeArray buffer) public unsafe uint AddNodeEventHandler(Action handler) where TNodeEvent : struct { - return Internal_AddNodeEventHandler(ref this, GetTypeHashCode(), handler); + return AddNodeEventHandler(GetTypeHashCode(), handler); + } + + // FIXME: Temporarily exposed until BurstRuntime.GetHashCode64 has a Unity-core + // equivalent, or DSPGraph's C# code is moved to a package. + public unsafe uint AddNodeEventHandler(long eventTypeHash, Action handler) where TNodeEvent : struct + { + return Internal_AddNodeEventHandler(ref this, eventTypeHash, handler); } public unsafe bool RemoveNodeEventHandler(uint handlerId) diff --git a/Modules/Audio/Public/csas/Managed/ExecuteContext.cs b/Modules/Audio/Public/csas/Managed/ExecuteContext.cs index 0bbafdd64c..156bd8a6a0 100644 --- a/Modules/Audio/Public/csas/Managed/ExecuteContext.cs +++ b/Modules/Audio/Public/csas/Managed/ExecuteContext.cs @@ -21,9 +21,18 @@ internal unsafe struct ExecuteContext public ulong DSPClock { get { return m_DSPClock; } } public uint DSPBufferSize { get { return m_DSPBufferSize; } } public uint SampleRate { get { return m_SampleRate; } } - public void PostEvent(T eventMsg) where T : struct + public void PostEvent(TNodeEvent eventMsg) where TNodeEvent : struct { - ExecuteContextInternal.Internal_PostEvent(m_DSPNodePtr, DSPGraph.GetTypeHashCode(), UnsafeUtility.AddressOf(ref eventMsg), UnsafeUtility.SizeOf()); + PostEvent(DSPGraph.GetTypeHashCode(), eventMsg); + } + + // FIXME: Temporarily exposed until BurstRuntime.GetHashCode64 has a Unity-core + // equivalent, or DSPGraph's C# code is moved to a package. + public void PostEvent(long eventTypeHash, TNodeEvent eventMsg) where TNodeEvent : struct + { + ExecuteContextInternal.Internal_PostEvent( + m_DSPNodePtr, eventTypeHash, UnsafeUtility.AddressOf(ref eventMsg), + UnsafeUtility.SizeOf()); } internal ulong m_DSPClock; diff --git a/Modules/Audio/Public/csas/Managed/ResourceContext.cs b/Modules/Audio/Public/csas/Managed/ResourceContext.cs index bf2b88db69..79248a325a 100644 --- a/Modules/Audio/Public/csas/Managed/ResourceContext.cs +++ b/Modules/Audio/Public/csas/Managed/ResourceContext.cs @@ -24,6 +24,8 @@ public NativeArray AllocateArray(int length) where T : struct var memory = Internal_AllocateArray(m_DSPNodePtr, size); var nBuffer = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(memory, length, Allocator.Invalid); + NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nBuffer, AtomicSafetyHandle.Create()); + return nBuffer; } diff --git a/Modules/Audio/Public/csas/Managed/SampleBufferArray.cs b/Modules/Audio/Public/csas/Managed/SampleBufferArray.cs index 656a858a91..2980aea888 100644 --- a/Modules/Audio/Public/csas/Managed/SampleBufferArray.cs +++ b/Modules/Audio/Public/csas/Managed/SampleBufferArray.cs @@ -22,6 +22,7 @@ unsafe struct NativeSampleBuffer public uint m_Channels; public SoundFormat m_Format; public float* m_Buffer; + private bool m_Initialized; } internal enum SoundFormat diff --git a/Modules/Audio/Public/csas/ScriptBindings/DSPCommandBlock.bindings.cs b/Modules/Audio/Public/csas/ScriptBindings/DSPCommandBlock.bindings.cs index 353330644b..01cd9cc3a7 100644 --- a/Modules/Audio/Public/csas/ScriptBindings/DSPCommandBlock.bindings.cs +++ b/Modules/Audio/Public/csas/ScriptBindings/DSPCommandBlock.bindings.cs @@ -44,10 +44,10 @@ static extern unsafe void Internal_CreateUpdateRequest( static extern void Internal_DisconnectByHandle(ref DSPCommandBlock block, ref DSPConnection connection); [NativeMethod(IsFreeFunction = true, ThrowsException = true)] - static extern void Internal_SetAttenuation(ref DSPCommandBlock block, ref DSPConnection connection, float value, uint interpolationLength); + static extern unsafe void Internal_SetAttenuation(ref DSPCommandBlock block, ref DSPConnection connection, void* value, byte dimension, uint interpolationLength); [NativeMethod(IsFreeFunction = true, ThrowsException = true)] - static extern void Internal_AddAttenuationKey(ref DSPCommandBlock block, ref DSPConnection connection, ulong dspClock, float value); + static extern unsafe void Internal_AddAttenuationKey(ref DSPCommandBlock block, ref DSPConnection connection, ulong dspClock, void* value, byte dimension); [NativeMethod(IsFreeFunction = true, ThrowsException = true)] static extern void Internal_SustainAttenuation(ref DSPCommandBlock block, ref DSPConnection connection, ulong dspClock); diff --git a/Modules/GraphViewEditor/Elements/Blackboard/BlackboardField.cs b/Modules/GraphViewEditor/Elements/Blackboard/BlackboardField.cs index f29dd66664..978464f20d 100644 --- a/Modules/GraphViewEditor/Elements/Blackboard/BlackboardField.cs +++ b/Modules/GraphViewEditor/Elements/Blackboard/BlackboardField.cs @@ -89,7 +89,8 @@ protected internal override void ExecuteDefaultAction(EventBase evt) if (evt.eventTypeId == AttachToPanelEvent.TypeId()) { var graphView = GetFirstAncestorOfType(); - graphView.RestorePersitentSelectionForElement(this); + if (graphView != null) + graphView.RestorePersitentSelectionForElement(this); } } diff --git a/Modules/GraphViewEditor/Elements/Edge.cs b/Modules/GraphViewEditor/Elements/Edge.cs index 6c75cd5fc0..64e2676f7d 100644 --- a/Modules/GraphViewEditor/Elements/Edge.cs +++ b/Modules/GraphViewEditor/Elements/Edge.cs @@ -356,8 +356,8 @@ void DoTrackGraphElement(Port port) current = current.hierarchy.parent; } - - port.node.RegisterCallback(OnGeometryChanged); + if (port.node != null) + port.node.RegisterCallback(OnGeometryChanged); } void DoUntrackGraphElement(Port port) @@ -378,7 +378,8 @@ void DoUntrackGraphElement(Port port) current = current.hierarchy.parent; } - port.node.UnregisterCallback(OnGeometryChanged); + if (port.node != null) + port.node.UnregisterCallback(OnGeometryChanged); } private void OnPortGeometryChanged(GeometryChangedEvent evt) diff --git a/Modules/GraphViewEditor/Elements/StackNode.cs b/Modules/GraphViewEditor/Elements/StackNode.cs index 6b5e01e77a..77d3eff9e9 100644 --- a/Modules/GraphViewEditor/Elements/StackNode.cs +++ b/Modules/GraphViewEditor/Elements/StackNode.cs @@ -65,10 +65,13 @@ protected internal override void ExecuteDefaultAction(EventBase evt) { graphView = GetFirstAncestorOfType(); - // Restore selections on children. - foreach (var child in Children().OfType()) + if (graphView != null) { - graphView.RestorePersitentSelectionForElement(child); + // Restore selections on children. + foreach (var child in Children().OfType()) + { + graphView.RestorePersitentSelectionForElement(child); + } } } } diff --git a/Modules/GraphViewEditor/ExperimentalUIElements/Orientation.cs b/Modules/GraphViewEditor/ExperimentalNamespaceRelic.cs similarity index 50% rename from Modules/GraphViewEditor/ExperimentalUIElements/Orientation.cs rename to Modules/GraphViewEditor/ExperimentalNamespaceRelic.cs index 96c2377600..6a417bff61 100644 --- a/Modules/GraphViewEditor/ExperimentalUIElements/Orientation.cs +++ b/Modules/GraphViewEditor/ExperimentalNamespaceRelic.cs @@ -4,9 +4,7 @@ namespace UnityEditor.Experimental.UIElements.GraphView { - public enum Orientation - { - Horizontal, - Vertical - } + // We cannot delete the whole namespace just yet as there are left-over using statement in some packages + // However expect this using statement no visible types exist anymore + internal class Empty {} } diff --git a/Modules/GraphViewEditor/ExperimentalUIElements/Capabilities.cs b/Modules/GraphViewEditor/ExperimentalUIElements/Capabilities.cs deleted file mode 100644 index 2fd3b7da0a..0000000000 --- a/Modules/GraphViewEditor/ExperimentalUIElements/Capabilities.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - [Flags] - public enum Capabilities - { - Selectable = 1 << 0, - Collapsible = 1 << 1, - Resizable = 1 << 2, - Movable = 1 << 3, - Deletable = 1 << 4, - Droppable = 1 << 5, - Ascendable = 1 << 6, - Renamable = 1 << 7, - } -} diff --git a/Modules/GraphViewEditor/ExperimentalUIElements/Decorators/GridBackground.cs b/Modules/GraphViewEditor/ExperimentalUIElements/Decorators/GridBackground.cs deleted file mode 100644 index c7df705cc0..0000000000 --- a/Modules/GraphViewEditor/ExperimentalUIElements/Decorators/GridBackground.cs +++ /dev/null @@ -1,235 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Experimental.UIElements.StyleSheets; - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - public class GridBackground : VisualElement - { - const string k_SpacingProperty = "spacing"; - const string k_ThickLinesProperty = "thick-lines"; - const string k_LineColorProperty = "line-color"; - const string k_ThickLineColorProperty = "thick-line-color"; - const string k_GridBackgroundColorProperty = "grid-background-color"; - - StyleValue m_Spacing; - float spacing - { - get - { - return m_Spacing.GetSpecifiedValueOrDefault(50.0f); - } - } - - StyleValue m_ThickLines; - int thickLines - { - get - { - return m_ThickLines.GetSpecifiedValueOrDefault(10); - } - } - - StyleValue m_LineColor; - Color lineColor - { - get - { - return m_LineColor.GetSpecifiedValueOrDefault(new Color(0f, 0f, 0f, 0.18f)); - } - } - - StyleValue m_ThickLineColor; - Color thickLineColor - { - get - { - return m_ThickLineColor.GetSpecifiedValueOrDefault(new Color(0f, 0f, 0f, 0.38f)); - } - } - - StyleValue m_GridBackgroundColor; - Color gridBackgroundColor - { - get - { - return m_GridBackgroundColor.GetSpecifiedValueOrDefault(new Color(0.17f, 0.17f, 0.17f, 1.0f)); - } - } - - private VisualElement m_Container; - - public GridBackground() - { - pickingMode = PickingMode.Ignore; - - this.StretchToParentSize(); - } - - private Vector3 Clip(Rect clipRect, Vector3 _in) - { - if (_in.x < clipRect.xMin) - _in.x = clipRect.xMin; - if (_in.x > clipRect.xMax) - _in.x = clipRect.xMax; - - if (_in.y < clipRect.yMin) - _in.y = clipRect.yMin; - if (_in.y > clipRect.yMax) - _in.y = clipRect.yMax; - - return _in; - } - - protected override void OnStyleResolved(ICustomStyle elementStyle) - { - base.OnStyleResolved(elementStyle); - elementStyle.ApplyCustomProperty(k_SpacingProperty, ref m_Spacing); - elementStyle.ApplyCustomProperty(k_ThickLinesProperty, ref m_ThickLines); - elementStyle.ApplyCustomProperty(k_ThickLineColorProperty, ref m_ThickLineColor); - elementStyle.ApplyCustomProperty(k_LineColorProperty, ref m_LineColor); - elementStyle.ApplyCustomProperty(k_GridBackgroundColorProperty, ref m_GridBackgroundColor); - } - - protected override void DoRepaint(IStylePainter painter) - { - var stylePainter = (IStylePainterInternal)painter; - stylePainter.DrawImmediate(Draw); - } - - void Draw() - { - VisualElement target = parent; - - var graphView = target as GraphView; - if (graphView == null) - { - throw new InvalidOperationException("GridBackground can only be added to a GraphView"); - } - m_Container = graphView.contentViewContainer; - Rect clientRect = graphView.layout; - - // Since we're always stretch to parent size, we will use (0,0) as (x,y) coordinates - clientRect.x = 0; - clientRect.y = 0; - - var containerScale = new Vector3(m_Container.transform.matrix.GetColumn(0).magnitude, - m_Container.transform.matrix.GetColumn(1).magnitude, - m_Container.transform.matrix.GetColumn(2).magnitude); - var containerTranslation = m_Container.transform.matrix.GetColumn(3); - var containerPosition = m_Container.layout; - - // background - HandleUtility.ApplyWireMaterial(); - - GL.Begin(GL.QUADS); - GL.Color(gridBackgroundColor); - GL.Vertex(new Vector3(clientRect.x, clientRect.y)); - GL.Vertex(new Vector3(clientRect.xMax, clientRect.y)); - GL.Vertex(new Vector3(clientRect.xMax, clientRect.yMax)); - GL.Vertex(new Vector3(clientRect.x, clientRect.yMax)); - GL.End(); - - // vertical lines - Vector3 from = new Vector3(clientRect.x, clientRect.y, 0.0f); - Vector3 to = new Vector3(clientRect.x, clientRect.height, 0.0f); - - var tx = Matrix4x4.TRS(containerTranslation, Quaternion.identity, Vector3.one); - - from = tx.MultiplyPoint(from); - to = tx.MultiplyPoint(to); - - from.x += (containerPosition.x * containerScale.x); - from.y += (containerPosition.y * containerScale.y); - to.x += (containerPosition.x * containerScale.x); - to.y += (containerPosition.y * containerScale.y); - - Handles.DrawWireDisc(from, new Vector3(0.0f, 0.0f, -1.0f), 6f); - - float thickGridLineX = from.x; - float thickGridLineY = from.y; - - // Update from/to to start at beginning of clientRect - from.x = (from.x % (spacing * (containerScale.x)) - (spacing * (containerScale.x))); - to.x = from.x; - - from.y = clientRect.y; - to.y = clientRect.y + clientRect.height; - - while (from.x < clientRect.width) - { - from.x += spacing * containerScale.x; - to.x += spacing * containerScale.x; - - GL.Begin(GL.LINES); - GL.Color(lineColor); - GL.Vertex(Clip(clientRect, from)); - GL.Vertex(Clip(clientRect, to)); - GL.End(); - } - - float thickLineSpacing = (spacing * thickLines); - from.x = to.x = (thickGridLineX % (thickLineSpacing * (containerScale.x)) - (thickLineSpacing * (containerScale.x))); - - while (from.x < clientRect.width + thickLineSpacing) - { - GL.Begin(GL.LINES); - GL.Color(thickLineColor); - GL.Vertex(Clip(clientRect, from)); - GL.Vertex(Clip(clientRect, to)); - GL.End(); - - from.x += (spacing * containerScale.x * thickLines); - to.x += (spacing * containerScale.x * thickLines); - } - - // horizontal lines - from = new Vector3(clientRect.x, clientRect.y, 0.0f); - to = new Vector3(clientRect.x + clientRect.width, clientRect.y, 0.0f); - - from.x += (containerPosition.x * containerScale.x); - from.y += (containerPosition.y * containerScale.y); - to.x += (containerPosition.x * containerScale.x); - to.y += (containerPosition.y * containerScale.y); - - from = tx.MultiplyPoint(from); - to = tx.MultiplyPoint(to); - - from.y = to.y = (from.y % (spacing * (containerScale.y)) - (spacing * (containerScale.y))); - from.x = clientRect.x; - to.x = clientRect.width; - - while (from.y < clientRect.height) - { - from.y += spacing * containerScale.y; - to.y += spacing * containerScale.y; - - GL.Begin(GL.LINES); - GL.Color(lineColor); - GL.Vertex(Clip(clientRect, from)); - GL.Vertex(Clip(clientRect, to)); - GL.End(); - } - - thickLineSpacing = spacing * thickLines; - from.y = to.y = (thickGridLineY % (thickLineSpacing * (containerScale.y)) - (thickLineSpacing * (containerScale.y))); - - while (from.y < clientRect.height + thickLineSpacing) - { - GL.Begin(GL.LINES); - GL.Color(thickLineColor); - GL.Vertex(Clip(clientRect, from)); - GL.Vertex(Clip(clientRect, to)); - GL.End(); - - from.y += spacing * containerScale.y * thickLines; - to.y += spacing * containerScale.y * thickLines; - } - } - } -} diff --git a/Modules/GraphViewEditor/ExperimentalUIElements/Direction.cs b/Modules/GraphViewEditor/ExperimentalUIElements/Direction.cs deleted file mode 100644 index 769ad99f28..0000000000 --- a/Modules/GraphViewEditor/ExperimentalUIElements/Direction.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - public enum Direction - { - Input = 0, - Output = 1 - } -} diff --git a/Modules/GraphViewEditor/ExperimentalUIElements/EdgeControl.cs b/Modules/GraphViewEditor/ExperimentalUIElements/EdgeControl.cs deleted file mode 100644 index 8238e220c7..0000000000 --- a/Modules/GraphViewEditor/ExperimentalUIElements/EdgeControl.cs +++ /dev/null @@ -1,993 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using System.Collections.Generic; -using UnityEngine.Profiling; - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - public class EdgeControl : VisualElement - { - private struct EdgeCornerSweepValues - { - public Vector2 circleCenter; - public double sweepAngle; - public double startAngle; - public double endAngle; - public Vector2 crossPoint1; - public Vector2 crossPoint2; - public float radius; - } - - private VisualElement m_FromCap; - private VisualElement m_ToCap; - private GraphView m_GraphView; - - private static Stack capPool = new Stack(); - - private static VisualElement GetCap() - { - VisualElement result = null; - if (capPool.Count > 0) - { - result = capPool.Pop(); - } - else - { - result = new VisualElement(); - result.AddToClassList("edgeCap"); - } - - return result; - } - - private static void RecycleCap(VisualElement cap) - { - capPool.Push(cap); - } - - public EdgeControl() - { - RegisterCallback(OnLeavePanel); - - m_FromCap = null; - m_ToCap = null; - - pickingMode = PickingMode.Ignore; - } - - private bool m_ControlPointsDirty = true; - private bool m_RenderPointsDirty = true; - private bool m_MeshDirty = true; - - Mesh m_Mesh; - public const float k_MinEdgeWidth = 1.75f; - - private const float k_EdgeLengthFromPort = 12.0f; - private const float k_EdgeTurnDiameter = 16.0f; - private const float k_EdgeSweepResampleRatio = 4.0f; - private const int k_EdgeStraightLineSegmentDivisor = 5; - - private Orientation m_InputOrientation; - public Orientation inputOrientation - { - get { return m_InputOrientation; } - set - { - if (m_InputOrientation == value) - return; - m_InputOrientation = value; - MarkDirtyRepaint(); - } - } - - private Orientation m_OutputOrientation; - public Orientation outputOrientation - { - get { return m_OutputOrientation; } - set - { - if (m_OutputOrientation == value) - return; - m_OutputOrientation = value; - MarkDirtyRepaint(); - } - } - - [Obsolete("Use inputColor and/or outputColor")] - public Color edgeColor - { - get { return m_InputColor; } - set - { - if (m_InputColor == value && m_OutputColor == value) - return; - m_InputColor = value; - m_OutputColor = value; - MarkDirtyRepaint(); - } - } - - Color m_InputColor = Color.grey; - public Color inputColor - { - get { return m_InputColor; } - set - { - if (m_InputColor != value) - { - m_InputColor = value; - MarkDirtyRepaint(); - } - } - } - - Color m_OutputColor = Color.grey; - public Color outputColor - { - get { return m_OutputColor; } - set - { - if (m_OutputColor != value) - { - m_OutputColor = value; - MarkDirtyRepaint(); - } - } - } - - private Color m_FromCapColor; - public Color fromCapColor - { - get { return m_FromCapColor; } - set - { - if (m_FromCapColor == value) - return; - m_FromCapColor = value; - - if (m_FromCap != null) - { - m_FromCap.style.backgroundColor = m_FromCapColor; - } - } - } - - private Color m_ToCapColor; - public Color toCapColor - { - get { return m_ToCapColor; } - set - { - if (m_ToCapColor == value) - return; - m_ToCapColor = value; - - if (m_ToCap != null) - { - m_ToCap.style.backgroundColor = m_ToCapColor; - } - } - } - - private float m_CapRadius = 5; - public float capRadius - { - get { return m_CapRadius; } - set - { - if (m_CapRadius == value) - return; - m_CapRadius = value; - MarkDirtyRepaint(); - } - } - - private int m_EdgeWidth = 2; - public int edgeWidth - { - get { return m_EdgeWidth; } - set - { - if (m_EdgeWidth == value) - return; - m_EdgeWidth = value; - m_MeshDirty = true; - UpdateLayout(); // The layout depends on the edges width - MarkDirtyRepaint(); - } - } - - private float m_InterceptWidth = 5; - public float interceptWidth - { - get { return m_InterceptWidth; } - set { m_InterceptWidth = value; } - } - - // The start of the edge in graph coordinates. - private Vector2 m_From; - public Vector2 from - { - get { return m_From; } - set - { - if ((m_From - value).sqrMagnitude > 0.25f) - { - m_From = value; - PointsChanged(); - } - } - } - - // The end of the edge in graph coordinates. - private Vector2 m_To; - public Vector2 to - { - get { return m_To; } - set - { - if ((m_To - value).sqrMagnitude > 0.25f) - { - m_To = value; - PointsChanged(); - } - } - } - - // The control points in graph coordinates. - private Vector2[] m_ControlPoints; - public Vector2[] controlPoints - { - get - { - return m_ControlPoints; - } - } - - - public bool drawFromCap - { - get { return m_FromCap != null; } - set - { - if (!value) - { - if (m_FromCap != null) - { - m_FromCap.RemoveFromHierarchy(); - RecycleCap(m_FromCap); - m_FromCap = null; - } - } - else - { - if (m_FromCap == null) - { - m_FromCap = GetCap(); - m_FromCap.style.backgroundColor = m_FromCapColor; - Add(m_FromCap); - } - } - } - } - - public bool drawToCap - { - get { return m_ToCap != null; } - set - { - if (!value) - { - if (m_ToCap != null) - { - m_ToCap.RemoveFromHierarchy(); - RecycleCap(m_ToCap); - m_ToCap = null; - } - } - else - { - if (m_ToCap == null) - { - m_ToCap = GetCap(); - m_ToCap.style.backgroundColor = m_ToCapColor; - Add(m_ToCap); - } - } - } - } - - void UpdateEdgeCaps() - { - if (m_FromCap != null) - { - Vector2 size = m_FromCap.layout.size; - m_FromCap.layout = new Rect(parent.ChangeCoordinatesTo(this, m_From) - (size / 2), size); - } - if (m_ToCap != null) - { - Vector2 size = m_ToCap.layout.size; - m_ToCap.layout = new Rect(parent.ChangeCoordinatesTo(this, m_To) - (size / 2), size); - } - } - - protected override void DoRepaint(IStylePainter painter) - { - UnityEngine.Profiling.Profiler.BeginSample("DrawEdge"); - UpdateEdgeCaps(); - // Edges do NOT call base.DoRepaint. It would create a visual artifact. - DrawEdge(painter); - - UnityEngine.Profiling.Profiler.EndSample(); - } - - public override bool ContainsPoint(Vector2 localPoint) - { - Profiler.BeginSample("EdgeControl.ContainsPoint"); - - if (!base.ContainsPoint(localPoint)) - { - Profiler.EndSample(); - return false; - } - - // bounding box check succeeded, do more fine grained check by measuring distance to bezier points - // exclude endpoints - - float capMaxDist = 4 * capRadius * capRadius; //(2 * CapRadius)^2 - - if ((from - localPoint).sqrMagnitude <= capMaxDist || - (to - localPoint).sqrMagnitude <= capMaxDist) - { - Profiler.EndSample(); - return false; - } - - var allPoints = m_RenderPoints; - - if (allPoints.Count > 0) - { - //we use squareDistance to avoid sqrts - float distance = (allPoints[0] - localPoint).sqrMagnitude; - for (var i = 0; i < allPoints.Count - 1; i++) - { - Vector2 currentPoint = allPoints[i]; - Vector2 nextPoint = allPoints[i + 1]; - - float distanceNext = (nextPoint - localPoint).sqrMagnitude; - float distanceLine = (currentPoint - nextPoint).sqrMagnitude; - if (distance < distanceLine && distanceNext < distanceLine - ) // the point is somewhere between the two points - { - //https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line - if (Mathf.Abs((nextPoint.y - currentPoint.y) * localPoint.x - - (nextPoint.x - currentPoint.x) * localPoint.y + nextPoint.x * currentPoint.y - - nextPoint.y * currentPoint.x) / Mathf.Sqrt(distanceLine) < interceptWidth) - { - Profiler.EndSample(); - return true; - } - } - - distance = distanceNext; - } - } - - Profiler.EndSample(); - return false; - } - - public override bool Overlaps(Rect rect) - { - if (base.Overlaps(rect)) - { - for (int a = 0; a < m_RenderPoints.Count - 1; a++) - { - if (RectUtils.IntersectsSegment(rect, m_RenderPoints[a], m_RenderPoints[a + 1])) - return true; - } - } - - return false; - } - - protected virtual void PointsChanged() - { - m_ControlPointsDirty = true; - MarkDirtyRepaint(); - } - - // The points that will be rendered. Expressed in coordinates local to the element. - List m_RenderPoints = new List(); - - static bool Approximately(Vector2 v1, Vector2 v2) - { - return Mathf.Approximately(v1.x, v2.x) && Mathf.Approximately(v1.y, v2.y); - } - - public virtual void UpdateLayout() - { - if (parent == null) return; - if (m_ControlPointsDirty == false) return; - - - ComputeControlPoints(); // Computes the control points in parent ( graph ) coordinates - ComputeLayout(); // Update the element layout based on the control points. - m_ControlPointsDirty = false; - } - - private List lastLocalControlPoints = new List(); - - void RenderStraightLines(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) - { - float safeSpan = outputOrientation == Orientation.Horizontal - ? Mathf.Abs((p1.x + k_EdgeLengthFromPort) - (p4.x - k_EdgeLengthFromPort)) - : Mathf.Abs((p1.y + k_EdgeLengthFromPort) - (p4.y - k_EdgeLengthFromPort)); - - float safeSpan3 = safeSpan / k_EdgeStraightLineSegmentDivisor; - float nodeToP2Dist = Mathf.Min(safeSpan3, k_EdgeTurnDiameter); - nodeToP2Dist = Mathf.Max(0, nodeToP2Dist); - - var offset = outputOrientation == Orientation.Horizontal - ? new Vector2(k_EdgeTurnDiameter - nodeToP2Dist, 0) - : new Vector2(0, k_EdgeTurnDiameter - nodeToP2Dist); - - m_RenderPoints.Add(p1); - m_RenderPoints.Add(p2 - offset); - m_RenderPoints.Add(p3 + offset); - m_RenderPoints.Add(p4); - } - - protected virtual void UpdateRenderPoints() - { - ComputeControlPoints(); // This should have been updated before : make sure anyway. - - if (m_RenderPointsDirty == false && m_ControlPoints != null) - { - return; - } - - Vector2 p1 = parent.ChangeCoordinatesTo(this, m_ControlPoints[0]); - Vector2 p2 = parent.ChangeCoordinatesTo(this, m_ControlPoints[1]); - Vector2 p3 = parent.ChangeCoordinatesTo(this, m_ControlPoints[2]); - Vector2 p4 = parent.ChangeCoordinatesTo(this, m_ControlPoints[3]); - - // Only compute this when the "local" points have actually changed - if (lastLocalControlPoints.Count == 4) - { - if (Approximately(p1, lastLocalControlPoints[0]) && - Approximately(p2, lastLocalControlPoints[1]) && - Approximately(p3, lastLocalControlPoints[2]) && - Approximately(p4, lastLocalControlPoints[3])) - { - m_RenderPointsDirty = false; - return; - } - } - - Profiler.BeginSample("EdgeControl.UpdateRenderPoints"); - lastLocalControlPoints.Clear(); - lastLocalControlPoints.Add(p1); - lastLocalControlPoints.Add(p2); - lastLocalControlPoints.Add(p3); - lastLocalControlPoints.Add(p4); - m_RenderPointsDirty = false; - m_MeshDirty = true; - - m_RenderPoints.Clear(); - - float diameter = k_EdgeTurnDiameter; - - // We have to handle a special case of the edge when it is a straight line, but not - // when going backwards in space (where the start point is in front in y to the end point). - // We do this by turning the line into 3 linear segments with no curves. This also - // avoids possible NANs in later angle calculations. - bool sameOrientations = outputOrientation == inputOrientation; - if (sameOrientations && - ((outputOrientation == Orientation.Horizontal && Mathf.Abs(p1.y - p4.y) < 2 && p1.x + k_EdgeLengthFromPort < p4.x - k_EdgeLengthFromPort) || - (outputOrientation == Orientation.Vertical && Mathf.Abs(p1.x - p4.x) < 2 && p1.y + k_EdgeLengthFromPort < p4.y - k_EdgeLengthFromPort))) - { - RenderStraightLines(p1, p2, p3, p4); - Profiler.EndSample(); - return; - } - - bool renderBothCorners = true; - - EdgeCornerSweepValues corner1 = GetCornerSweepValues(p1, p2, p3, diameter, Direction.Output); - EdgeCornerSweepValues corner2 = GetCornerSweepValues(p2, p3, p4, diameter, Direction.Input); - - if (!ValidateCornerSweepValues(ref corner1, ref corner2)) - { - if (sameOrientations) - { - RenderStraightLines(p1, p2, p3, p4); - Profiler.EndSample(); - return; - } - - renderBothCorners = false; - - //we try to do it with a single corner instead - Vector2 px = (outputOrientation == Orientation.Horizontal) ? new Vector2(p4.x, p1.y) : new Vector2(p1.x, p4.y); - - corner1 = GetCornerSweepValues(p1, px, p4, diameter, Direction.Output); - } - - m_RenderPoints.Add(p1); - - if (!sameOrientations && renderBothCorners) - { - //if the 2 corners or endpoints are too close, the corner sweep angle calculations can't handle different orientations - float minDistance = 2 * diameter * diameter; - if ((p3 - p2).sqrMagnitude < minDistance || - (p4 - p1).sqrMagnitude < minDistance) - { - Vector2 px = (p2 + p3) * 0.5f; - corner1 = GetCornerSweepValues(p1, px, p4, diameter, Direction.Output); - renderBothCorners = false; - } - } - - GetRoundedCornerPoints(m_RenderPoints, corner1, Direction.Output); - if (renderBothCorners) - GetRoundedCornerPoints(m_RenderPoints, corner2, Direction.Input); - - m_RenderPoints.Add(p4); - Profiler.EndSample(); - } - - private bool ValidateCornerSweepValues(ref EdgeCornerSweepValues corner1, ref EdgeCornerSweepValues corner2) - { - // Get the midpoint between the two corner circle centers. - Vector2 circlesMidpoint = (corner1.circleCenter + corner2.circleCenter) / 2; - - // Find the angle to the corner circles midpoint so we can compare it to the sweep angles of each corner. - Vector2 p2CenterToCross1 = corner1.circleCenter - corner1.crossPoint1; - Vector2 p2CenterToCirclesMid = corner1.circleCenter - circlesMidpoint; - double angleToCirclesMid = outputOrientation == Orientation.Horizontal - ? Math.Atan2(p2CenterToCross1.y, p2CenterToCross1.x) - Math.Atan2(p2CenterToCirclesMid.y, p2CenterToCirclesMid.x) - : Math.Atan2(p2CenterToCross1.x, p2CenterToCross1.y) - Math.Atan2(p2CenterToCirclesMid.x, p2CenterToCirclesMid.y); - - if (double.IsNaN(angleToCirclesMid)) - return false; - - // We need the angle to the circles midpoint to match the turn direction of the first corner's sweep angle. - angleToCirclesMid = Math.Sign(angleToCirclesMid) * 2 * Mathf.PI - angleToCirclesMid; - if (Mathf.Abs((float)angleToCirclesMid) > 1.5 * Mathf.PI) - angleToCirclesMid = -1 * Math.Sign(angleToCirclesMid) * 2 * Mathf.PI + angleToCirclesMid; - - // Calculate the maximum sweep angle so that both corner sweeps and with the tangents of the 2 circles meeting each other. - float h = p2CenterToCirclesMid.magnitude; - float p2AngleToMidTangent = Mathf.Acos(corner1.radius / h); - - if (double.IsNaN(p2AngleToMidTangent)) - return false; - - float maxSweepAngle = Mathf.Abs((float)corner1.sweepAngle) - p2AngleToMidTangent * 2; - - // If the angle to the circles midpoint is within the sweep angle, we need to apply our maximum sweep angle - // calculated above, otherwise the maximum sweep angle is irrelevant. - if (Mathf.Abs((float)angleToCirclesMid) < Mathf.Abs((float)corner1.sweepAngle)) - { - corner1.sweepAngle = Math.Sign(corner1.sweepAngle) * Mathf.Min(maxSweepAngle, Mathf.Abs((float)corner1.sweepAngle)); - corner2.sweepAngle = Math.Sign(corner2.sweepAngle) * Mathf.Min(maxSweepAngle, Mathf.Abs((float)corner2.sweepAngle)); - } - - return true; - } - - private EdgeCornerSweepValues GetCornerSweepValues( - Vector2 p1, Vector2 cornerPoint, Vector2 p2, float diameter, Direction closestPortDirection) - { - EdgeCornerSweepValues corner = new EdgeCornerSweepValues(); - - // Calculate initial radius. This radius can change depending on the sharpness of the corner. - corner.radius = diameter / 2; - - // Calculate vectors from p1 to cornerPoint. - Vector2 d1Corner = (cornerPoint - p1).normalized; - Vector2 d1 = d1Corner * diameter; - float dx1 = d1.x; - float dy1 = d1.y; - - // Calculate vectors from p2 to cornerPoint. - Vector2 d2Corner = (cornerPoint - p2).normalized; - Vector2 d2 = d2Corner * diameter; - float dx2 = d2.x; - float dy2 = d2.y; - - // Calculate the angle of the corner (divided by 2). - float angle = (float)(Math.Atan2(dy1, dx1) - Math.Atan2(dy2, dx2)) / 2; - - // Calculate the length of the segment between the cornerPoint and where - // the corner circle with given radius meets the line. - float tan = (float)Math.Abs(Math.Tan(angle)); - float segment = corner.radius / tan; - - // If the segment is larger than the diameter, we need to cap the segment - // to the diameter and reduce the radius to match the segment. This is what - // makes the corner turn radii get smaller as the edge corners get tighter. - if (segment > diameter) - { - segment = diameter; - corner.radius = diameter * tan; - } - - // Calculate both cross points (where the circle touches the p1-cornerPoint line - // and the p2-cornerPoint line). - corner.crossPoint1 = cornerPoint - (d1Corner * segment); - corner.crossPoint2 = cornerPoint - (d2Corner * segment); - - // Calculation of the coordinates of the circle center. - corner.circleCenter = GetCornerCircleCenter(cornerPoint, corner.crossPoint1, corner.crossPoint2, segment, corner.radius); - - // Calculate the starting and ending angles. - corner.startAngle = Math.Atan2(corner.crossPoint1.y - corner.circleCenter.y, corner.crossPoint1.x - corner.circleCenter.x); - corner.endAngle = Math.Atan2(corner.crossPoint2.y - corner.circleCenter.y, corner.crossPoint2.x - corner.circleCenter.x); - - // Get the full sweep angle from the starting and ending angles. - corner.sweepAngle = corner.endAngle - corner.startAngle; - - // If we are computing the second corner (into the input port), we want to start - // the sweep going backwards. - if (closestPortDirection == Direction.Input) - { - double endAngle = corner.endAngle; - corner.endAngle = corner.startAngle; - corner.startAngle = endAngle; - } - - // Validate the sweep angle so it turns into the correct direction. - if (corner.sweepAngle > Math.PI) - corner.sweepAngle = -2 * Math.PI + corner.sweepAngle; - else if (corner.sweepAngle < -Math.PI) - corner.sweepAngle = 2 * Math.PI + corner.sweepAngle; - - return corner; - } - - private Vector2 GetCornerCircleCenter(Vector2 cornerPoint, Vector2 crossPoint1, Vector2 crossPoint2, float segment, float radius) - { - float dx = cornerPoint.x * 2 - crossPoint1.x - crossPoint2.x; - float dy = cornerPoint.y * 2 - crossPoint1.y - crossPoint2.y; - - var cornerToCenterVector = new Vector2(dx, dy); - - float L = cornerToCenterVector.magnitude; - - if (Mathf.Approximately(L, 0)) - { - return cornerPoint; - } - - float d = new Vector2(segment, radius).magnitude; - float factor = d / L; - - return new Vector2(cornerPoint.x - cornerToCenterVector.x * factor, cornerPoint.y - cornerToCenterVector.y * factor); - } - - private void GetRoundedCornerPoints(List points, EdgeCornerSweepValues corner, Direction closestPortDirection) - { - // Calculate the number of points that will sample the arc from the sweep angle. - int pointsCount = Mathf.CeilToInt((float)Math.Abs(corner.sweepAngle * k_EdgeSweepResampleRatio)); - int sign = Math.Sign(corner.sweepAngle); - bool backwards = (closestPortDirection == Direction.Input); - - for (int i = 0; i < pointsCount; ++i) - { - // If we are computing the second corner (into the input port), the sweep is going backwards - // but we still need to add the points to the list in the correct order. - float sweepIndex = backwards ? i - pointsCount : i; - - double sweepedAngle = corner.startAngle + sign * sweepIndex / k_EdgeSweepResampleRatio; - - var pointX = (float)(corner.circleCenter.x + Math.Cos(sweepedAngle) * corner.radius); - var pointY = (float)(corner.circleCenter.y + Math.Sin(sweepedAngle) * corner.radius); - - // Check if we overlap the previous point. If we do, we skip this point so that we - // don't cause the edge polygons to twist. - if (i == 0 && backwards) - { - if (outputOrientation == Orientation.Horizontal) - { - if (corner.sweepAngle < 0 && points[points.Count - 1].y > pointY) - continue; - else if (corner.sweepAngle >= 0 && points[points.Count - 1].y < pointY) - continue; - } - else - { - if (corner.sweepAngle < 0 && points[points.Count - 1].x < pointX) - continue; - else if (corner.sweepAngle >= 0 && points[points.Count - 1].x > pointX) - continue; - } - } - - points.Add(new Vector2(pointX, pointY)); - } - } - - private void AssignControlPoint(ref Vector2 destination, Vector2 newValue) - { - if (!Approximately(destination, newValue)) - { - destination = newValue; - m_RenderPointsDirty = true; - } - } - - protected virtual void ComputeControlPoints() - { - if (m_ControlPointsDirty == false) return; - - Profiler.BeginSample("EdgeControl.ComputeControlPoints"); - - float offset = k_EdgeLengthFromPort + k_EdgeTurnDiameter; - - // This is to ensure we don't have the edge extending - // left and right by the offset right when the `from` - // and `to` are on top of each other. - float fromToDistance = (to - from).magnitude; - offset = Mathf.Min(offset, fromToDistance * 2); - offset = Mathf.Max(offset, k_EdgeTurnDiameter); - - if (m_ControlPoints == null || m_ControlPoints.Length != 4) - m_ControlPoints = new Vector2[4]; - - AssignControlPoint(ref m_ControlPoints[0], from); - - if (outputOrientation == Orientation.Horizontal) - AssignControlPoint(ref m_ControlPoints[1], new Vector2(from.x + offset, from.y)); - else - AssignControlPoint(ref m_ControlPoints[1], new Vector2(from.x, from.y + offset)); - - if (inputOrientation == Orientation.Horizontal) - AssignControlPoint(ref m_ControlPoints[2], new Vector2(to.x - offset, to.y)); - else - AssignControlPoint(ref m_ControlPoints[2], new Vector2(to.x, to.y - offset)); - - AssignControlPoint(ref m_ControlPoints[3], to); - Profiler.EndSample(); - } - - void ComputeLayout() - { - Profiler.BeginSample("EdgeControl.ComputeLayout"); - Vector2 to = m_ControlPoints[m_ControlPoints.Length - 1]; - Vector2 from = m_ControlPoints[0]; - - Rect rect = new Rect(Vector2.Min(to, from), new Vector2(Mathf.Abs(from.x - to.x), Mathf.Abs(from.y - to.y))); - - // Make sure any control points (including tangents, are included in the rect) - for (int i = 1; i < m_ControlPoints.Length - 1; ++i) - { - if (!rect.Contains(m_ControlPoints[i])) - { - Vector2 pt = m_ControlPoints[i]; - rect.xMin = Math.Min(rect.xMin, pt.x); - rect.yMin = Math.Min(rect.yMin, pt.y); - rect.xMax = Math.Max(rect.xMax, pt.x); - rect.yMax = Math.Max(rect.yMax, pt.y); - } - } - - if (m_GraphView == null) - { - m_GraphView = GetFirstAncestorOfType(); - } - - //Make sure that we have the place to display Edges with EdgeControl.k_MinEdgeWidth at the lowest level of zoom. - float margin = Mathf.Max(edgeWidth * 0.5f + 1, EdgeControl.k_MinEdgeWidth / m_GraphView.minScale); - - rect.xMin -= margin; - rect.yMin -= margin; - rect.width += margin * 2; - rect.height += margin * 2; - - if (layout != rect) - { - layout = rect; - m_RenderPointsDirty = true; - } - Profiler.EndSample(); - } - - static Material s_LineMat; - - static Material lineMat - { - get - { - if (s_LineMat == null) - s_LineMat = new Material(EditorGUIUtility.LoadRequired("GraphView/AAEdge.shader") as Shader); - return s_LineMat; - } - } - - protected virtual void DrawEdge(IStylePainter painter) - { - var stylePainter = (IStylePainterInternal)painter; - stylePainter.DrawImmediate(Draw); - } - - void Draw() - { - if (edgeWidth <= 0) - return; - - UpdateRenderPoints(); - - Vector2[] points = controlPoints; - - Color inputColor = this.inputColor; - Color outputColor = this.outputColor; - - float realWidth = edgeWidth; - if (realWidth * m_GraphView.scale < k_MinEdgeWidth) - { - realWidth = k_MinEdgeWidth / m_GraphView.scale; - - // make up for bigger edge by fading it. - inputColor.a = outputColor.a = edgeWidth / realWidth; - } - - if (m_MeshDirty || m_Mesh == null) - { - m_MeshDirty = false; - - RecomputeMesh(); - } - - // Send the view zoom factor so that the antialias width do not grow when zooming in. - lineMat.SetFloat("_ZoomFactor", m_GraphView.scale * realWidth / edgeWidth * EditorGUIUtility.pixelsPerPoint); - - // Send the view zoom correction so that the vertex shader can scale the edge triangles when below m_MinWidth. - lineMat.SetFloat("_ZoomCorrection", realWidth / edgeWidth); - - lineMat.SetColor("_InputColor", (QualitySettings.activeColorSpace == ColorSpace.Linear) ? inputColor.gamma : inputColor); - lineMat.SetColor("_OutputColor", (QualitySettings.activeColorSpace == ColorSpace.Linear) ? outputColor.gamma : outputColor); - - lineMat.SetPass(0); - Graphics.DrawMeshNow(m_Mesh, Matrix4x4.identity); - } - - private void RecomputeMesh() - { - int cpt = m_RenderPoints.Count; - - float polyLineLength = 0; - - for (int i = 1; i < cpt; ++i) - { - polyLineLength += (m_RenderPoints[i - 1] - m_RenderPoints[i]).sqrMagnitude; - } - - if (m_Mesh == null) - { - m_Mesh = new Mesh(); - m_Mesh.hideFlags = HideFlags.HideAndDontSave; - } - - Vector3[] vertices = m_Mesh.vertices; - Vector2[] uvs = m_Mesh.uv; - Vector3[] normals = m_Mesh.normals; - bool newIndices = false; - int wantedLength = (cpt) * 2; - if (vertices == null || vertices.Length != wantedLength) - { - vertices = new Vector3[wantedLength]; - uvs = new Vector2[wantedLength]; - normals = new Vector3[wantedLength]; - newIndices = true; - m_Mesh.triangles = new int[] {}; - } - - float halfWidth = edgeWidth * 0.5f; - - float vertexHalfWidth = halfWidth + 2; - - float currentLength = 0; - - Vector2 unitPreviousSegment = Vector2.zero; - for (int i = 0; i < cpt; ++i) - { - Vector2 dir; - Vector2 unitNextSegment = Vector2.zero; - Vector2 nextSegment = Vector2.zero; - - if (i < cpt - 1) - { - nextSegment = (m_RenderPoints[i + 1] - m_RenderPoints[i]); - unitNextSegment = nextSegment.normalized; - } - - - if (i > 0 && i < cpt - 1) - { - dir = unitPreviousSegment + unitNextSegment; - dir.Normalize(); - } - else if (i > 0) - { - dir = unitPreviousSegment; - } - else - { - dir = unitNextSegment; - } - - Vector2 norm = new Vector3(dir.y, -dir.x, 0); - - Vector2 border = -norm * vertexHalfWidth; - - int index = i * 2; - uvs[index] = new Vector2(-vertexHalfWidth, halfWidth); - vertices[index] = m_RenderPoints[i]; - // normals store the Vector2 normal in x,y and the progress in the edge in z ( which drive the gradient ). - normals[index] = new Vector3(-border.x, -border.y, currentLength / polyLineLength); - - uvs[index + 1] = new Vector2(vertexHalfWidth, halfWidth); - vertices[index + 1] = m_RenderPoints[i]; - normals[index + 1] = new Vector3(border.x, border.y, currentLength / polyLineLength); - - if (i < cpt - 2) - { - currentLength += nextSegment.sqrMagnitude; - } - else - { - currentLength = polyLineLength; - } - - unitPreviousSegment = unitNextSegment; - } - - m_Mesh.vertices = vertices; - m_Mesh.normals = normals; - m_Mesh.uv = uvs; - - if (newIndices) - { - //fill triangle indices as it is a triangle strip - int[] indices = new int[(wantedLength - 2) * 3]; - - for (int i = 0; i < wantedLength - 2; ++i) - { - int index = i * 3; - if ((i & 0x01) == 0) - { - indices[index] = i; - indices[index + 1] = i + 1; - indices[index + 2] = i + 2; - } - else - { - indices[index] = i + 1; - indices[index + 1] = i; - indices[index + 2] = i + 2; - } - } - - m_Mesh.triangles = indices; - } - - m_Mesh.RecalculateBounds(); - } - - void OnLeavePanel(DetachFromPanelEvent e) - { - if (m_Mesh != null) - { - UnityEngine.Object.DestroyImmediate(m_Mesh); - m_Mesh = null; - } - } - } -} diff --git a/Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/Blackboard.cs b/Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/Blackboard.cs deleted file mode 100644 index e70e1bd9c9..0000000000 --- a/Modules/GraphViewEditor/ExperimentalUIElements/Elements/Blackboard/Blackboard.cs +++ /dev/null @@ -1,141 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -using System; -using System.Collections.Generic; -using UnityEngine; -using UnityEngine.Experimental.UIElements; -using UnityEngine.Experimental.UIElements.StyleEnums; - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - public class Blackboard : GraphElement - { - private const int k_DefaultWidth = 200; - private const float k_DefaultHeight = 400; - private VisualElement m_MainContainer; - private VisualElement m_Root; - private Label m_TitleLabel; - private Label m_SubTitleLabel; - private ScrollView m_ScrollView; - private VisualElement m_ContentContainer; - private VisualElement m_HeaderItem; - private Button m_AddButton; - private bool m_Scrollable = true; - internal static readonly string StyleSheetPath = "StyleSheets/GraphViewExperimental/Blackboard.uss"; - - public Action addItemRequested { get; set; } - public Action moveItemRequested { get; set; } - public Action editTextRequested { get; set; } - - public override string title - { - get { return m_TitleLabel.text; } - set { m_TitleLabel.text = value; } - } - - public string subTitle - { - get { return m_SubTitleLabel.text; } - set { m_SubTitleLabel.text = value; } - } - - public override VisualElement contentContainer { get { return m_ContentContainer; } } - - public bool scrollable - { - get - { - return m_Scrollable; - } - set - { - if (m_Scrollable == value) - return; - - m_Scrollable = value; - - if (m_Scrollable) - { - if (m_ScrollView == null) - { - m_ScrollView = new ScrollView(); - } - - // Remove the sections container from the content item and add it to the scrollview - m_ContentContainer.RemoveFromHierarchy(); - m_Root.Add(m_ScrollView); - m_ScrollView.Add(m_ContentContainer); - style.positionType = PositionType.Manual; // As both the width and height can be changed by the user using a resizer - - // If the current the current geometry is invalid then set a default size - - if (layout.width == 0 || layout.height == 0) - { - layout = new Rect(layout.x, layout.y, layout.width == 0 ? k_DefaultWidth : layout.width, layout.height == 0 ? k_DefaultHeight : layout.height); - } - - AddToClassList("scrollable"); - } - else - { - if (m_ScrollView != null) - { - // Remove the sections container from the scrollview and add it to the content item - style.positionType = PositionType.Absolute; // As the height is automatically computed from the content but the width can be changed by the user using a resizer - m_ScrollView.RemoveFromHierarchy(); - m_ContentContainer.RemoveFromHierarchy(); - m_Root.Add(m_ContentContainer); - } - RemoveFromClassList("scrollable"); - } - } - } - - public Blackboard() - { - var tpl = EditorGUIUtility.Load("UXML/GraphViewExperimental/Blackboard.uxml") as VisualTreeAsset; - AddStyleSheetPath(StyleSheetPath); - - m_MainContainer = tpl.CloneTree(null); - m_MainContainer.AddToClassList("mainContainer"); - - m_Root = m_MainContainer.Q("content"); - - m_HeaderItem = m_MainContainer.Q("header"); - m_HeaderItem.AddToClassList("blackboardHeader"); - - m_AddButton = m_MainContainer.Q(name: "addButton") as Button; - m_AddButton.clickable.clicked += () => { - if (addItemRequested != null) - { - addItemRequested(this); - } - }; - - m_TitleLabel = m_MainContainer.Q