diff --git a/Editor/Mono/2D/Interface/IAssetDatabase.cs b/Editor/Mono/2D/Interface/IAssetDatabase.cs deleted file mode 100644 index 60b0d4ec7f..0000000000 --- a/Editor/Mono/2D/Interface/IAssetDatabase.cs +++ /dev/null @@ -1,28 +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 UnityEditor; - -namespace UnityEditor.U2D.Interface -{ - internal interface IAssetDatabase - { - string GetAssetPath(Object o); - AssetImporter GetAssetImporterFromPath(string path); - } - - internal class AssetDatabaseSystem : IAssetDatabase - { - public string GetAssetPath(Object o) - { - return UnityEditor.AssetDatabase.GetAssetPath(o); - } - - public AssetImporter GetAssetImporterFromPath(string path) - { - return UnityEditor.AssetImporter.GetAtPath(path); - } - } -} diff --git a/Editor/Mono/2D/Interface/IEvent.cs b/Editor/Mono/2D/Interface/IEvent.cs deleted file mode 100644 index 6db0d4c449..0000000000 --- a/Editor/Mono/2D/Interface/IEvent.cs +++ /dev/null @@ -1,105 +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 UnityEvent = UnityEngine.Event; - -// We are putting this in the Editor folder for now since on SpriteEditorWindow et al. are using it -namespace UnityEngine.U2D.Interface -{ - internal interface IEvent - { - EventType type { get; } - string commandName { get; } - bool control { get; } - bool alt { get; } - bool shift { get; } - KeyCode keyCode { get; } - Vector2 mousePosition { get; } - int button { get; } - EventModifiers modifiers { get; } - EventType GetTypeForControl(int id); - - void Use(); - } - - internal class Event : IEvent - { - UnityEvent m_Event; - - public Event() - { - m_Event = UnityEvent.current; - } - - public EventType type - { - get { return m_Event.type; } - } - - public string commandName - { - get { return m_Event.commandName; } - } - - public bool control - { - get { return m_Event.control; } - } - - public bool alt - { - get { return m_Event.alt; } - } - - public bool shift - { - get { return m_Event.shift; } - } - - public KeyCode keyCode - { - get { return m_Event.keyCode; } - } - - public Vector2 mousePosition - { - get { return m_Event.mousePosition; } - } - - public int button - { - get { return m_Event.button; } - } - - public void Use() - { - m_Event.Use(); - } - - public EventModifiers modifiers - { - get { return m_Event.modifiers; } - } - - public EventType GetTypeForControl(int id) - { - return m_Event.GetTypeForControl(id); - } - } - - internal interface IEventSystem - { - IEvent current { get; } - } - - internal class EventSystem : IEventSystem - { - public IEvent current - { - get { return new Event(); } - } - } -} diff --git a/Editor/Mono/2D/Interface/IGL.cs b/Editor/Mono/2D/Interface/IGL.cs deleted file mode 100644 index a6e8726b8e..0000000000 --- a/Editor/Mono/2D/Interface/IGL.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 UnityEngine; - -namespace UnityEngine.U2D.Interface -{ - internal interface IGL - { - void PushMatrix(); - void PopMatrix(); - void MultMatrix(Matrix4x4 m); - void Begin(int mode); - void End(); - void Color(Color c); - void Vertex(Vector3 v); - } - - internal class GLSystem : IGL - { - static IGL m_GLSystem; - internal static void SetSystem(IGL system) - { - m_GLSystem = system; - } - - internal static IGL GetSystem() - { - if (m_GLSystem == null) - m_GLSystem = new GLSystem(); - return m_GLSystem; - } - - public void PushMatrix() - { - GL.PushMatrix(); - } - - public void PopMatrix() - { - GL.PopMatrix(); - } - - public void MultMatrix(Matrix4x4 m) - { - GL.MultMatrix(m); - } - - public void Begin(int mode) - { - GL.Begin(mode); - } - - public void End() - { - GL.End(); - } - - public void Color(Color c) - { - GL.Color(c); - } - - public void Vertex(Vector3 v) - { - GL.Vertex(v); - } - } -} diff --git a/Editor/Mono/2D/Interface/IGUIUtility.cs b/Editor/Mono/2D/Interface/IGUIUtility.cs deleted file mode 100644 index c5c0ee6eae..0000000000 --- a/Editor/Mono/2D/Interface/IGUIUtility.cs +++ /dev/null @@ -1,51 +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 UnityEngine -{ - internal interface IGUIUtility - { - int GetPermanentControlID(); - int hotControl { get; set; } - int keyboardControl { get; set; } - int GetControlID(int hint, FocusType focus); - } - - internal class GUIUtilitySystem : IGUIUtility - { - public int GetPermanentControlID() - { - return GUIUtility.GetPermanentControlID(); - } - - public int hotControl - { - get - { - return GUIUtility.hotControl; - } - set - { - GUIUtility.hotControl = value; - } - } - - public int keyboardControl - { - get - { - return GUIUtility.keyboardControl; - } - set - { - GUIUtility.keyboardControl = value; - } - } - - public int GetControlID(int hint, FocusType focus) - { - return GUIUtility.GetControlID(hint, focus); - } - } -} diff --git a/Editor/Mono/2D/Interface/IHandles.cs b/Editor/Mono/2D/Interface/IHandles.cs deleted file mode 100644 index bb0cec37c1..0000000000 --- a/Editor/Mono/2D/Interface/IHandles.cs +++ /dev/null @@ -1,79 +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 UnityHandles = UnityEditor.Handles; -using UnityTexture2D = UnityEngine.Texture2D; -using UnityEngine.U2D.Interface; - -namespace UnityEditor.U2D.Interface -{ - internal interface IHandles - { - Color color { get; set; } - Matrix4x4 matrix { get; set; } - - Vector3[] MakeBezierPoints(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, int division); - - void DrawAAPolyLine(ITexture2D lineTex, float width, params Vector3[] points); - void DrawAAPolyLine(ITexture2D lineTex, params Vector3[] points); - - void DrawLine(Vector3 p1, Vector3 p2); - - void SetDiscSectionPoints(Vector3[] dest, Vector3 center, Vector3 normal, Vector3 from, float angle, float radius); - } - - internal class HandlesSystem : IHandles - { - static IHandles m_System; - - static public void SetSystem(IHandles system) - { - m_System = system; - } - - static public IHandles GetSystem() - { - if (m_System == null) - m_System = new HandlesSystem(); - return m_System; - } - - public Color color - { - get { return UnityHandles.color; } - set { UnityHandles.color = value; } - } - public Matrix4x4 matrix - { - get { return UnityHandles.matrix; } - set { UnityHandles.matrix = value; } - } - - public Vector3[] MakeBezierPoints(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, int division) - { - return UnityHandles.MakeBezierPoints(startPosition, endPosition, startTangent, endTangent, division); - } - - public void DrawAAPolyLine(ITexture2D lineTex, float width, params Vector3[] points) - { - UnityHandles.DrawAAPolyLine((UnityTexture2D)lineTex, width, points); - } - - public void DrawAAPolyLine(ITexture2D lineTex, params Vector3[] points) - { - UnityHandles.DrawAAPolyLine((UnityTexture2D)lineTex, points); - } - - public void DrawLine(Vector3 p1, Vector3 p2) - { - UnityHandles.DrawLine(p1, p2); - } - - public void SetDiscSectionPoints(Vector3[] dest, Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) - { - UnityHandles.SetDiscSectionPoints(dest, center, normal, from, angle, radius); - } - } -} diff --git a/Editor/Mono/2D/Interface/ITexture.cs b/Editor/Mono/2D/Interface/ITexture.cs deleted file mode 100644 index 41f09c6733..0000000000 --- a/Editor/Mono/2D/Interface/ITexture.cs +++ /dev/null @@ -1,146 +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 UnityTexture2D = UnityEngine.Texture2D; -using System; - -// We are putting this in the Editor folder for now since on SpriteEditorWindow et al. are using it -namespace UnityEngine.U2D.Interface -{ - internal abstract class ITexture2D - { - abstract public int width { get; } - abstract public int height { get; } - abstract public TextureFormat format { get; } - abstract public Color32[] GetPixels32(); - abstract public FilterMode filterMode { get; set; } - abstract public string name { get; } - abstract public void SetPixels(Color[] c); - abstract public void Apply(); - abstract public float mipMapBias { get; } - - public static bool operator==(ITexture2D t1, ITexture2D t2) - { - if (object.ReferenceEquals(t1, null)) - { - return object.ReferenceEquals(t2, null) || t2 == null; - } - - return t1.Equals(t2); - } - - public static bool operator!=(ITexture2D t1, ITexture2D t2) - { - if (object.ReferenceEquals(t1, null)) - { - return !object.ReferenceEquals(t2, null) && t2 != null; - } - - return !t1.Equals(t2); - } - - override public bool Equals(object other) - { - throw new NotImplementedException(); - } - - override public int GetHashCode() - { - throw new NotImplementedException(); - } - - public static implicit operator UnityEngine.Object(ITexture2D t) - { - return object.ReferenceEquals(t, null) ? null : t.ToUnityObject(); - } - - public static implicit operator UnityEngine.Texture2D(ITexture2D t) - { - return object.ReferenceEquals(t, null) ? null : t.ToUnityTexture(); - } - - abstract protected UnityEngine.Object ToUnityObject(); - abstract protected UnityEngine.Texture2D ToUnityTexture(); - } - - internal class Texture2D : ITexture2D - { - UnityTexture2D m_Texture; - - public Texture2D(UnityTexture2D texture) - { - m_Texture = texture; - } - - override public int width - { - get { return m_Texture.width; } - } - - override public int height - { - get { return m_Texture.height; } - } - - override public TextureFormat format - { - get { return m_Texture.format; } - } - - override public Color32[] GetPixels32() - { - return m_Texture.GetPixels32(); - } - - override public FilterMode filterMode - { - get { return m_Texture.filterMode; } - set { m_Texture.filterMode = value; } - } - - override public float mipMapBias - { - get { return m_Texture.mipMapBias; } - } - - override public string name - { - get { return m_Texture.name; } - } - - public override bool Equals(object other) - { - Texture2D t = other as Texture2D; - if (object.ReferenceEquals(t, null)) - return m_Texture == null; - return m_Texture == t.m_Texture; - } - - public override int GetHashCode() - { - return m_Texture.GetHashCode(); - } - - public override void SetPixels(Color[] c) - { - m_Texture.SetPixels(c); - } - - public override void Apply() - { - m_Texture.Apply(); - } - - override protected UnityEngine.Object ToUnityObject() - { - return m_Texture; - } - - override protected UnityEngine.Texture2D ToUnityTexture() - { - return m_Texture; - } - } -} diff --git a/Editor/Mono/2D/Interface/IUndoSystem.cs b/Editor/Mono/2D/Interface/IUndoSystem.cs deleted file mode 100644 index 1cc598e095..0000000000 --- a/Editor/Mono/2D/Interface/IUndoSystem.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; - -namespace UnityEditor.U2D.Interface -{ - internal interface IUndoSystem - { - void RegisterUndoCallback(Undo.UndoRedoCallback undoCallback); - void UnregisterUndoCallback(Undo.UndoRedoCallback undoCallback); - void RegisterCompleteObjectUndo(ScriptableObject obj, string undoText); - void ClearUndo(ScriptableObject obj); - } - - internal class UndoSystem : IUndoSystem - { - public void RegisterUndoCallback(Undo.UndoRedoCallback undoCallback) - { - Undo.undoRedoPerformed += undoCallback; - } - - public void UnregisterUndoCallback(Undo.UndoRedoCallback undoCallback) - { - Undo.undoRedoPerformed -= undoCallback; - } - - public void RegisterCompleteObjectUndo(ScriptableObject so, string undoText) - { - if (so != null) - { - Undo.RegisterCompleteObjectUndo(so, undoText); - } - } - - public void ClearUndo(ScriptableObject so) - { - if (so != null) - { - Undo.ClearUndo(so); - } - } - } -} diff --git a/Editor/Mono/2D/SpriteAtlas/SpriteAtlasInspector.cs b/Editor/Mono/2D/SpriteAtlas/SpriteAtlasInspector.cs index 3ff20a742e..90218d3f3e 100644 --- a/Editor/Mono/2D/SpriteAtlas/SpriteAtlasInspector.cs +++ b/Editor/Mono/2D/SpriteAtlas/SpriteAtlasInspector.cs @@ -61,7 +61,8 @@ class Styles public readonly GUIContent variantMultiplierLabel = EditorGUIUtility.TrTextContent("Scale", "Down scale ratio."); public readonly GUIContent copyMasterButton = EditorGUIUtility.TrTextContent("Copy Master's Settings", "Copy all master's settings into this variant."); public readonly GUIContent packButton = EditorGUIUtility.TrTextContent("Pack Preview", "Pack this atlas."); - public readonly GUIContent disabledPackLabel = EditorGUIUtility.TrTextContent("Sprite Atlas packing is disabled. Enable it in Edit > Project Settings > Editor."); + + public readonly GUIContent disabledPackLabel = EditorGUIUtility.TrTextContent("Sprite Atlas packing is disabled. Enable it in Edit > Settings > Editor.", null, EditorGUIUtility.GetHelpIcon(MessageType.Info)); public readonly GUIContent packableListLabel = EditorGUIUtility.TrTextContent("Objects for Packing", "Only accept Folder, Sprite Sheet(Texture) and Sprite."); public readonly GUIContent notPowerOfTwoWarning = EditorGUIUtility.TrTextContent("This scale will produce a Sprite Atlas variant with a packed texture that is NPOT (non - power of two). This may cause visual artifacts in certain compression/texture formats."); @@ -310,7 +311,10 @@ public override void OnInspectorGUI() } else { - EditorGUILayout.HelpBox(s_Styles.disabledPackLabel.text, MessageType.Info); + if (GUILayout.Button(s_Styles.disabledPackLabel, EditorStyles.helpBox)) + { + SettingsWindow.OpenProjectSettings("Project/Editor"); + } } serializedObject.ApplyModifiedProperties(); diff --git a/Editor/Mono/Accessibility/UserAccessibilitySettings.cs b/Editor/Mono/Accessibility/UserAccessibilitySettings.cs deleted file mode 100644 index 9489dfa555..0000000000 --- a/Editor/Mono/Accessibility/UserAccessibilitySettings.cs +++ /dev/null @@ -1,46 +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.Accessibility -{ - internal enum ColorBlindCondition - { - Default, - Deuteranopia, - Protanopia, - Tritanopia, - } - - // NOTE: The preferences in this class are currently only exposed via a context menu in the ProfilerWindow - // these toggles need to instead be moved to e.g., the Preferences menu before they are used elsewhere - internal static class UserAccessiblitySettings - { - static UserAccessiblitySettings() - { - s_ColorBlindCondition = (ColorBlindCondition)EditorPrefs.GetInt(k_ColorBlindConditionPrefKey, (int)ColorBlindCondition.Default); - } - - private const string k_ColorBlindConditionPrefKey = "AccessibilityColorBlindCondition"; - - public static ColorBlindCondition colorBlindCondition - { - get { return s_ColorBlindCondition; } - set - { - if (s_ColorBlindCondition != value) - { - s_ColorBlindCondition = value; - EditorPrefs.SetInt(k_ColorBlindConditionPrefKey, (int)value); - if (colorBlindConditionChanged != null) - colorBlindConditionChanged(); - } - } - } - private static ColorBlindCondition s_ColorBlindCondition; - - public static Action colorBlindConditionChanged; - } -} diff --git a/Editor/Mono/Animation/AnimationClipSettings.bindings.cs b/Editor/Mono/Animation/AnimationClipSettings.bindings.cs deleted file mode 100644 index 3f31322e69..0000000000 --- a/Editor/Mono/Animation/AnimationClipSettings.bindings.cs +++ /dev/null @@ -1,41 +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.Runtime.InteropServices; -using UnityEngine; -using UnityEngine.Bindings; -using UnityEngine.Scripting; -using UnityEngine.Playables; -using UnityEngine.Scripting.APIUpdating; -using UnityEngine.Internal; - -namespace UnityEditor -{ - [NativeType(CodegenOptions.Custom, "MonoAnimationClipSettings")] - [NativeAsStruct] - [StructLayout(LayoutKind.Sequential)] - [RequiredByNativeCode] - public class AnimationClipSettings - { - public AnimationClip additiveReferencePoseClip; - public float additiveReferencePoseTime; - public float startTime; - public float stopTime; - public float orientationOffsetY; - public float level; - public float cycleOffset; - public bool hasAdditiveReferencePose; - public bool loopTime; - public bool loopBlend; - public bool loopBlendOrientation; - public bool loopBlendPositionY; - public bool loopBlendPositionXZ; - public bool keepOriginalOrientation; - public bool keepOriginalPositionY; - public bool keepOriginalPositionXZ; - public bool heightFromFeet; - public bool mirror; - } -} diff --git a/Editor/Mono/Animation/AnimationClipStats.bindings.cs b/Editor/Mono/Animation/AnimationClipStats.bindings.cs deleted file mode 100644 index ffe13b88f3..0000000000 --- a/Editor/Mono/Animation/AnimationClipStats.bindings.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.Bindings; -using UnityEngine.Scripting; -using UnityEngine.Playables; -using UnityEngine.Scripting.APIUpdating; -using UnityEngine.Internal; - -namespace UnityEditor -{ - // Must be kept in sync with AnimationClipStats in AnimationClipStats - internal struct AnimationClipStats - { - public int size; - public int positionCurves; - public int quaternionCurves; - public int eulerCurves; - public int scaleCurves; - public int muscleCurves; - public int genericCurves; - public int pptrCurves; - public int totalCurves; - public int constantCurves; - public int denseCurves; - public int streamCurves; - - public void Reset() - { - size = 0; - positionCurves = 0; - quaternionCurves = 0; - eulerCurves = 0; - scaleCurves = 0; - muscleCurves = 0; - genericCurves = 0; - pptrCurves = 0; - totalCurves = 0; - constantCurves = 0; - denseCurves = 0; - streamCurves = 0; - } - - public void Combine(AnimationClipStats other) - { - size += other.size; - positionCurves += other.positionCurves; - quaternionCurves += other.quaternionCurves; - eulerCurves += other.eulerCurves; - scaleCurves += other.scaleCurves; - muscleCurves += other.muscleCurves; - genericCurves += other.genericCurves; - pptrCurves += other.pptrCurves; - totalCurves += other.totalCurves; - constantCurves += other.constantCurves; - denseCurves += other.denseCurves; - streamCurves += other.streamCurves; - } - } -} diff --git a/Editor/Mono/Animation/AnimationMode.bindings.cs b/Editor/Mono/Animation/AnimationMode.bindings.cs index c3b411f482..2b30484c29 100644 --- a/Editor/Mono/Animation/AnimationMode.bindings.cs +++ b/Editor/Mono/Animation/AnimationMode.bindings.cs @@ -146,6 +146,9 @@ internal static void StartAnimationRecording() [NativeThrows] extern public static void AddPropertyModification(EditorCurveBinding binding, PropertyModification modification, bool keepPrefabOverride); + [NativeThrows] + extern public static void AddEditorCurveBinding([NotNull] GameObject gameObject, EditorCurveBinding binding); + [NativeThrows] extern internal static void AddTransformTR([NotNull] GameObject root, string path); diff --git a/Editor/Mono/Animation/AnimationUtility.bindings.cs b/Editor/Mono/Animation/AnimationUtility.bindings.cs index dd22c87e44..b2ede18a80 100644 --- a/Editor/Mono/Animation/AnimationUtility.bindings.cs +++ b/Editor/Mono/Animation/AnimationUtility.bindings.cs @@ -143,8 +143,14 @@ internal static EditorCurveBinding[] GetAnimatableBindings(ScriptableObject scri return Internal_GetScriptableObjectAnimatableBindings(scriptableObject); } + internal static EditorCurveBinding[] GetAdditionalAnimatorBindings(GameObject targetObject) + { + return Internal_GetAdditionalAnimatorBindings(targetObject); + } + extern private static EditorCurveBinding[] Internal_GetGameObjectAnimatableBindings([NotNull] GameObject targetObject, [NotNull] GameObject root); extern private static EditorCurveBinding[] Internal_GetScriptableObjectAnimatableBindings([NotNull] ScriptableObject scriptableObject); + extern private static EditorCurveBinding[] Internal_GetAdditionalAnimatorBindings([NotNull] GameObject targetObject); // Binds the property and returns the type of the bound value (Can be used to display special UI for it and to enforce correct drag and drop) // null if it can't be bound. diff --git a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopup.cs b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopup.cs index 84e4b40e80..7bece927e0 100644 --- a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopup.cs +++ b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopup.cs @@ -13,6 +13,11 @@ namespace UnityEditorInternal internal class AddCurvesPopup : EditorWindow { const float k_WindowPadding = 3; + const float k_SpaceForSlider = 16; + + const float k_WindowMaxWidth = 450; + const float k_WindowMinWidth = 240; + const float k_WindowFixedHeight = 250; internal static AnimationWindowState s_State; @@ -20,16 +25,25 @@ internal class AddCurvesPopup : EditorWindow private static long s_LastClosedTime; private static AddCurvesPopupHierarchy s_Hierarchy; - private static Vector2 windowSize = new Vector2(240, 250); - public delegate void OnNewCurveAdded(AddCurvesPopupPropertyNode node); private static OnNewCurveAdded NewCurveAddedCallback; + Vector2 GetWindowSize() + { + float contentWidth = s_Hierarchy.GetContentWidth(); + float width = Mathf.Clamp(contentWidth + k_SpaceForSlider + k_WindowPadding, k_WindowMinWidth, k_WindowMaxWidth); + return new Vector2(width, k_WindowFixedHeight); + } + void Init(Rect buttonRect) { + s_Hierarchy = new AddCurvesPopupHierarchy(); + s_Hierarchy.InitIfNeeded(this, new Rect(0, 0, k_WindowMinWidth, k_WindowFixedHeight)); + buttonRect = GUIUtility.GUIToScreenRect(buttonRect); - ShowAsDropDown(buttonRect, windowSize, new[] { PopupLocation.Right }); + + ShowAsDropDown(buttonRect, GetWindowSize(), new[] { PopupLocation.Right }); } void OnEnable() @@ -77,8 +91,7 @@ internal void OnGUI() if (Event.current.type == EventType.Layout) return; - if (s_Hierarchy == null) - s_Hierarchy = new AddCurvesPopupHierarchy(); + Vector2 windowSize = GetWindowSize(); Rect rect = new Rect(1, 1, windowSize.x - k_WindowPadding, windowSize.y - k_WindowPadding); GUI.Box(new Rect(0, 0, windowSize.x, windowSize.y), GUIContent.none, "grey_border"); diff --git a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchy.cs b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchy.cs index 3f69454e6f..4adb9ff208 100644 --- a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchy.cs +++ b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchy.cs @@ -14,9 +14,16 @@ internal class AddCurvesPopupHierarchy private TreeViewState m_TreeViewState; private AddCurvesPopupHierarchyDataSource m_TreeViewDataSource; + private float m_ContentWidth = 0f; + + public float GetContentWidth() + { + return m_ContentWidth; + } + public void OnGUI(Rect position, EditorWindow owner) { - InitIfNeeded(owner, position); + m_TreeView.SetTotalRect(position); m_TreeView.OnEvent(); m_TreeView.OnGUI(position, GUIUtility.GetControlID(FocusType.Keyboard)); } @@ -33,7 +40,7 @@ public void InitIfNeeded(EditorWindow owner, Rect rect) m_TreeView.deselectOnUnhandledMouseDown = true; m_TreeViewDataSource = new AddCurvesPopupHierarchyDataSource(m_TreeView); - TreeViewGUI gui = new AddCurvesPopupHierarchyGUI(m_TreeView, owner); + AddCurvesPopupHierarchyGUI gui = new AddCurvesPopupHierarchyGUI(m_TreeView, owner); m_TreeView.Init(rect, m_TreeViewDataSource, @@ -42,6 +49,8 @@ public void InitIfNeeded(EditorWindow owner, Rect rect) ); m_TreeViewDataSource.UpdateData(); + + m_ContentWidth = gui.GetContentWidth(); } internal virtual bool IsRenamingNodeAllowed(TreeViewItem node) diff --git a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyDataSource.cs b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyDataSource.cs index b944bfb74b..5bea4058b3 100644 --- a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyDataSource.cs +++ b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyDataSource.cs @@ -31,6 +31,7 @@ private void SetupRootNodeSettings() public override void FetchData() { + m_RootItem = null; if (AddCurvesPopup.s_State.selection.canAddCurves) { GameObject rootGameObject = AddCurvesPopup.s_State.activeRootGameObject; diff --git a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyGUI.cs b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyGUI.cs index 37a14c36a6..939b21cf85 100644 --- a/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyGUI.cs +++ b/Editor/Mono/Animation/AnimationWindow/AddCurvesPopupHierarchyGUI.cs @@ -5,6 +5,7 @@ using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; +using System.Collections.Generic; namespace UnityEditorInternal { @@ -14,6 +15,7 @@ internal class AddCurvesPopupHierarchyGUI : TreeViewGUI public bool showPlusButton { get; set; } private GUIStyle plusButtonStyle = "OL Plus"; private GUIStyle plusButtonBackgroundStyle = "Tag MenuItem"; + private GUIContent addPropertiesContent = EditorGUIUtility.TrTextContent("Add Properties"); private const float plusButtonWidth = 17; public AddCurvesPopupHierarchyGUI(TreeViewController treeView, EditorWindow owner) @@ -25,7 +27,12 @@ public AddCurvesPopupHierarchyGUI(TreeViewController treeView, EditorWindow owne public override void OnRowGUI(Rect rowRect, TreeViewItem node, int row, bool selected, bool focused) { base.OnRowGUI(rowRect, node, row, selected, focused); + DoAddCurveButton(rowRect, node); + HandleContextMenu(rowRect, node); + } + private void DoAddCurveButton(Rect rowRect, TreeViewItem node) + { // Is it propertynode. If not, then we don't need plusButton so quit here AddCurvesPopupPropertyNode hierarchyNode = node as AddCurvesPopupPropertyNode; if (hierarchyNode == null || hierarchyNode.curveBindings == null || hierarchyNode.curveBindings.Length == 0) @@ -41,10 +48,85 @@ public override void OnRowGUI(Rect rowRect, TreeViewItem node, int row, bool sel if (GUI.Button(buttonRect, GUIContent.none, plusButtonStyle)) { AddCurvesPopup.AddNewCurve(hierarchyNode); - owner.Close(); + + // Hold shift key to add new curves and keep window opened. + if (Event.current.shift) + m_TreeView.ReloadData(); + else + owner.Close(); } } + private void HandleContextMenu(Rect rowRect, TreeViewItem node) + { + if (Event.current.type != EventType.ContextClick) + return; + + if (rowRect.Contains(Event.current.mousePosition)) + { + // Add current node to selection + var ids = new List(m_TreeView.GetSelection()); + ids.Add(node.id); + m_TreeView.SetSelection(ids.ToArray(), false, false); + + GenerateMenu().ShowAsContext(); + Event.current.Use(); + } + } + + private GenericMenu GenerateMenu() + { + GenericMenu menu = new GenericMenu(); + menu.AddItem(addPropertiesContent, false, AddPropertiesFromSelectedNodes); + + return menu; + } + + private void AddPropertiesFromSelectedNodes() + { + int[] ids = m_TreeView.GetSelection(); + for (int i = 0; i < ids.Length; ++i) + { + var node = m_TreeView.FindItem(ids[i]); + var propertyNode = node as AddCurvesPopupPropertyNode; + + if (propertyNode != null) + { + AddCurvesPopup.AddNewCurve(propertyNode); + } + else if (node.hasChildren) + { + foreach (var childNode in node.children) + { + var childPropertyNode = childNode as AddCurvesPopupPropertyNode; + if (childPropertyNode != null) + { + AddCurvesPopup.AddNewCurve(childPropertyNode); + } + } + } + } + + m_TreeView.ReloadData(); + } + + public float GetContentWidth() + { + IList rows = m_TreeView.data.GetRows(); + List allRows = new List(); + allRows.AddRange(rows); + + for (int i = 0; i < allRows.Count; ++i) + { + var row = allRows[i]; + if (row.hasChildren) + allRows.AddRange(row.children); + } + + float rowWidth = GetMaxWidth(allRows); + return rowWidth + plusButtonWidth; + } + override protected void SyncFakeItem() { //base.SyncFakeItem(); diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationClipSelectionItem.cs b/Editor/Mono/Animation/AnimationWindow/AnimationClipSelectionItem.cs deleted file mode 100644 index c6942190d7..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationClipSelectionItem.cs +++ /dev/null @@ -1,35 +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 UnityEditor; - -using Object = UnityEngine.Object; - -namespace UnityEditorInternal -{ - internal class AnimationClipSelectionItem : AnimationWindowSelectionItem - { - public static AnimationClipSelectionItem Create(AnimationClip animationClip, Object sourceObject) - { - AnimationClipSelectionItem selectionItem = CreateInstance(typeof(AnimationClipSelectionItem)) as AnimationClipSelectionItem; - - selectionItem.gameObject = sourceObject as GameObject; - selectionItem.scriptableObject = sourceObject as ScriptableObject; - selectionItem.animationClip = animationClip; - selectionItem.id = 0; // no need for id since there's only one item in selection. - - return selectionItem; - } - - public override bool canPreview { get { return false; } } - - public override bool canRecord { get { return false; } } - - public override bool canChangeAnimationClip { get { return false; } } - - public override bool canSyncSceneSelection { get { return false; } } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowCurve.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowCurve.cs deleted file mode 100644 index f866b167e1..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowCurve.cs +++ /dev/null @@ -1,325 +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 UnityEditor; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using Object = UnityEngine.Object; - -namespace UnityEditorInternal -{ - internal class AnimationWindowCurve : IComparable - { - public const float timeEpsilon = 0.00001f; - - public List m_Keyframes; - - private EditorCurveBinding m_Binding; - private int m_BindingHashCode; - - private AnimationClip m_Clip; - private AnimationWindowSelectionItem m_SelectionBinding; - - private System.Type m_ValueType; - - public EditorCurveBinding binding { get { return m_Binding; } } - public bool isPPtrCurve { get { return m_Binding.isPPtrCurve; } } - public bool isDiscreteCurve { get { return m_Binding.isDiscreteCurve; } } - public bool isPhantom { get { return m_Binding.isPhantom; } } - public string propertyName { get { return m_Binding.propertyName; } } - public string path { get { return m_Binding.path; } } - public System.Type type { get { return m_Binding.type; } } - public System.Type valueType { get { return m_ValueType; } } - public int length { get { return m_Keyframes.Count; } } - - public int depth { get { return path.Length > 0 ? path.Split('/').Length : 0; } } - - public AnimationClip clip { get { return m_Clip; } } - - public GameObject rootGameObject { get { return m_SelectionBinding != null ? m_SelectionBinding.rootGameObject : null; } } - public ScriptableObject scriptableObject { get { return m_SelectionBinding != null ? m_SelectionBinding.scriptableObject : null; } } - public bool clipIsEditable { get { return m_SelectionBinding != null ? m_SelectionBinding.clipIsEditable : true; } } - public bool animationIsEditable { get { return m_SelectionBinding != null ? m_SelectionBinding.animationIsEditable : true; } } - public int selectionID { get { return m_SelectionBinding != null ? m_SelectionBinding.id : 0; } } - - public AnimationWindowSelectionItem selectionBinding { get { return m_SelectionBinding; } set { m_SelectionBinding = value; } } - - public AnimationWindowCurve(AnimationClip clip, EditorCurveBinding binding, System.Type valueType) - { - binding = RotationCurveInterpolation.RemapAnimationBindingForRotationCurves(binding, clip); - - m_Binding = binding; - m_BindingHashCode = binding.GetHashCode(); - m_ValueType = valueType; - m_Clip = clip; - - LoadKeyframes(clip); - } - - public void LoadKeyframes(AnimationCurve curve) - { - if (curve == null) - return; - - for (int i = 0; i < curve.length; i++) - m_Keyframes.Add(new AnimationWindowKeyframe(this, curve[i])); - } - - public void LoadKeyframes(AnimationClip clip) - { - m_Keyframes = new List(); - - if (!m_Binding.isPPtrCurve) - { - AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, binding); - LoadKeyframes(curve); - } - else - { - ObjectReferenceKeyframe[] curve = AnimationUtility.GetObjectReferenceCurve(clip, binding); - if (curve != null) - { - for (int i = 0; i < curve.Length; i++) - m_Keyframes.Add(new AnimationWindowKeyframe(this, curve[i])); - } - } - } - - public override int GetHashCode() - { - int clipID = (clip == null ? 0 : clip.GetInstanceID()); - return unchecked(selectionID * 92821 ^ clipID * 19603 ^ GetBindingHashCode()); - } - - public int GetBindingHashCode() - { - return m_BindingHashCode; - } - - public int CompareTo(AnimationWindowCurve obj) - { - bool pathEquals = path.Equals(obj.path); - bool typeEquals = obj.type == type; - - if (!pathEquals && depth != obj.depth) - { - int minLength = Math.Min(path.Length, obj.path.Length); - int commonLength = 0; - int index = 0; - for (; index < minLength; ++index) - { - if (path[index] != obj.path[index]) - break; - - if (path[index] == '/') - commonLength = index + 1; - } - - if (index == minLength) - commonLength = minLength; - - string subPath1 = path.Substring(commonLength); - string subPath2 = obj.path.Substring(commonLength); - - if (String.IsNullOrEmpty(subPath1)) - return -1; - else if (String.IsNullOrEmpty(subPath2)) - return 1; - - Regex r = new Regex(@"^[^\/]*\/"); - - Match match1 = r.Match(subPath1); - string next1 = match1.Success ? match1.Value.Substring(0, match1.Value.Length - 1) : subPath1; - - Match match2 = r.Match(subPath2); - string next2 = match2.Success ? match2.Value.Substring(0, match2.Value.Length - 1) : subPath2; - - return next1.CompareTo(next2); - } - - bool sameTransformComponent = type == typeof(Transform) && obj.type == typeof(Transform) && pathEquals; - bool oneIsTransformComponent = (type == typeof(Transform) || obj.type == typeof(Transform)) && pathEquals; - - // We want to sort position before rotation - if (sameTransformComponent) - { - string propertyGroupA = AnimationWindowUtility.GetNicePropertyGroupDisplayName(typeof(Transform), AnimationWindowUtility.GetPropertyGroupName(propertyName)); - string propertyGroupB = AnimationWindowUtility.GetNicePropertyGroupDisplayName(typeof(Transform), AnimationWindowUtility.GetPropertyGroupName(obj.propertyName)); - - if (propertyGroupA.Contains("Position") && propertyGroupB.Contains("Rotation")) - return -1; - if (propertyGroupA.Contains("Rotation") && propertyGroupB.Contains("Position")) - return 1; - } - // Transform component should always come first. - else if (oneIsTransformComponent) - { - if (type == typeof(Transform)) - return -1; - else - return 1; - } - - // Sort (.r, .g, .b, .a) and (.x, .y, .z, .w) - if (pathEquals && typeEquals) - { - int lhsIndex = AnimationWindowUtility.GetComponentIndex(obj.propertyName); - int rhsIndex = AnimationWindowUtility.GetComponentIndex(propertyName); - if (lhsIndex != -1 && rhsIndex != -1 && propertyName.Substring(0, propertyName.Length - 2) == obj.propertyName.Substring(0, obj.propertyName.Length - 2)) - return rhsIndex - lhsIndex; - } - - return (path + type + propertyName).CompareTo(obj.path + obj.type + obj.propertyName); - } - - public AnimationCurve ToAnimationCurve() - { - int length = m_Keyframes.Count; - AnimationCurve animationCurve = new AnimationCurve(); - List keys = new List(); - - float lastFrameTime = float.MinValue; - - for (int i = 0; i < length; i++) - { - // Make sure we don't get two keyframes in an exactly the same time. We just ignore those. - if (Mathf.Abs(m_Keyframes[i].time - lastFrameTime) > AnimationWindowCurve.timeEpsilon) - { - Keyframe newKeyframe = m_Keyframes[i].ToKeyframe(); - keys.Add(newKeyframe); - lastFrameTime = m_Keyframes[i].time; - } - } - - animationCurve.keys = keys.ToArray(); - return animationCurve; - } - - public ObjectReferenceKeyframe[] ToObjectCurve() - { - int length = m_Keyframes.Count; - List keys = new List(); - - float lastFrameTime = float.MinValue; - - for (int i = 0; i < length; i++) - { - // Make sure we don't get two keyframes in an exactly the same time. We just ignore those. - if (Mathf.Abs(m_Keyframes[i].time - lastFrameTime) > AnimationWindowCurve.timeEpsilon) - { - ObjectReferenceKeyframe newKeyframe = m_Keyframes[i].ToObjectReferenceKeyframe(); - lastFrameTime = newKeyframe.time; - keys.Add(newKeyframe); - } - } - - return keys.ToArray(); - } - - public AnimationWindowKeyframe FindKeyAtTime(AnimationKeyTime keyTime) - { - int index = GetKeyframeIndex(keyTime); - if (index == -1) - return null; - - return m_Keyframes[index]; - } - - public object Evaluate(float time) - { - if (m_Keyframes.Count == 0) - return isPPtrCurve ? null : (object)0f; - - AnimationWindowKeyframe firstKey = m_Keyframes[0]; - if (time <= firstKey.time) - return firstKey.value; - - AnimationWindowKeyframe lastKey = m_Keyframes[m_Keyframes.Count - 1]; - if (time >= lastKey.time) - return lastKey.value; - - AnimationWindowKeyframe key = firstKey; - for (int i = 1; i < m_Keyframes.Count; ++i) - { - AnimationWindowKeyframe nextKey = m_Keyframes[i]; - - if (key.time < time && nextKey.time >= time) - { - if (isPPtrCurve) - { - return key.value; - } - else - { - // Create an animation curve stub and evaluate. - Keyframe keyframe = key.ToKeyframe(); - Keyframe nextKeyframe = nextKey.ToKeyframe(); - - AnimationCurve animationCurve = new AnimationCurve(); - animationCurve.keys = new Keyframe[2] { keyframe, nextKeyframe }; - - return animationCurve.Evaluate(time); - } - } - - key = nextKey; - } - - // Shouldn't happen... - return isPPtrCurve ? null : (object)0f; - } - - public void AddKeyframe(AnimationWindowKeyframe key, AnimationKeyTime keyTime) - { - // If there is already key in this time, we always want to remove it - RemoveKeyframe(keyTime); - - m_Keyframes.Add(key); - m_Keyframes.Sort((a, b) => a.time.CompareTo(b.time)); - } - - public void RemoveKeyframe(AnimationKeyTime time) - { - // Loop backwards so key removals don't mess up order - for (int i = m_Keyframes.Count - 1; i >= 0; i--) - { - if (time.ContainsTime(m_Keyframes[i].time)) - m_Keyframes.RemoveAt(i); - } - } - - public bool HasKeyframe(AnimationKeyTime time) - { - return GetKeyframeIndex(time) != -1; - } - - public int GetKeyframeIndex(AnimationKeyTime time) - { - for (int i = 0; i < m_Keyframes.Count; i++) - { - if (time.ContainsTime(m_Keyframes[i].time)) - return i; - } - return -1; - } - - // Remove keys at range. Start time is exclusive and end time inclusive. - public void RemoveKeysAtRange(float startTime, float endTime) - { - for (int i = m_Keyframes.Count - 1; i >= 0; i--) - { - if (Mathf.Approximately(endTime, m_Keyframes[i].time) || - m_Keyframes[i].time > startTime && m_Keyframes[i].time < endTime) - m_Keyframes.RemoveAt(i); - } - } - - public void Clear() - { - m_Keyframes.Clear(); - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowEvent.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowEvent.cs deleted file mode 100644 index 613cfa17ff..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowEvent.cs +++ /dev/null @@ -1,103 +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 UnityEditor; - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal struct AnimationWindowEventMethod - { - public string name; - public Type parameterType; - } - - internal class AnimationWindowEvent : ScriptableObject - { - public GameObject root; - public AnimationClip clip; - public AnimationClipInfoProperties clipInfo; - public int eventIndex; - - static public AnimationWindowEvent CreateAndEdit(GameObject root, AnimationClip clip, float time) - { - AnimationEvent animationEvent = new AnimationEvent(); - animationEvent.time = time; - - // Or add a new one - AnimationEvent[] events = AnimationUtility.GetAnimationEvents(clip); - int eventIndex = InsertAnimationEvent(ref events, clip, animationEvent); - - AnimationWindowEvent animationWindowEvent = CreateInstance(); - animationWindowEvent.hideFlags = HideFlags.HideInHierarchy; - animationWindowEvent.name = "Animation Event"; - - animationWindowEvent.root = root; - animationWindowEvent.clip = clip; - animationWindowEvent.clipInfo = null; - animationWindowEvent.eventIndex = eventIndex; - - return animationWindowEvent; - } - - static public AnimationWindowEvent Edit(GameObject root, AnimationClip clip, int eventIndex) - { - AnimationWindowEvent animationWindowEvent = CreateInstance(); - animationWindowEvent.hideFlags = HideFlags.HideInHierarchy; - animationWindowEvent.name = "Animation Event"; - - animationWindowEvent.root = root; - animationWindowEvent.clip = clip; - animationWindowEvent.clipInfo = null; - animationWindowEvent.eventIndex = eventIndex; - - return animationWindowEvent; - } - - static public AnimationWindowEvent Edit(AnimationClipInfoProperties clipInfo, int eventIndex) - { - AnimationWindowEvent animationWindowEvent = CreateInstance(); - animationWindowEvent.hideFlags = HideFlags.HideInHierarchy; - animationWindowEvent.name = "Animation Event"; - - animationWindowEvent.root = null; - animationWindowEvent.clip = null; - animationWindowEvent.clipInfo = clipInfo; - animationWindowEvent.eventIndex = eventIndex; - - return animationWindowEvent; - } - - static private int InsertAnimationEvent(ref AnimationEvent[] events, AnimationClip clip, AnimationEvent evt) - { - Undo.RegisterCompleteObjectUndo(clip, "Add Event"); - - // Or add a new one - int insertIndex = events.Length; - for (int i = 0; i < events.Length; i++) - { - if (events[i].time > evt.time) - { - insertIndex = i; - break; - } - } - - ArrayUtility.Insert(ref events, insertIndex, evt); - AnimationUtility.SetAnimationEvents(clip, events); - - events = AnimationUtility.GetAnimationEvents(clip); - if (events[insertIndex].time != evt.time || events[insertIndex].functionName != evt.functionName) - Debug.LogError("Failed insertion"); - - return insertIndex; - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyDataSource.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyDataSource.cs deleted file mode 100644 index 2dd490c0bf..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyDataSource.cs +++ /dev/null @@ -1,163 +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 UnityEditor; -using System.Collections.Generic; -using UnityEditor.IMGUI.Controls; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace UnityEditorInternal -{ - internal class AnimationWindowHierarchyDataSource : TreeViewDataSource - { - // Animation window shared state - private AnimationWindowState state { get; set; } - public bool showAll { get; set; } - - public AnimationWindowHierarchyDataSource(TreeViewController treeView, AnimationWindowState animationWindowState) - : base(treeView) - { - state = animationWindowState; - } - - private void SetupRootNodeSettings() - { - showRootItem = false; - rootIsCollapsable = false; - SetExpanded(m_RootItem, true); - } - - private AnimationWindowHierarchyNode GetEmptyRootNode() - { - return new AnimationWindowHierarchyNode(0, -1, null, null, "", "", "root"); - } - - public override void FetchData() - { - m_RootItem = GetEmptyRootNode(); - SetupRootNodeSettings(); - m_NeedRefreshRows = true; - - if (state.selection.disabled) - { - root.children = null; - return; - } - - List childNodes = new List(); - - if (state.allCurves.Count > 0) - { - AnimationWindowHierarchyMasterNode masterNode = new AnimationWindowHierarchyMasterNode(); - masterNode.curves = state.allCurves.ToArray(); - - childNodes.Add(masterNode); - } - - childNodes.AddRange(CreateTreeFromCurves()); - childNodes.Add(new AnimationWindowHierarchyAddButtonNode()); - - TreeViewUtility.SetChildParentReferences(new List(childNodes.ToArray()), root); - } - - public override bool IsRenamingItemAllowed(TreeViewItem item) - { - if (item is AnimationWindowHierarchyAddButtonNode || item is AnimationWindowHierarchyMasterNode || item is AnimationWindowHierarchyClipNode) - return false; - - if ((item as AnimationWindowHierarchyNode).path.Length == 0) - return false; - - return true; - } - - public List CreateTreeFromCurves() - { - List nodes = new List(); - List singlePropertyCurves = new List(); - - AnimationWindowCurve[] curves = state.allCurves.ToArray(); - AnimationWindowHierarchyNode parentNode = (AnimationWindowHierarchyNode)m_RootItem; - - for (int i = 0; i < curves.Length; i++) - { - AnimationWindowCurve curve = curves[i]; - AnimationWindowCurve nextCurve = i < curves.Length - 1 ? curves[i + 1] : null; - - singlePropertyCurves.Add(curve); - - bool areSameGroup = nextCurve != null && AnimationWindowUtility.GetPropertyGroupName(nextCurve.propertyName) == AnimationWindowUtility.GetPropertyGroupName(curve.propertyName); - bool areSamePathAndType = nextCurve != null && curve.path.Equals(nextCurve.path) && curve.type == nextCurve.type; - - // We expect curveBindings to come sorted by propertyname - // So we compare curve vs nextCurve. If its different path or different group (think "scale.xyz" as group), then we know this is the last element of such group. - if (i == curves.Length - 1 || !areSameGroup || !areSamePathAndType) - { - if (singlePropertyCurves.Count > 1) - nodes.Add(AddPropertyGroupToHierarchy(singlePropertyCurves.ToArray(), parentNode)); - else - nodes.Add(AddPropertyToHierarchy(singlePropertyCurves[0], parentNode)); - singlePropertyCurves.Clear(); - } - } - - return nodes; - } - - private AnimationWindowHierarchyPropertyGroupNode AddPropertyGroupToHierarchy(AnimationWindowCurve[] curves, AnimationWindowHierarchyNode parentNode) - { - List childNodes = new List(); - - System.Type animatableObjectType = curves[0].type; - AnimationWindowHierarchyPropertyGroupNode node = new AnimationWindowHierarchyPropertyGroupNode(animatableObjectType, 0, AnimationWindowUtility.GetPropertyGroupName(curves[0].propertyName), curves[0].path, parentNode); - - node.icon = GetIcon(curves[0].binding); - - node.indent = curves[0].depth; - node.curves = curves; - - foreach (AnimationWindowCurve curve in curves) - { - AnimationWindowHierarchyPropertyNode childNode = AddPropertyToHierarchy(curve, node); - // For child nodes we do not want to display the type in front (It is already shown by the group node) - childNode.displayName = AnimationWindowUtility.GetPropertyDisplayName(childNode.propertyName); - childNodes.Add(childNode); - } - - TreeViewUtility.SetChildParentReferences(new List(childNodes.ToArray()), node); - return node; - } - - private AnimationWindowHierarchyPropertyNode AddPropertyToHierarchy(AnimationWindowCurve curve, AnimationWindowHierarchyNode parentNode) - { - AnimationWindowHierarchyPropertyNode node = new AnimationWindowHierarchyPropertyNode(curve.type, 0, curve.propertyName, curve.path, parentNode, curve.binding, curve.isPPtrCurve); - - if (parentNode.icon != null) - node.icon = parentNode.icon; - else - node.icon = GetIcon(curve.binding); - - node.indent = curve.depth; - node.curves = new[] { curve }; - return node; - } - - public Texture2D GetIcon(EditorCurveBinding curveBinding) - { - if (state.activeRootGameObject != null) - { - Object animatedObject = AnimationUtility.GetAnimatedObject(state.activeRootGameObject, curveBinding); - if (animatedObject != null) - return AssetPreview.GetMiniThumbnail(animatedObject); - } - return AssetPreview.GetMiniTypeThumbnail(curveBinding.type); - } - - public void UpdateData() - { - m_TreeView.ReloadData(); - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyNode.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyNode.cs deleted file mode 100644 index 7ed4ca36a9..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowHierarchyNode.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 UnityEditor; -using UnityEngine; -using System.Collections.Generic; -using UnityEditor.IMGUI.Controls; - -namespace UnityEditorInternal -{ - internal class AnimationWindowHierarchyNode : TreeViewItem - { - public string path; - public System.Type animatableObjectType; - public string propertyName; - - public EditorCurveBinding? binding; - public AnimationWindowCurve[] curves; - - public float? topPixel = null; - public int indent = 0; - - public AnimationWindowHierarchyNode(int instanceID, int depth, TreeViewItem parent, System.Type animatableObjectType, string propertyName, string path, string displayName) - : base(instanceID, depth, parent, displayName) - { - this.displayName = displayName; - this.animatableObjectType = animatableObjectType; - this.propertyName = propertyName; - this.path = path; - } - } - - internal class AnimationWindowHierarchyPropertyGroupNode : AnimationWindowHierarchyNode - { - public AnimationWindowHierarchyPropertyGroupNode(System.Type animatableObjectType, int setId, string propertyName, string path, TreeViewItem parent) - : base(AnimationWindowUtility.GetPropertyNodeID(setId, path, animatableObjectType, propertyName), parent != null ? parent.depth + 1 : -1, parent, animatableObjectType, AnimationWindowUtility.GetPropertyGroupName(propertyName), path, AnimationWindowUtility.GetNicePropertyGroupDisplayName(animatableObjectType, propertyName)) - {} - } - - internal class AnimationWindowHierarchyPropertyNode : AnimationWindowHierarchyNode - { - public bool isPptrNode; - - public AnimationWindowHierarchyPropertyNode(System.Type animatableObjectType, int setId, string propertyName, string path, TreeViewItem parent, EditorCurveBinding binding, bool isPptrNode) - : base(AnimationWindowUtility.GetPropertyNodeID(setId, path, animatableObjectType, propertyName), parent != null ? parent.depth + 1 : -1, parent, animatableObjectType, propertyName, path, AnimationWindowUtility.GetNicePropertyDisplayName(animatableObjectType, propertyName)) - { - this.binding = binding; - this.isPptrNode = isPptrNode; - } - } - - internal class AnimationWindowHierarchyClipNode : AnimationWindowHierarchyNode - { - public AnimationWindowHierarchyClipNode(TreeViewItem parent, int setId, string name) - : base(setId, parent != null ? parent.depth + 1 : -1, parent, null, null, null, name) - {} - } - - internal class AnimationWindowHierarchyMasterNode : AnimationWindowHierarchyNode - { - public AnimationWindowHierarchyMasterNode() - : base(0, -1, null, null, null, null, "") - {} - } - - // A special node to put "Add Curve" button in bottom of the tree - internal class AnimationWindowHierarchyAddButtonNode : AnimationWindowHierarchyNode - { - public AnimationWindowHierarchyAddButtonNode() - : base(0, -1, null, null, null, null, "") - {} - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeySelection.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeySelection.cs deleted file mode 100644 index 80cffd1205..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeySelection.cs +++ /dev/null @@ -1,42 +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 UnityEngine; -using UnityEditor; -using System.Collections.Generic; -using System.Collections; -using Object = UnityEngine.Object; - -namespace UnityEditorInternal -{ - [System.Serializable] - internal class AnimationWindowKeySelection : ScriptableObject, ISerializationCallbackReceiver - { - private HashSet m_SelectedKeyHashes; - [SerializeField] private List m_SelectedKeyHashesSerialized; - - public HashSet selectedKeyHashes - { - get { return m_SelectedKeyHashes ?? (m_SelectedKeyHashes = new HashSet()); } - set { m_SelectedKeyHashes = value; } - } - - public void SaveSelection(string undoLabel) - { - Undo.RegisterCompleteObjectUndo(this, undoLabel); - } - - public void OnBeforeSerialize() - { - m_SelectedKeyHashesSerialized = m_SelectedKeyHashes.ToList(); - } - - public void OnAfterDeserialize() - { - m_SelectedKeyHashes = new HashSet(m_SelectedKeyHashesSerialized); - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeyframe.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeyframe.cs deleted file mode 100644 index 2a310b8c35..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowKeyframe.cs +++ /dev/null @@ -1,174 +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 UnityEditor; - -namespace UnityEditorInternal -{ - internal class AnimationWindowKeyframe - { - public float m_InTangent; - public float m_OutTangent; - public float m_InWeight; - public float m_OutWeight; - public WeightedMode m_WeightedMode; - public int m_TangentMode; - public int m_TimeHash; - int m_Hash; - - float m_time; - - object m_value; - - AnimationWindowCurve m_curve; - public float time - { - get { return m_time; } - set - { - m_time = value; - m_Hash = 0; - m_TimeHash = value.GetHashCode(); - } - } - - public object value - { - get { return m_value; } - set { m_value = value; } - } - - public float inTangent - { - get { return m_InTangent; } - set { m_InTangent = value; } - } - - public float outTangent - { - get { return m_OutTangent; } - set { m_OutTangent = value; } - } - - public float inWeight - { - get { return m_InWeight; } - set { m_InWeight = value; } - } - - public float outWeight - { - get { return m_OutWeight; } - set { m_OutWeight = value; } - } - - public WeightedMode weightedMode - { - get { return m_WeightedMode; } - set { m_WeightedMode = value; } - } - - public AnimationWindowCurve curve - { - get { return m_curve; } - set - { - m_curve = value; - m_Hash = 0; - } - } - - public bool isPPtrCurve { get { return curve.isPPtrCurve; } } - public bool isDiscreteCurve { get { return curve.isDiscreteCurve; } } - - public AnimationWindowKeyframe() - { - } - - public AnimationWindowKeyframe(AnimationWindowKeyframe key) - { - this.time = key.time; - this.value = key.value; - this.curve = key.curve; - this.m_InTangent = key.m_InTangent; - this.m_OutTangent = key.m_OutTangent; - this.m_InWeight = key.inWeight; - this.m_OutWeight = key.outWeight; - this.m_WeightedMode = key.weightedMode; - this.m_TangentMode = key.m_TangentMode; - this.m_curve = key.m_curve; - } - - public AnimationWindowKeyframe(AnimationWindowCurve curve, Keyframe key) - { - this.time = key.time; - this.value = key.value; - this.curve = curve; - this.m_InTangent = key.inTangent; - this.m_OutTangent = key.outTangent; - this.m_InWeight = key.inWeight; - this.m_OutWeight = key.outWeight; - this.m_WeightedMode = key.weightedMode; - this.m_TangentMode = key.tangentModeInternal; - this.m_curve = curve; - } - - public AnimationWindowKeyframe(AnimationWindowCurve curve, ObjectReferenceKeyframe key) - { - this.time = key.time; - this.value = key.value; - this.curve = curve; - } - - public int GetHash() - { - if (m_Hash == 0) - { - // Berstein hash - unchecked - { - m_Hash = curve.GetHashCode(); - m_Hash = 33 * m_Hash + time.GetHashCode(); - } - } - - return m_Hash; - } - - public int GetIndex() - { - for (int i = 0; i < curve.m_Keyframes.Count; i++) - { - if (curve.m_Keyframes[i] == this) - { - return i; - } - } - return -1; - } - - public Keyframe ToKeyframe() - { - var keyframe = new Keyframe(time, (float)value, inTangent, outTangent); - - keyframe.tangentModeInternal = m_TangentMode; - keyframe.weightedMode = weightedMode; - keyframe.inWeight = inWeight; - keyframe.outWeight = outWeight; - - return keyframe; - } - - public ObjectReferenceKeyframe ToObjectReferenceKeyframe() - { - var keyframe = new ObjectReferenceKeyframe(); - - keyframe.time = time; - keyframe.value = (UnityEngine.Object)value; - - return keyframe; - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/AnimationWindowManipulator.cs b/Editor/Mono/Animation/AnimationWindow/AnimationWindowManipulator.cs deleted file mode 100644 index 76fc50980b..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/AnimationWindowManipulator.cs +++ /dev/null @@ -1,192 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class AnimationWindowManipulator - { - public delegate bool OnStartDragDelegate(AnimationWindowManipulator manipulator, Event evt); - public delegate bool OnDragDelegate(AnimationWindowManipulator manipulator, Event evt); - public delegate bool OnEndDragDelegate(AnimationWindowManipulator manipulator, Event evt); - - public OnStartDragDelegate onStartDrag; - public OnDragDelegate onDrag; - public OnEndDragDelegate onEndDrag; - - public Rect rect; - public int controlID; - - public AnimationWindowManipulator() - { - // NoOps... - onStartDrag += (AnimationWindowManipulator manipulator, Event evt) => { return false; }; - onDrag += (AnimationWindowManipulator manipulator, Event evt) => { return false; }; - onEndDrag += (AnimationWindowManipulator manipulator, Event evt) => { return false; }; - } - - public virtual void HandleEvents() - { - controlID = GUIUtility.GetControlID(FocusType.Passive); - - Event evt = Event.current; - EventType eventType = evt.GetTypeForControl(controlID); - - bool handled = false; - switch (eventType) - { - case EventType.MouseDown: - if (evt.button == 0) - { - handled = onStartDrag(this, evt); - - if (handled) - GUIUtility.hotControl = controlID; - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == controlID) - { - handled = onDrag(this, evt); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == controlID) - { - handled = onEndDrag(this, evt); - GUIUtility.hotControl = 0; - } - break; - } - - if (handled) - evt.Use(); - } - - public virtual void IgnoreEvents() - { - GUIUtility.GetControlID(FocusType.Passive); - } - } - - internal class AreaManipulator : AnimationWindowManipulator - { - private GUIStyle m_Style; - private MouseCursor m_Cursor; - - public AreaManipulator(GUIStyle style, MouseCursor cursor) - { - m_Style = style; - m_Cursor = cursor; - } - - public AreaManipulator(GUIStyle style) - { - m_Style = style; - m_Cursor = MouseCursor.Arrow; - } - - public void OnGUI(Rect widgetRect) - { - if (m_Style == null) - return; - - rect = widgetRect; - - if (Mathf.Approximately(widgetRect.width * widgetRect.height, 0f)) - return; - - GUI.Label(widgetRect, GUIContent.none, m_Style); - - if (GUIUtility.hotControl == 0 && m_Cursor != MouseCursor.Arrow) - { - EditorGUIUtility.AddCursorRect(widgetRect, m_Cursor); - } - else if (GUIUtility.hotControl == controlID) - { - Vector2 mousePosition = Event.current.mousePosition; - EditorGUIUtility.AddCursorRect(new Rect(mousePosition.x - 10, mousePosition.y - 10, 20, 20), m_Cursor); - } - } - } - - internal class TimeCursorManipulator : AnimationWindowManipulator - { - public enum Alignment - { - Center, - Left, - Right - }; - - public Alignment alignment; - public Color headColor; - public Color lineColor; - public bool dottedLine; - public bool drawLine; - public bool drawHead; - public string tooltip; - - private GUIStyle m_Style; - - public TimeCursorManipulator(GUIStyle style) - { - m_Style = style; - dottedLine = false; - headColor = Color.white; - lineColor = style.normal.textColor; - drawLine = true; - drawHead = true; - tooltip = string.Empty; - alignment = Alignment.Center; - } - - public void OnGUI(Rect windowRect, float pixelTime) - { - float widgetWidth = m_Style.fixedWidth; - float widgetHeight = m_Style.fixedHeight; - - Vector2 windowCoordinate = new Vector2(pixelTime, windowRect.yMin); - - switch (alignment) - { - case Alignment.Center: - rect = new Rect((windowCoordinate.x - widgetWidth / 2.0f), windowCoordinate.y, widgetWidth, widgetHeight); - break; - case Alignment.Left: - rect = new Rect(windowCoordinate.x - widgetWidth, windowCoordinate.y, widgetWidth, widgetHeight); - break; - case Alignment.Right: - rect = new Rect(windowCoordinate.x, windowCoordinate.y, widgetWidth, widgetHeight); - break; - } - - Vector3 p1 = new Vector3(windowCoordinate.x, windowCoordinate.y + widgetHeight, 0.0f); - Vector3 p2 = new Vector3(windowCoordinate.x, windowRect.height, 0.0f); - - if (drawLine) - { - Handles.color = lineColor; - if (dottedLine) - Handles.DrawDottedLine(p1, p2, 5.0f); - else - Handles.DrawLine(p1, p2); - } - - if (drawHead) - { - Color c = GUI.color; - GUI.color = headColor; - GUI.Box(rect, GUIContent.none, m_Style); - GUI.color = c; - } - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/CurveBindingUtility.cs b/Editor/Mono/Animation/AnimationWindow/CurveBindingUtility.cs deleted file mode 100644 index 21ee380a73..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/CurveBindingUtility.cs +++ /dev/null @@ -1,48 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditorInternal -{ - static internal class CurveBindingUtility - { - // Retrieve current value. If bindings are available and value is animated, use bindings to get value. - // Otherwise, evaluate AnimationWindowCurve at current time. - public static object GetCurrentValue(AnimationWindowState state, AnimationWindowCurve curve) - { - if (state.previewing && curve.rootGameObject != null) - { - return AnimationWindowUtility.GetCurrentValue(curve.rootGameObject, curve.binding); - } - else - { - return curve.Evaluate(state.currentTime); - } - } - - // Retrieve Current Value. Use specified bindings to do so. - public static object GetCurrentValue(GameObject rootGameObject, EditorCurveBinding curveBinding) - { - if (rootGameObject != null) - { - return AnimationWindowUtility.GetCurrentValue(rootGameObject, curveBinding); - } - else - { - if (curveBinding.isPPtrCurve) - { - // Cannot extract type of PPtrCurve. - return null; - } - else - { - // Cannot extract type of AnimationCurve. Default to float. - return 0.0f; - } - } - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/BoolCurveRenderer.cs b/Editor/Mono/Animation/AnimationWindow/CurveRenderer/BoolCurveRenderer.cs deleted file mode 100644 index a3d514be15..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/BoolCurveRenderer.cs +++ /dev/null @@ -1,30 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class BoolCurveRenderer : NormalCurveRenderer - { - public BoolCurveRenderer(AnimationCurve curve) - : base(curve) - { - } - - public override float ClampedValue(float value) - { - return value != 0.0f ? 1.0f : 0.0f; - } - - public override float EvaluateCurveSlow(float time) - { - return ClampedValue(GetCurve().Evaluate(time)); - } - } -} // namespace diff --git a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/CurveRenderer.cs b/Editor/Mono/Animation/AnimationWindow/CurveRenderer/CurveRenderer.cs deleted file mode 100644 index 1873db588b..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/CurveRenderer.cs +++ /dev/null @@ -1,28 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal interface CurveRenderer - { - void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, Color wrapColor); - AnimationCurve GetCurve(); - float RangeStart(); - float RangeEnd(); - void SetWrap(WrapMode wrap); - void SetWrap(WrapMode preWrap, WrapMode postWrap); - void SetCustomRange(float start, float end); - float EvaluateCurveSlow(float time); - float EvaluateCurveDeltaSlow(float time); - Bounds GetBounds(); - Bounds GetBounds(float minTime, float maxTime); - float ClampedValue(float value); - void FlushCache(); - } -} // namespace diff --git a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/EulerCurveRenderer.cs b/Editor/Mono/Animation/AnimationWindow/CurveRenderer/EulerCurveRenderer.cs deleted file mode 100644 index b1eda17f54..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/EulerCurveRenderer.cs +++ /dev/null @@ -1,79 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class EulerCurveRenderer : CurveRenderer - { - private int component; - private EulerCurveCombinedRenderer renderer; - - public EulerCurveRenderer(int component, EulerCurveCombinedRenderer renderer) - { - this.component = component; - this.renderer = renderer; - } - - public AnimationCurve GetCurve() - { - return renderer.GetCurveOfComponent(component); - } - - public float ClampedValue(float value) - { - return value; - } - - public float RangeStart() { return renderer.RangeStart(); } - public float RangeEnd() { return renderer.RangeEnd(); } - public void SetWrap(WrapMode wrap) - { - renderer.SetWrap(wrap); - } - - public void SetWrap(WrapMode preWrapMode, WrapMode postWrapMode) - { - renderer.SetWrap(preWrapMode, postWrapMode); - } - - public void SetCustomRange(float start, float end) - { - renderer.SetCustomRange(start, end); - } - - public float EvaluateCurveSlow(float time) - { - return renderer.EvaluateCurveSlow(time, component); - } - - public float EvaluateCurveDeltaSlow(float time) - { - return renderer.EvaluateCurveDeltaSlow(time, component); - } - - public void DrawCurve(float minTime, float maxTime, Color color, Matrix4x4 transform, Color wrapColor) - { - renderer.DrawCurve(minTime, maxTime, color, transform, component, wrapColor); - } - - public Bounds GetBounds() - { - return GetBounds(renderer.RangeStart(), renderer.RangeEnd()); - } - - public Bounds GetBounds(float minTime, float maxTime) - { - return renderer.GetBounds(minTime, maxTime, component); - } - - public void FlushCache() - { - } - } -} // namespace diff --git a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/IntCurveRenderer.cs b/Editor/Mono/Animation/AnimationWindow/CurveRenderer/IntCurveRenderer.cs deleted file mode 100644 index 68145127af..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/CurveRenderer/IntCurveRenderer.cs +++ /dev/null @@ -1,55 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class IntCurveRenderer : NormalCurveRenderer - { - const float kSegmentWindowResolution = 1000; - const int kMaximumSampleCount = 1000; - const float kStepHelperOffset = 0.000001f; - - - public IntCurveRenderer(AnimationCurve curve) - : base(curve) - { - } - - public override float ClampedValue(float value) - { - return Mathf.Floor(value + 0.5f); - } - - public override float EvaluateCurveSlow(float time) - { - return ClampedValue(GetCurve().Evaluate(time)); - } - - protected override int GetSegmentResolution(float minTime, float maxTime, float keyTime, float nextKeyTime) - { - float fullTimeRange = maxTime - minTime; - float keyTimeRange = nextKeyTime - keyTime; - int count = Mathf.RoundToInt(kSegmentWindowResolution * (keyTimeRange / fullTimeRange)); - return Mathf.Clamp(count, 1, kMaximumSampleCount); - } - - protected override void AddPoint(ref List points, ref float lastTime, float sampleTime, ref float lastValue, float sampleValue) - { - if (lastValue != sampleValue) - { - points.Add(new Vector3(lastTime + kStepHelperOffset, sampleValue)); - } - - points.Add(new Vector3(sampleTime, sampleValue)); - lastTime = sampleTime; - lastValue = sampleValue; - } - } -} // namespace diff --git a/Editor/Mono/Animation/AnimationWindow/DopeLine.cs b/Editor/Mono/Animation/AnimationWindow/DopeLine.cs deleted file mode 100644 index c576b1cf2c..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/DopeLine.cs +++ /dev/null @@ -1,122 +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 UnityEditor; -using System.Collections.Generic; -using System.Linq; -using System; - -namespace UnityEditorInternal -{ - internal class DopeLine - { - private int m_HierarchyNodeID; - private AnimationWindowCurve[] m_Curves; - private List m_Keys; - - public static GUIStyle dopekeyStyle = "Dopesheetkeyframe"; - - public Rect position; - public System.Type objectType; - public bool tallMode; - public bool hasChildren; - public bool isMasterDopeline; - - public System.Type valueType - { - get - { - if (m_Curves.Length > 0) - { - System.Type type = m_Curves[0].valueType; - for (int i = 1; i < m_Curves.Length; i++) - { - if (m_Curves[i].valueType != type) - return null; - } - return type; - } - - return null; - } - } - - public bool isPptrDopeline - { - get - { - if (m_Curves.Length > 0) - { - for (int i = 0; i < m_Curves.Length; i++) - { - if (!m_Curves[i].isPPtrCurve) - return false; - } - return true; - } - return false; - } - } - - public bool isEditable - { - get - { - if (m_Curves.Length > 0) - { - bool isReadOnly = Array.Exists(m_Curves, curve => !curve.animationIsEditable); - return !isReadOnly; - } - - return false; - } - } - - public int hierarchyNodeID - { - get - { - return m_HierarchyNodeID; - } - } - - public AnimationWindowCurve[] curves - { - get - { - return m_Curves; - } - } - - public List keys - { - get - { - if (m_Keys == null) - { - m_Keys = new List(); - foreach (AnimationWindowCurve curve in m_Curves) - foreach (AnimationWindowKeyframe key in curve.m_Keyframes) - m_Keys.Add(key); - - m_Keys.Sort((a, b) => a.time.CompareTo(b.time)); - } - - return m_Keys; - } - } - - public void InvalidateKeyframes() - { - m_Keys = null; - } - - public DopeLine(int hierarchyNodeID, AnimationWindowCurve[] curves) - { - m_HierarchyNodeID = hierarchyNodeID; - m_Curves = curves; - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/GameObjectSelectionItem.cs b/Editor/Mono/Animation/AnimationWindow/GameObjectSelectionItem.cs deleted file mode 100644 index f1d1aa5e68..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/GameObjectSelectionItem.cs +++ /dev/null @@ -1,68 +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 UnityEditor; - -namespace UnityEditorInternal -{ - internal class GameObjectSelectionItem : AnimationWindowSelectionItem - { - public static GameObjectSelectionItem Create(GameObject gameObject) - { - GameObjectSelectionItem selectionItem = CreateInstance(typeof(GameObjectSelectionItem)) as GameObjectSelectionItem; - - selectionItem.gameObject = gameObject; - selectionItem.animationClip = null; - selectionItem.id = 0; // no need for id since there's only one item in selection. - - if (selectionItem.rootGameObject != null) - { - AnimationClip[] allClips = AnimationUtility.GetAnimationClips(selectionItem.rootGameObject); - - if (selectionItem.animationClip == null && selectionItem.gameObject != null) // there is activeGO but clip is still null - selectionItem.animationClip = allClips.Length > 0 ? allClips[0] : null; - else if (!Array.Exists(allClips, x => x == selectionItem.animationClip)) // clip doesn't belong to the currently active GO - selectionItem.animationClip = allClips.Length > 0 ? allClips[0] : null; - } - - return selectionItem; - } - - public override AnimationClip animationClip - { - set - { - base.animationClip = value; - } - get - { - if (animationPlayer == null) - return null; - - return base.animationClip; - } - } - - public override void Synchronize() - { - if (rootGameObject != null) - { - AnimationClip[] allClips = AnimationUtility.GetAnimationClips(rootGameObject); - if (allClips.Length > 0) - { - if (!Array.Exists(allClips, x => x == animationClip)) - { - animationClip = allClips[0]; - } - } - else - { - animationClip = null; - } - } - } - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/IAnimationContextualResponder.cs b/Editor/Mono/Animation/AnimationWindow/IAnimationContextualResponder.cs deleted file mode 100644 index 9070b0ecf8..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/IAnimationContextualResponder.cs +++ /dev/null @@ -1,37 +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 UnityEditor; -using Object = UnityEngine.Object; - -namespace UnityEditorInternal -{ - // Required information for animation recording. - internal interface IAnimationContextualResponder - { - bool IsAnimatable(PropertyModification[] modifications); - bool IsEditable(Object targetObject); - - bool KeyExists(PropertyModification[] modifications); - bool CandidateExists(PropertyModification[] modifications); - - bool CurveExists(PropertyModification[] modifications); - - bool HasAnyCandidates(); - bool HasAnyCurves(); - - void AddKey(PropertyModification[] modifications); - void RemoveKey(PropertyModification[] modifications); - - void RemoveCurve(PropertyModification[] modifications); - - void AddCandidateKeys(); - void AddAnimatedKeys(); - - void GoToNextKeyframe(PropertyModification[] modifications); - void GoToPreviousKeyframe(PropertyModification[] modifications); - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/IAnimationRecordingState.cs b/Editor/Mono/Animation/AnimationWindow/IAnimationRecordingState.cs deleted file mode 100644 index 8458aab6dd..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/IAnimationRecordingState.cs +++ /dev/null @@ -1,28 +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 System.Text; -using UnityEngine; -using UnityEditor; - -namespace UnityEditorInternal -{ - // Required information for animation recording. - internal interface IAnimationRecordingState - { - GameObject activeGameObject { get; } - GameObject activeRootGameObject { get; } - AnimationClip activeAnimationClip { get; } - int currentFrame { get; } - - bool addZeroFrame { get; } - - bool DiscardModification(PropertyModification modification); - void SaveCurve(AnimationWindowCurve curve); - void AddPropertyModification(EditorCurveBinding binding, PropertyModification propertyModification, bool keepPrefabOverride); - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/IAnimationWindowControl.cs b/Editor/Mono/Animation/AnimationWindow/IAnimationWindowControl.cs deleted file mode 100644 index 356bc4fb30..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/IAnimationWindowControl.cs +++ /dev/null @@ -1,56 +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 UnityEditor; -using Object = UnityEngine.Object; - -namespace UnityEditorInternal -{ - internal abstract class IAnimationWindowControl : ScriptableObject - { - public virtual void OnEnable() { hideFlags = HideFlags.HideAndDontSave; } - public abstract void OnSelectionChanged(); - - public abstract AnimationKeyTime time { get; } - - public abstract void GoToTime(float time); - public abstract void GoToFrame(int frame); - - public abstract void StartScrubTime(); - public abstract void ScrubTime(float time); - public abstract void EndScrubTime(); - - public abstract void GoToPreviousFrame(); - public abstract void GoToNextFrame(); - public abstract void GoToPreviousKeyframe(); - public abstract void GoToNextKeyframe(); - public abstract void GoToFirstKeyframe(); - public abstract void GoToLastKeyframe(); - - public abstract bool canPlay { get; } - public abstract bool playing { get; } - - public abstract bool StartPlayback(); - public abstract void StopPlayback(); - public abstract bool PlaybackUpdate(); - - public abstract bool canPreview { get; } - public abstract bool previewing { get; } - - public abstract bool StartPreview(); - public abstract void StopPreview(); - - public abstract bool canRecord { get; } - public abstract bool recording { get; } - - public abstract bool StartRecording(Object targetObject); - public abstract void StopRecording(); - public abstract void ResampleAnimation(); - - public abstract void ProcessCandidates(); - public abstract void ClearCandidates(); - } -} diff --git a/Editor/Mono/Animation/AnimationWindow/RotationCurveInterpolation.cs b/Editor/Mono/Animation/AnimationWindow/RotationCurveInterpolation.cs deleted file mode 100644 index 6405421094..0000000000 --- a/Editor/Mono/Animation/AnimationWindow/RotationCurveInterpolation.cs +++ /dev/null @@ -1,286 +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 UnityEditorInternal; -using UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class RotationCurveInterpolation - { - public struct State - { - public bool allAreNonBaked; - public bool allAreBaked; - public bool allAreRaw; - public bool allAreRotations; - } - - public static char[] kPostFix = { 'x', 'y', 'z', 'w' }; - - public enum Mode { Baked, NonBaked, RawQuaternions, RawEuler, Undefined } - - public static Mode GetModeFromCurveData(EditorCurveBinding data) - { - if (AnimationWindowUtility.IsTransformType(data.type) && data.propertyName.StartsWith("localEulerAngles")) - { - if (data.propertyName.StartsWith("localEulerAnglesBaked")) - return Mode.Baked; - else if (data.propertyName.StartsWith("localEulerAnglesRaw")) - return Mode.RawEuler; - else - return Mode.NonBaked; - } - else if (AnimationWindowUtility.IsTransformType(data.type) && data.propertyName.StartsWith("m_LocalRotation")) - return Mode.RawQuaternions; - - return Mode.Undefined; - } - - // Extracts the interpolation state for the selection from the clip - public static State GetCurveState(AnimationClip clip, EditorCurveBinding[] selection) - { - State state; - state.allAreRaw = true; - state.allAreNonBaked = true; - state.allAreBaked = true; - state.allAreRotations = true; - - foreach (EditorCurveBinding data in selection) - { - Mode mode = GetModeFromCurveData(data); - state.allAreBaked &= (mode == Mode.Baked); - state.allAreNonBaked &= (mode == Mode.NonBaked); - state.allAreRaw &= mode == (Mode.RawEuler); - state.allAreRotations &= mode != (Mode.Undefined); - } - - return state; - } - - public static int GetCurveIndexFromName(string name) - { - return ExtractComponentCharacter(name) - 'x'; - } - - public static char ExtractComponentCharacter(string name) - { - return name[name.Length - 1]; - } - - public static string GetPrefixForInterpolation(Mode newInterpolationMode) - { - if (newInterpolationMode == Mode.Baked) - return "localEulerAnglesBaked"; - else if (newInterpolationMode == Mode.NonBaked) - return "localEulerAngles"; - else if (newInterpolationMode == Mode.RawEuler) - return "localEulerAnglesRaw"; - else if (newInterpolationMode == Mode.RawQuaternions) - return "m_LocalRotation"; - else - return null; - } - - internal static EditorCurveBinding[] ConvertRotationPropertiesToDefaultInterpolation(AnimationClip clip, EditorCurveBinding[] selection) - { - var mode = clip.legacy ? Mode.Baked : Mode.RawEuler; - return ConvertRotationPropertiesToInterpolationType(selection, mode); - } - - internal static EditorCurveBinding[] ConvertRotationPropertiesToInterpolationType(EditorCurveBinding[] selection, Mode newInterpolationMode) - { - if (selection.Length != 4) - return selection; - - if (GetModeFromCurveData(selection[0]) == Mode.RawQuaternions) - { - EditorCurveBinding[] newCurves = new EditorCurveBinding[3]; - newCurves[0] = selection[0]; - newCurves[1] = selection[1]; - newCurves[2] = selection[2]; - - string prefix = GetPrefixForInterpolation(newInterpolationMode); - newCurves[0].propertyName = prefix + ".x"; - newCurves[1].propertyName = prefix + ".y"; - newCurves[2].propertyName = prefix + ".z"; - - return newCurves; - } - else - return selection; - } - - static EditorCurveBinding[] GenerateTransformCurveBindingArray(string path, string property, Type type, int count) - { - EditorCurveBinding[] bindings = new EditorCurveBinding[count]; - for (int i = 0; i < count; i++) - bindings[i] = EditorCurveBinding.FloatCurve(path, type, property + kPostFix[i]); - return bindings; - } - - static public EditorCurveBinding[] RemapAnimationBindingForAddKey(EditorCurveBinding binding, AnimationClip clip) - { - if (!AnimationWindowUtility.IsTransformType(binding.type)) - { - return null; - } - else if (binding.propertyName.StartsWith("m_LocalPosition.")) - { - if (binding.type == typeof(Transform)) - return GenerateTransformCurveBindingArray(binding.path, "m_LocalPosition.", binding.type, 3); - else - return null; - } - else if (binding.propertyName.StartsWith("m_LocalScale.")) - return GenerateTransformCurveBindingArray(binding.path, "m_LocalScale.", binding.type, 3); - else if (binding.propertyName.StartsWith("m_LocalRotation")) - { - return SelectRotationBindingForAddKey(binding, clip); - } - else - return null; - } - - static public EditorCurveBinding[] RemapAnimationBindingForRotationAddKey(EditorCurveBinding binding, AnimationClip clip) - { - if (!AnimationWindowUtility.IsTransformType(binding.type)) - { - return null; - } - else if (binding.propertyName.StartsWith("m_LocalRotation")) - { - return SelectRotationBindingForAddKey(binding, clip); - } - else - return null; - } - - static private EditorCurveBinding[] SelectRotationBindingForAddKey(EditorCurveBinding binding, AnimationClip clip) - { - EditorCurveBinding testBinding = binding; - testBinding.propertyName = "localEulerAnglesBaked.x"; - if (AnimationUtility.GetEditorCurve(clip, testBinding) != null) - return GenerateTransformCurveBindingArray(binding.path, "localEulerAnglesBaked.", binding.type, 3); - else - { - testBinding.propertyName = "localEulerAngles.x"; - if (AnimationUtility.GetEditorCurve(clip, testBinding) != null) - { - return GenerateTransformCurveBindingArray(binding.path, "localEulerAngles.", binding.type, 3); - } - else - { - testBinding.propertyName = "localEulerAnglesRaw.x"; - if (clip.legacy && AnimationUtility.GetEditorCurve(clip, testBinding) == null) - return GenerateTransformCurveBindingArray(binding.path, "localEulerAnglesBaked.", binding.type, 3); - - return GenerateTransformCurveBindingArray(binding.path, "localEulerAnglesRaw.", binding.type, 3); - } - } - } - - static public EditorCurveBinding RemapAnimationBindingForRotationCurves(EditorCurveBinding curveBinding, AnimationClip clip) - { - if (!AnimationWindowUtility.IsTransformType(curveBinding.type)) - return curveBinding; - - // Convert rotation binding to valid editor curve binding. - // Only a single rotation binding (RawEuler, Baked or NonBaked) should be allowed in one clip. - // RawQuaternions should be converted to appropriate euler bindings if available. - Mode mode = GetModeFromCurveData(curveBinding); - if (mode != Mode.Undefined) - { - string suffix = curveBinding.propertyName.Split('.')[1]; - - EditorCurveBinding newBinding = curveBinding; - - if (mode != Mode.NonBaked) - { - newBinding.propertyName = GetPrefixForInterpolation(Mode.NonBaked) + "." + suffix; - AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, newBinding); - if (curve != null) - return newBinding; - } - - if (mode != Mode.Baked) - { - newBinding.propertyName = GetPrefixForInterpolation(Mode.Baked) + "." + suffix; - AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, newBinding); - if (curve != null) - return newBinding; - } - - if (mode != Mode.RawEuler) - { - newBinding.propertyName = GetPrefixForInterpolation(Mode.RawEuler) + "." + suffix; - AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, newBinding); - if (curve != null) - return newBinding; - } - - return curveBinding; - } - else - return curveBinding; - } - - internal static void SetInterpolation(AnimationClip clip, EditorCurveBinding[] curveBindings, Mode newInterpolationMode) - { - Undo.RegisterCompleteObjectUndo(clip, "Rotation Interpolation"); - - if (clip.legacy && newInterpolationMode == Mode.RawEuler) - { - Debug.LogWarning("Warning, Euler Angles interpolation mode is not fully supported for Legacy animation clips. If you mix clips using Euler Angles interpolation with clips using other interpolation modes (using Animation.CrossFade, Animation.Blend or other methods), you will get erroneous results. Use with caution.", clip); - } - List newCurvesBindings = new List(); - List newCurveDatas = new List(); - List oldCurvesBindings = new List(); - - foreach (EditorCurveBinding curveBinding in curveBindings) - { - Mode currentMode = GetModeFromCurveData(curveBinding); - - if (currentMode == Mode.Undefined) - continue; - - if (currentMode == Mode.RawQuaternions) - { - Debug.LogWarning("Can't convert quaternion curve: " + curveBinding.propertyName); - continue; - } - - AnimationCurve curve = AnimationUtility.GetEditorCurve(clip, curveBinding); - - if (curve == null) - continue; - - string newPropertyPath = GetPrefixForInterpolation(newInterpolationMode) + '.' + ExtractComponentCharacter(curveBinding.propertyName); - - EditorCurveBinding newBinding = new EditorCurveBinding(); - newBinding.propertyName = newPropertyPath; - newBinding.type = curveBinding.type; - newBinding.path = curveBinding.path; - newCurvesBindings.Add(newBinding); - newCurveDatas.Add(curve); - - EditorCurveBinding removeCurve = new EditorCurveBinding(); - removeCurve.propertyName = curveBinding.propertyName; - removeCurve.type = curveBinding.type; - removeCurve.path = curveBinding.path; - oldCurvesBindings.Add(removeCurve); - } - - Undo.RegisterCompleteObjectUndo(clip, "Rotation Interpolation"); - - foreach (EditorCurveBinding binding in oldCurvesBindings) - AnimationUtility.SetEditorCurve(clip, binding, null); - - foreach (EditorCurveBinding binding in newCurvesBindings) - AnimationUtility.SetEditorCurve(clip, binding, newCurveDatas[newCurvesBindings.IndexOf(binding)]); - } - } -} diff --git a/Editor/Mono/Animation/BlendTree.cs b/Editor/Mono/Animation/BlendTree.cs deleted file mode 100644 index 70ba96bbf2..0000000000 --- a/Editor/Mono/Animation/BlendTree.cs +++ /dev/null @@ -1,95 +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 System.Collections.Generic; -using UnityEditor; -using UnityEditor.Animations; -using System.Linq; - -namespace UnityEditor.Animations -{ - [ExcludeFromPreset] - public partial class BlendTree : Motion - { - public void AddChild(Motion motion) - { - AddChild(motion, Vector2.zero, 0); - } - - public void AddChild(Motion motion, Vector2 position) - { - AddChild(motion, position, 0); - } - - public void AddChild(Motion motion, float threshold) - { - AddChild(motion, Vector2.zero, threshold); - } - - public void RemoveChild(int index) - { - Undo.RecordObject(this, "Remove Child"); - ChildMotion[] childMotions = children; - ArrayUtility.RemoveAt(ref childMotions, index); - children = childMotions; - } - - internal void AddChild(Motion motion, Vector2 position, float threshold) - { - Undo.RecordObject(this, "Added BlendTree Child"); - ChildMotion[] childMotions = children; - ChildMotion newMotion = new ChildMotion(); - newMotion.timeScale = 1; - newMotion.motion = motion; - newMotion.position = position; - newMotion.threshold = threshold; - newMotion.directBlendParameter = "Blend"; - ArrayUtility.Add(ref childMotions, newMotion); - children = childMotions; - } - - public BlendTree CreateBlendTreeChild(float threshold) - { - return CreateBlendTreeChild(Vector2.zero, threshold); - } - - public BlendTree CreateBlendTreeChild(Vector2 position) - { - return CreateBlendTreeChild(position, 0); - } - - internal bool HasChild(BlendTree childTree, bool recursive) - { - foreach (ChildMotion child in children) - { - if (child.motion == childTree) - { - return true; - } - - if (recursive && child.motion is BlendTree && (child.motion as BlendTree).HasChild(childTree, true)) - { - return true; - } - } - - return false; - } - - internal BlendTree CreateBlendTreeChild(Vector2 position, float threshold) - { - Undo.RecordObject(this, "Created BlendTree Child"); - - BlendTree tree = new BlendTree(); - tree.name = "BlendTree"; - tree.hideFlags = HideFlags.HideInHierarchy; - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(tree, AssetDatabase.GetAssetPath(this)); - - AddChild(tree, position, threshold); - return tree; - } - } -} diff --git a/Editor/Mono/Animation/GameObjectRecorder.bindings.cs b/Editor/Mono/Animation/GameObjectRecorder.bindings.cs index c5ee0ddd49..de7c75bede 100644 --- a/Editor/Mono/Animation/GameObjectRecorder.bindings.cs +++ b/Editor/Mono/Animation/GameObjectRecorder.bindings.cs @@ -46,7 +46,17 @@ public void BindComponentsOfType(GameObject target, Type componentType, bool rec extern public GameObject root { get; } // Bindings. - extern public void Bind(EditorCurveBinding binding); + public void Bind(EditorCurveBinding binding) + { + if (!binding.type.IsSubclassOf(typeof(UnityEngine.Object))) + throw new InvalidCastException("Binding type should derive from Unity type."); + + BindInternal(binding); + } + + [NativeMethod("Bind")] + extern private void BindInternal(EditorCurveBinding binding); + extern public void BindAll(GameObject target, bool recursive); extern public void BindComponent([NotNull] Component component); diff --git a/Editor/Mono/Animation/MecanimUtilities.cs b/Editor/Mono/Animation/MecanimUtilities.cs deleted file mode 100644 index c4ec2ef7cc..0000000000 --- a/Editor/Mono/Animation/MecanimUtilities.cs +++ /dev/null @@ -1,49 +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 System.Collections; -using UnityEditor; -using System.Collections.Generic; -using System.Linq; - - -namespace UnityEditor.Animations -{ - internal class MecanimUtilities - { - public static bool StateMachineRelativePath(AnimatorStateMachine parent, AnimatorStateMachine toFind, - ref List hierarchy) - { - hierarchy.Add(parent); - if (parent == toFind) - return true; - var childStateMachines = AnimatorStateMachine.StateMachineCache.GetChildStateMachines(parent); - for (int i = 0; i < childStateMachines.Length; i++) - { - if (StateMachineRelativePath(childStateMachines[i].stateMachine, toFind, ref hierarchy)) - return true; - } - hierarchy.Remove(parent); - return false; - } - - internal static bool AreSameAsset(Object obj1, Object obj2) - { - return AssetDatabase.GetAssetPath(obj1) == AssetDatabase.GetAssetPath(obj2); - } - - internal static void DestroyBlendTreeRecursive(BlendTree blendTree) - { - for (int i = 0; i < blendTree.children.Length; i++) - { - BlendTree childBlendTree = blendTree.children[i].motion as BlendTree; - if (childBlendTree != null && AreSameAsset(blendTree, childBlendTree)) - DestroyBlendTreeRecursive(childBlendTree); - } - - Undo.DestroyObjectImmediate(blendTree); - } - } -} diff --git a/Editor/Mono/Animation/SerializedStringTable.cs b/Editor/Mono/Animation/SerializedStringTable.cs deleted file mode 100644 index 9e6117d278..0000000000 --- a/Editor/Mono/Animation/SerializedStringTable.cs +++ /dev/null @@ -1,71 +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 System.Collections; - -[System.Serializable] -internal class SerializedStringTable -{ - [SerializeField] private string[] keys; - [SerializeField] private int[] values; - private Hashtable table; - public Hashtable hashtable { get { SanityCheck(); return table; } } - - public int Length { get { SanityCheck(); return keys.Length; } } - - private void SanityCheck() - { - if (keys == null) - { - keys = new string[0]; - values = new int[0]; - } - if (table == null) - { - table = new Hashtable(); - for (int i = 0; i < keys.Length; i++) table[keys[i]] = values[i]; - } - } - - private void SynchArrays() - { - keys = new string[table.Count]; - values = new int[table.Count]; - table.Keys.CopyTo(keys, 0); - table.Values.CopyTo(values, 0); - } - - public void Set(string key, int value) - { - SanityCheck(); - table[key] = value; - SynchArrays(); - } - - public void Set(string key) - { - Set(key, 0); - } - - public bool Contains(string key) - { - SanityCheck(); - return table.Contains(key); - } - - public int Get(string key) - { - SanityCheck(); - if (!table.Contains(key)) return -1; - return (int)table[key]; - } - - public void Remove(string key) - { - SanityCheck(); - if (table.Contains(key)) table.Remove(key); - SynchArrays(); - } -} diff --git a/Editor/Mono/Animation/StateMachine.cs b/Editor/Mono/Animation/StateMachine.cs deleted file mode 100644 index 7fadf37c91..0000000000 --- a/Editor/Mono/Animation/StateMachine.cs +++ /dev/null @@ -1,721 +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 System.Collections.Generic; -using UnityEditor; -using System.Linq; - -namespace UnityEditor.Animations -{ - internal struct PushUndoIfNeeded - { - public bool pushUndo - { - get { return impl.m_PushUndo; } - set { impl.m_PushUndo = value; } - } - - public PushUndoIfNeeded(bool pushUndo) - { - m_Impl = new PushUndoIfNeededImpl(pushUndo); - } - - public void DoUndo(Object target, string undoOperation) - { - impl.DoUndo(target, undoOperation); - } - - PushUndoIfNeededImpl impl - { - get - { - if (m_Impl == null) - m_Impl = new PushUndoIfNeededImpl(true); - return m_Impl; - } - } - - PushUndoIfNeededImpl m_Impl; - - private class PushUndoIfNeededImpl - { - public PushUndoIfNeededImpl(bool pushUndo) - { - m_PushUndo = pushUndo; - } - - public void DoUndo(Object target, string undoOperation) - { - if (m_PushUndo) - { - Undo.RegisterCompleteObjectUndo(target, undoOperation); - } - } - - public bool m_PushUndo; - }; - } - - - public partial class AnimatorTransitionBase : Object - { - private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); - internal bool pushUndo { set { undoHandler.pushUndo = value; } } - - public void AddCondition(AnimatorConditionMode mode, float threshold, string parameter) - { - undoHandler.DoUndo(this, "Condition added"); - - AnimatorCondition[] conditionVector = conditions; - AnimatorCondition newCondition = new AnimatorCondition(); - newCondition.mode = mode; - newCondition.parameter = parameter; - newCondition.threshold = threshold; - - ArrayUtility.Add(ref conditionVector, newCondition); - conditions = conditionVector; - } - - public void RemoveCondition(AnimatorCondition condition) - { - undoHandler.DoUndo(this, "Condition removed"); - AnimatorCondition[] conditionVector = conditions; - ArrayUtility.Remove(ref conditionVector, condition); - conditions = conditionVector; - } - } - - - internal class AnimatorDefaultTransition : ScriptableObject - { - } - - public partial class AnimatorState : Object - { - private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); - internal bool pushUndo { set { undoHandler.pushUndo = value; } } - - - public void AddTransition(AnimatorStateTransition transition) - { - undoHandler.DoUndo(this, "Transition added"); - - AnimatorStateTransition[] transitionsVector = transitions; - ArrayUtility.Add(ref transitionsVector, transition); - transitions = transitionsVector; - } - - public void RemoveTransition(AnimatorStateTransition transition) - { - undoHandler.DoUndo(this, "Transition removed"); - - AnimatorStateTransition[] transitionsVector = transitions; - ArrayUtility.Remove(ref transitionsVector, transition); - transitions = transitionsVector; - - if (MecanimUtilities.AreSameAsset(this, transition)) - Undo.DestroyObjectImmediate(transition); - } - - private AnimatorStateTransition CreateTransition(bool setDefaultExitTime) - { - AnimatorStateTransition newTransition = new AnimatorStateTransition(); - newTransition.hasExitTime = false; - newTransition.hasFixedDuration = true; - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this)); - newTransition.hideFlags = HideFlags.HideInHierarchy; - - if (setDefaultExitTime) - SetDefaultTransitionExitTime(ref newTransition); - - return newTransition; - } - - private void SetDefaultTransitionExitTime(ref AnimatorStateTransition newTransition) - { - newTransition.hasExitTime = true; - - if (motion != null && motion.averageDuration > 0.0f) - { - const float transitionDefaultDuration = 0.25f; - float transitionDurationNormalized = transitionDefaultDuration / motion.averageDuration; - newTransition.duration = transitionDefaultDuration; - newTransition.exitTime = 1.0f - transitionDurationNormalized; - } - else - { - newTransition.duration = 0.25f; - newTransition.exitTime = 0.75f; - } - } - - public AnimatorStateTransition AddTransition(AnimatorState destinationState) - { - AnimatorStateTransition newTransition = CreateTransition(false); - newTransition.destinationState = destinationState; - AddTransition(newTransition); - return newTransition; - } - - public AnimatorStateTransition AddTransition(AnimatorStateMachine destinationStateMachine) - { - AnimatorStateTransition newTransition = CreateTransition(false); - newTransition.destinationStateMachine = destinationStateMachine; - AddTransition(newTransition); - return newTransition; - } - - public AnimatorStateTransition AddTransition(AnimatorState destinationState, bool defaultExitTime) - { - AnimatorStateTransition newTransition = CreateTransition(defaultExitTime); - newTransition.destinationState = destinationState; - AddTransition(newTransition); - return newTransition; - } - - public AnimatorStateTransition AddTransition(AnimatorStateMachine destinationStateMachine, bool defaultExitTime) - { - AnimatorStateTransition newTransition = CreateTransition(defaultExitTime); - newTransition.destinationStateMachine = destinationStateMachine; - AddTransition(newTransition); - return newTransition; - } - - public AnimatorStateTransition AddExitTransition() - { - return AddExitTransition(false); - } - - public AnimatorStateTransition AddExitTransition(bool defaultExitTime) - { - AnimatorStateTransition newTransition = CreateTransition(defaultExitTime); - newTransition.isExit = true; - AddTransition(newTransition); - return newTransition; - } - - internal AnimatorStateMachine FindParent(AnimatorStateMachine root) - { - if (root.HasState(this, false)) return root; - else return root.stateMachinesRecursive.Find(sm => sm.stateMachine.HasState(this, false)).stateMachine; - } - - internal AnimatorStateTransition FindTransition(AnimatorState destinationState) // pp todo return a list? - { - return (new List(transitions)).Find(t => t.destinationState == destinationState); - } - - [System.Obsolete("uniqueName does not exist anymore. Consider using .name instead.", true)] - public string uniqueName - { - get { return ""; } - } - - [System.Obsolete("GetMotion() is obsolete. Use motion", true)] - public Motion GetMotion() - { - return null; - } - - [System.Obsolete("uniqueNameHash does not exist anymore.", true)] - public int uniqueNameHash - { - get { return -1; } - } - } - - public partial class AnimatorStateMachine : Object - { - private PushUndoIfNeeded undoHandler = new PushUndoIfNeeded(true); - internal bool pushUndo { set { undoHandler.pushUndo = value; } } - - internal class StateMachineCache - { - static Dictionary m_ChildStateMachines; - static bool m_Initialized; - - static void Init() - { - if (!m_Initialized) - { - m_ChildStateMachines = new Dictionary(); - m_Initialized = true; - } - } - - static public void Clear() - { - Init(); - m_ChildStateMachines.Clear(); - } - - static public ChildAnimatorStateMachine[] GetChildStateMachines(AnimatorStateMachine parent) - { - Init(); - - ChildAnimatorStateMachine[] children; - if (m_ChildStateMachines.TryGetValue(parent, out children) == false) - { - children = parent.stateMachines; - m_ChildStateMachines.Add(parent, children); - } - return children; - } - } - internal List statesRecursive - { - get - { - List ret = new List(); - ret.AddRange(states); - - for (int j = 0; j < stateMachines.Length; j++) - { - ret.AddRange(stateMachines[j].stateMachine.statesRecursive); - } - return ret; - } - } - - internal List stateMachinesRecursive - { - get - { - List ret = new List(); - var childStateMachines = AnimatorStateMachine.StateMachineCache.GetChildStateMachines(this); - ret.AddRange(childStateMachines); - - for (int j = 0; j < childStateMachines.Length; j++) - { - ret.AddRange(childStateMachines[j].stateMachine.stateMachinesRecursive); - } - return ret; - } - } - - internal List anyStateTransitionsRecursive - { - get - { - List childTransitions = new List(); - childTransitions.AddRange(anyStateTransitions); - - foreach (ChildAnimatorStateMachine stateMachine in stateMachines) - { - childTransitions.AddRange(stateMachine.stateMachine.anyStateTransitionsRecursive); - } - - return childTransitions; - } - } - - internal Vector3 GetStatePosition(AnimatorState state) - { - ChildAnimatorState[] animatorStates = states; - for (int i = 0; i < animatorStates.Length; i++) - if (state == animatorStates[i].state) - return animatorStates[i].position; - - System.Diagnostics.Debug.Fail("Can't find state (" + state.name + ") in parent state machine (" + name + ")."); - return Vector3.zero; - } - - internal void SetStatePosition(AnimatorState state, Vector3 position) - { - ChildAnimatorState[] childStates = states; - for (int i = 0; i < childStates.Length; i++) - if (state == childStates[i].state) - { - childStates[i].position = position; - states = childStates; - return; - } - - System.Diagnostics.Debug.Fail("Can't find state (" + state.name + ") in parent state machine (" + name + ")."); - } - - internal Vector3 GetStateMachinePosition(AnimatorStateMachine stateMachine) - { - ChildAnimatorStateMachine[] childSM = stateMachines; - for (int i = 0; i < childSM.Length; i++) - if (stateMachine == childSM[i].stateMachine) - return childSM[i].position; - - System.Diagnostics.Debug.Fail("Can't find state machine (" + stateMachine.name + ") in parent state machine (" + name + ")."); - - return Vector3.zero; - } - - internal void SetStateMachinePosition(AnimatorStateMachine stateMachine, Vector3 position) - { - ChildAnimatorStateMachine[] childSM = stateMachines; - for (int i = 0; i < childSM.Length; i++) - if (stateMachine == childSM[i].stateMachine) - { - childSM[i].position = position; - stateMachines = childSM; - return; - } - - System.Diagnostics.Debug.Fail("Can't find state machine (" + stateMachine.name + ") in parent state machine (" + name + ")."); - } - - public AnimatorState AddState(string name) - { - return AddState(name, states.Length > 0 ? states[states.Length - 1].position + new Vector3(35, 65) : new Vector3(200, 0, 0)); - } - - public AnimatorState AddState(string name, Vector3 position) - { - AnimatorState state = new AnimatorState(); - state.hideFlags = HideFlags.HideInHierarchy; - state.name = MakeUniqueStateName(name); - - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(state, AssetDatabase.GetAssetPath(this)); - - AddState(state, position); - - return state; - } - - public void AddState(AnimatorState state, Vector3 position) - { - ChildAnimatorState[] childStates = states; - if (System.Array.Exists(childStates, childState => childState.state == state)) - { - Debug.LogWarning(System.String.Format("State '{0}' already exists in state machine '{1}', discarding new state.", state.name, name)); - return; - } - - undoHandler.DoUndo(this, "State added"); - ChildAnimatorState newState = new ChildAnimatorState(); - newState.state = state; - newState.position = position; - - ArrayUtility.Add(ref childStates, newState); - states = childStates; - } - - public void RemoveState(AnimatorState state) - { - undoHandler.DoUndo(this, "State removed"); - undoHandler.DoUndo(state, "State removed"); - RemoveStateInternal(state); - } - - public AnimatorStateMachine AddStateMachine(string name) - { - return AddStateMachine(name, Vector3.zero); - } - - public AnimatorStateMachine AddStateMachine(string name, Vector3 position) - { - AnimatorStateMachine stateMachine = new AnimatorStateMachine(); - stateMachine.hideFlags = HideFlags.HideInHierarchy; - stateMachine.name = MakeUniqueStateMachineName(name); - - AddStateMachine(stateMachine, position); - - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(stateMachine, AssetDatabase.GetAssetPath(this)); - - return stateMachine; - } - - public void AddStateMachine(AnimatorStateMachine stateMachine, Vector3 position) - { - ChildAnimatorStateMachine[] childStateMachines = stateMachines; - if (System.Array.Exists(childStateMachines, childStateMachine => childStateMachine.stateMachine == stateMachine)) - { - Debug.LogWarning(System.String.Format("Sub state machine '{0}' already exists in state machine '{1}', discarding new state machine.", stateMachine.name, name)); - return; - } - - undoHandler.DoUndo(this, "StateMachine " + stateMachine.name + " added"); - ChildAnimatorStateMachine newStateMachine = new ChildAnimatorStateMachine(); - newStateMachine.stateMachine = stateMachine; - newStateMachine.position = position; - - ArrayUtility.Add(ref childStateMachines, newStateMachine); - stateMachines = childStateMachines; - } - - public void RemoveStateMachine(AnimatorStateMachine stateMachine) - { - undoHandler.DoUndo(this, "StateMachine removed"); - undoHandler.DoUndo(stateMachine, "StateMachine removed"); - RemoveStateMachineInternal(stateMachine); - } - - private AnimatorStateTransition AddAnyStateTransition() - { - undoHandler.DoUndo(this, "AnyState Transition Added"); - - AnimatorStateTransition[] transitionsVector = anyStateTransitions; - AnimatorStateTransition newTransition = new AnimatorStateTransition(); - newTransition.hasExitTime = false; - newTransition.hasFixedDuration = true; - newTransition.duration = 0.25f; - newTransition.exitTime = 0.75f; - - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this)); - - newTransition.hideFlags = HideFlags.HideInHierarchy; - ArrayUtility.Add(ref transitionsVector, newTransition); - anyStateTransitions = transitionsVector; - - - return newTransition; - } - - public AnimatorStateTransition AddAnyStateTransition(AnimatorState destinationState) - { - AnimatorStateTransition newTransition = AddAnyStateTransition(); - newTransition.destinationState = destinationState; - return newTransition; - } - - public AnimatorStateTransition AddAnyStateTransition(AnimatorStateMachine destinationStateMachine) - { - AnimatorStateTransition newTransition = AddAnyStateTransition(); - newTransition.destinationStateMachine = destinationStateMachine; - return newTransition; - } - - public bool RemoveAnyStateTransition(AnimatorStateTransition transition) - { - if ((new List(anyStateTransitions)).Any(t => t == transition)) - { - undoHandler.DoUndo(this, "AnyState Transition Removed"); - - AnimatorStateTransition[] transitionsVector = anyStateTransitions; - ArrayUtility.Remove(ref transitionsVector, transition); - anyStateTransitions = transitionsVector; - - if (MecanimUtilities.AreSameAsset(this, transition)) - Undo.DestroyObjectImmediate(transition); - - return true; - } - - return false; - } - - internal void RemoveAnyStateTransitionRecursive(AnimatorStateTransition transition) - { - if (RemoveAnyStateTransition(transition)) - return; - - List childStateMachines = stateMachinesRecursive; - foreach (ChildAnimatorStateMachine sm in childStateMachines) - { - if (sm.stateMachine.RemoveAnyStateTransition(transition)) - return; - } - } - - public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine) - { - AnimatorStateMachine sm = null; - return AddStateMachineTransition(sourceStateMachine, sm); - } - - public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorStateMachine destinationStateMachine) - { - undoHandler.DoUndo(this, "StateMachine Transition Added"); - - AnimatorTransition[] transitionsVector = GetStateMachineTransitions(sourceStateMachine); - AnimatorTransition newTransition = new AnimatorTransition(); - if (destinationStateMachine) - { - newTransition.destinationStateMachine = destinationStateMachine; - } - - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this)); - - newTransition.hideFlags = HideFlags.HideInHierarchy; - ArrayUtility.Add(ref transitionsVector, newTransition); - SetStateMachineTransitions(sourceStateMachine, transitionsVector); - - return newTransition; - } - - public AnimatorTransition AddStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorState destinationState) - { - AnimatorTransition newTransition = AddStateMachineTransition(sourceStateMachine); - newTransition.destinationState = destinationState; - return newTransition; - } - - public AnimatorTransition AddStateMachineExitTransition(AnimatorStateMachine sourceStateMachine) - { - AnimatorTransition newTransition = AddStateMachineTransition(sourceStateMachine); - newTransition.isExit = true; - return newTransition; - } - - public bool RemoveStateMachineTransition(AnimatorStateMachine sourceStateMachine, AnimatorTransition transition) - { - undoHandler.DoUndo(this, "StateMachine Transition Removed"); - - AnimatorTransition[] transitionsVector = GetStateMachineTransitions(sourceStateMachine); - int baseSize = transitionsVector.Length; - ArrayUtility.Remove(ref transitionsVector, transition); - SetStateMachineTransitions(sourceStateMachine, transitionsVector); - - if (MecanimUtilities.AreSameAsset(this, transition)) - Undo.DestroyObjectImmediate(transition); - - return baseSize != transitionsVector.Length; - } - - private AnimatorTransition AddEntryTransition() - { - undoHandler.DoUndo(this, "Entry Transition Added"); - AnimatorTransition[] transitionsVector = entryTransitions; - AnimatorTransition newTransition = new AnimatorTransition(); - - if (AssetDatabase.GetAssetPath(this) != "") - AssetDatabase.AddObjectToAsset(newTransition, AssetDatabase.GetAssetPath(this)); - - newTransition.hideFlags = HideFlags.HideInHierarchy; - ArrayUtility.Add(ref transitionsVector, newTransition); - entryTransitions = transitionsVector; - - return newTransition; - } - - public AnimatorTransition AddEntryTransition(AnimatorState destinationState) - { - AnimatorTransition newTransition = AddEntryTransition(); - newTransition.destinationState = destinationState; - return newTransition; - } - - public AnimatorTransition AddEntryTransition(AnimatorStateMachine destinationStateMachine) - { - AnimatorTransition newTransition = AddEntryTransition(); - newTransition.destinationStateMachine = destinationStateMachine; - return newTransition; - } - - public bool RemoveEntryTransition(AnimatorTransition transition) - { - if ((new List(entryTransitions)).Any(t => t == transition)) - { - undoHandler.DoUndo(this, "Entry Transition Removed"); - AnimatorTransition[] transitionsVector = entryTransitions; - ArrayUtility.Remove(ref transitionsVector, transition); - entryTransitions = transitionsVector; - - if (MecanimUtilities.AreSameAsset(this, transition)) - Undo.DestroyObjectImmediate(transition); - - return true; - } - - return false; - } - - internal ChildAnimatorState FindState(int nameHash) - { - return (new List(states)).Find(s => s.state.nameHash == nameHash); - } - - internal ChildAnimatorState FindState(string name) - { - return (new List(states)).Find(s => s.state.name == name); - } - - internal bool HasState(AnimatorState state) - { - return statesRecursive.Any(s => s.state == state); - } - - internal bool IsDirectParent(AnimatorStateMachine stateMachine) - { - return stateMachines.Any(sm => sm.stateMachine == stateMachine); - } - - internal bool HasStateMachine(AnimatorStateMachine child) - { - return stateMachinesRecursive.Any(sm => sm.stateMachine == child); - } - - internal bool HasTransition(AnimatorState stateA, AnimatorState stateB) - { - return stateA.transitions.Any(t => t.destinationState == stateB) || - stateB.transitions.Any(t => t.destinationState == stateA); - } - - internal AnimatorStateMachine FindParent(AnimatorStateMachine stateMachine) - { - if (stateMachines.Any(childSM => childSM.stateMachine == stateMachine)) - return this; - else - return stateMachinesRecursive.Find(sm => sm.stateMachine.stateMachines.Any(childSM => childSM.stateMachine == stateMachine)).stateMachine; - } - - internal AnimatorStateMachine FindStateMachine(string path) - { - string[] smNames = path.Split('.'); - - // first element is always Root statemachine 'this' - AnimatorStateMachine currentSM = this; - // last element is state name, we don't care - for (int i = 1; i < smNames.Length - 1 && currentSM != null; ++i) - { - var childStateMachines = AnimatorStateMachine.StateMachineCache.GetChildStateMachines(currentSM); - int index = System.Array.FindIndex(childStateMachines, t => t.stateMachine.name == smNames[i]); - currentSM = index >= 0 ? childStateMachines[index].stateMachine : null; - } - - return (currentSM == null) ? this : currentSM; - } - - internal AnimatorStateMachine FindStateMachine(AnimatorState state) - { - if (HasState(state, false)) - return this; - - List childStateMachines = stateMachinesRecursive; - int index = childStateMachines.FindIndex(sm => sm.stateMachine.HasState(state, false)); - return index >= 0 ? childStateMachines[index].stateMachine : null; - } - - internal AnimatorStateTransition FindTransition(AnimatorState destinationState) - { - return (new List(anyStateTransitions)).Find(t => t.destinationState == destinationState); - } - - [System.Obsolete("stateCount is obsolete. Use .states.Length instead.", true)] - int stateCount - { - get { return 0; } - } - - [System.Obsolete("stateMachineCount is obsolete. Use .stateMachines.Length instead.", true)] - int stateMachineCount - { - get { return 0; } - } - - [System.Obsolete("GetTransitionsFromState is obsolete. Use AnimatorState.transitions instead.", true)] - AnimatorState GetTransitionsFromState(AnimatorState state) - { - return null; - } - - [System.Obsolete("uniqueNameHash does not exist anymore.", true)] - int uniqueNameHash - { - get { return -1; } - } - } -} diff --git a/Editor/Mono/Animation/TickHandler.cs b/Editor/Mono/Animation/TickHandler.cs deleted file mode 100644 index f0ccffc3c3..0000000000 --- a/Editor/Mono/Animation/TickHandler.cs +++ /dev/null @@ -1,214 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - [System.Serializable] - internal class TickHandler - { - // Variables related to drawing tick markers - [SerializeField] private float[] m_TickModulos = new float[] {}; // array with possible modulo numbers to choose from - [SerializeField] private float[] m_TickStrengths = new float[] {}; // array with current strength of each modulo number - [SerializeField] private int m_SmallestTick = 0; // index of the currently smallest modulo number used to draw ticks - [SerializeField] private int m_BiggestTick = -1; // index of the currently biggest modulo number used to draw ticks - [SerializeField] private float m_MinValue = 0; // shownArea min (in curve space) - [SerializeField] private float m_MaxValue = 1; // shownArea max (in curve space) - [SerializeField] private float m_PixelRange = 1; // total width/height of curveeditor - - public int tickLevels { get { return m_BiggestTick - m_SmallestTick + 1; } } - - public void SetTickModulos(float[] tickModulos) - { - m_TickModulos = tickModulos; - } - - public List GetTickModulosForFrameRate(float frameRate) - { - List modulos; - - // Make frames multiples of 5 and 10, if frameRate is too high (avoid overflow) or not an even number - if (frameRate > int.MaxValue / 2.0f || frameRate != Mathf.Round(frameRate)) - { - modulos = new List - { - 1f / frameRate, - 5f / frameRate, - 10f / frameRate, - 50f / frameRate, - 100f / frameRate, - 500f / frameRate, - 1000f / frameRate, - 5000f / frameRate, - 10000f / frameRate, - 50000f / frameRate, - 100000f / frameRate, - 500000f / frameRate - }; - - return modulos; - } - - List dividers = new List(); - int divisor = 1; - while (divisor < frameRate) - { - if (Math.Abs(divisor - frameRate) < 1e-5) - break; - int multiple = Mathf.RoundToInt(frameRate / divisor); - if (multiple % 60 == 0) - { - divisor *= 2; - dividers.Add(divisor); - } - else if (multiple % 30 == 0) - { - divisor *= 3; - dividers.Add(divisor); - } - else if (multiple % 20 == 0) - { - divisor *= 2; - dividers.Add(divisor); - } - else if (multiple % 10 == 0) - { - divisor *= 2; - dividers.Add(divisor); - } - else if (multiple % 5 == 0) - { - divisor *= 5; - dividers.Add(divisor); - } - else if (multiple % 2 == 0) - { - divisor *= 2; - dividers.Add(divisor); - } - else if (multiple % 3 == 0) - { - divisor *= 3; - dividers.Add(divisor); - } - else - divisor = Mathf.RoundToInt(frameRate); - } - modulos = new List(13 + dividers.Count); - - for (int i = 0; i < dividers.Count; i++) - modulos.Add(1f / dividers[dividers.Count - i - 1]); - - // Ticks based on seconds - modulos.Add(1); - modulos.Add(5); - modulos.Add(10); - modulos.Add(30); - modulos.Add(60); - modulos.Add(60 * 5); - modulos.Add(60 * 10); - modulos.Add(60 * 30); - modulos.Add(3600); - modulos.Add(3600 * 6); - modulos.Add(3600 * 24); - modulos.Add(3600 * 24 * 7); - modulos.Add(3600 * 24 * 14); - return modulos; - } - - public void SetTickModulosForFrameRate(float frameRate) - { - var modulos = GetTickModulosForFrameRate(frameRate); - SetTickModulos(modulos.ToArray()); - } - - public void SetRanges(float minValue, float maxValue, float minPixel, float maxPixel) - { - m_MinValue = minValue; - m_MaxValue = maxValue; - m_PixelRange = maxPixel - minPixel; - } - - public float[] GetTicksAtLevel(int level, bool excludeTicksFromHigherlevels) - { - if (level < 0) - return new float[0] {}; - - int l = Mathf.Clamp(m_SmallestTick + level, 0, m_TickModulos.Length - 1); - List ticks = new List(); - int startTick = Mathf.FloorToInt(m_MinValue / m_TickModulos[l]); - int endTick = Mathf.CeilToInt(m_MaxValue / m_TickModulos[l]); - for (int i = startTick; i <= endTick; i++) - { - // Return if tick mark is at same time as larger tick mark - if (excludeTicksFromHigherlevels - && l < m_BiggestTick - && (i % Mathf.RoundToInt(m_TickModulos[l + 1] / m_TickModulos[l]) == 0)) - continue; - ticks.Add(i * m_TickModulos[l]); - } - return ticks.ToArray(); - } - - public float GetStrengthOfLevel(int level) - { - return m_TickStrengths[m_SmallestTick + level]; - } - - public float GetPeriodOfLevel(int level) - { - return m_TickModulos[Mathf.Clamp(m_SmallestTick + level, 0, m_TickModulos.Length - 1)]; - } - - public int GetLevelWithMinSeparation(float pixelSeparation) - { - for (int i = 0; i < m_TickModulos.Length; i++) - { - // How far apart (in pixels) these modulo ticks are spaced: - float tickSpacing = m_TickModulos[i] * m_PixelRange / (m_MaxValue - m_MinValue); - if (tickSpacing >= pixelSeparation) - return i - m_SmallestTick; - } - return -1; - } - - public void SetTickStrengths(float tickMinSpacing, float tickMaxSpacing, bool sqrt) - { - m_TickStrengths = new float[m_TickModulos.Length]; - m_SmallestTick = 0; - m_BiggestTick = m_TickModulos.Length - 1; - - // Find the strength for each modulo number tick marker - for (int i = m_TickModulos.Length - 1; i >= 0; i--) - { - // How far apart (in pixels) these modulo ticks are spaced: - float tickSpacing = m_TickModulos[i] * m_PixelRange / (m_MaxValue - m_MinValue); - - // Calculate the strength of the tick markers based on the spacing: - m_TickStrengths[i] = - (tickSpacing - tickMinSpacing) / (tickMaxSpacing - tickMinSpacing); - - // Beyond kTickHeightFatThreshold the ticks don't get any bigger or fatter, - // so ignore them, since they are already covered by smalle modulo ticks anyway: - if (m_TickStrengths[i] >= 1) m_BiggestTick = i; - - // Do not show tick markers less than 3 pixels apart: - if (tickSpacing <= tickMinSpacing) { m_SmallestTick = i; break; } - } - - // Use sqrt on actively used modulo number tick markers - for (int i = m_SmallestTick; i <= m_BiggestTick; i++) - { - m_TickStrengths[i] = Mathf.Clamp01(m_TickStrengths[i]); - if (sqrt) - m_TickStrengths[i] = Mathf.Sqrt(m_TickStrengths[i]); - } - } - } -} // namespace diff --git a/Editor/Mono/Animation/TickStyle.cs b/Editor/Mono/Animation/TickStyle.cs deleted file mode 100644 index cc9e3680e0..0000000000 --- a/Editor/Mono/Animation/TickStyle.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 UnityEngine; - -namespace UnityEditor -{ - [System.Serializable] - internal class TickStyle - { - public EditorGUIUtility.SkinnedColor tickColor = new EditorGUIUtility.SkinnedColor(new Color(0.0f, 0.0f, 0.0f, 0.2f), new Color(.45f, .45f, .45f, 0.2f)); // color and opacity of ticks - public EditorGUIUtility.SkinnedColor labelColor = new EditorGUIUtility.SkinnedColor(new Color(0.0f, 0.0f, 0.0f, 0.32f), new Color(0.8f, 0.8f, 0.8f, 0.32f)); // color and opacity of tick labels - public int distMin = 10; // min distance between ticks before they disappear completely - public int distFull = 80; // distance between ticks where they gain full strength - public int distLabel = 50; // min distance between tick labels - public bool stubs = false; // draw ticks as stubs or as full lines? - public bool centerLabel = false; // center label on tick lines - public string unit = ""; // unit to write after the number - } -} diff --git a/Editor/Mono/Animation/ZoomableArea.cs b/Editor/Mono/Animation/ZoomableArea.cs index 80017a2a7e..8ab4fd6020 100644 --- a/Editor/Mono/Animation/ZoomableArea.cs +++ b/Editor/Mono/Animation/ZoomableArea.cs @@ -377,14 +377,20 @@ public void SetShownHRange(float min, float max) public void SetShownVRangeInsideMargins(float min, float max) { + float heightInsideMargins = drawRect.height - topmargin - bottommargin; + if (heightInsideMargins < kMinHeight) heightInsideMargins = kMinHeight; + + float denum = max - min; + if (denum < kMinHeight) denum = kMinHeight; + if (m_UpDirection == YDirection.Positive) { - m_Scale.y = -(drawRect.height - topmargin - bottommargin) / (max - min); + m_Scale.y = -heightInsideMargins / denum; m_Translation.y = drawRect.height - min * m_Scale.y - topmargin; } else { - m_Scale.y = (drawRect.height - topmargin - bottommargin) / (max - min); + m_Scale.y = heightInsideMargins / denum; m_Translation.y = -min * m_Scale.y - bottommargin; } EnforceScaleAndRange(); @@ -392,14 +398,17 @@ public void SetShownVRangeInsideMargins(float min, float max) public void SetShownVRange(float min, float max) { + float denum = max - min; + if (denum < kMinHeight) denum = kMinHeight; + if (m_UpDirection == YDirection.Positive) { - m_Scale.y = -drawRect.height / (max - min); + m_Scale.y = -drawRect.height / denum; m_Translation.y = drawRect.height - min * m_Scale.y; } else { - m_Scale.y = drawRect.height / (max - min); + m_Scale.y = drawRect.height / denum; m_Translation.y = -min * m_Scale.y; } EnforceScaleAndRange(); @@ -983,5 +992,20 @@ public float PixelDeltaToTime(Rect rect) { return shownArea.width / rect.width; } + + public void UpdateZoomScale(float fMaxScaleValue, float fMinScaleValue) + { + // Update/reset the values of the scale to new zoom range, if the current values do not fall in the range of the new resolution + + if (m_Scale.y > fMaxScaleValue || m_Scale.y < fMinScaleValue) + { + m_Scale.y = m_Scale.y > fMaxScaleValue ? fMaxScaleValue : fMinScaleValue; + } + + if (m_Scale.x > fMaxScaleValue || m_Scale.x < fMinScaleValue) + { + m_Scale.x = m_Scale.x > fMaxScaleValue ? fMaxScaleValue : fMinScaleValue; + } + } } } // namespace diff --git a/Editor/Mono/AnimationCurvePreviewCache.bindings.cs b/Editor/Mono/AnimationCurvePreviewCache.bindings.cs deleted file mode 100644 index c81f80566e..0000000000 --- a/Editor/Mono/AnimationCurvePreviewCache.bindings.cs +++ /dev/null @@ -1,119 +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.Bindings; -using UnityEditor; - -namespace UnityEditorInternal -{ - [NativeHeader("Editor/Src/AnimationCurvePreviewCache.bindings.h")] - [NativeHeader("Editor/Src/Utility/SerializedProperty.h")] - [NativeHeader("Runtime/Graphics/Texture2D.h")] - [StaticAccessor("AnimationCurvePreviewCacheBindings", StaticAccessorType.DoubleColon)] - internal class AnimationCurvePreviewCache - { - // Regions as SerializedProperty - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Rect curveRanges) - { - return GetPreview(previewWidth, previewHeight, property, property2, color, Color.clear, Color.clear); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) - { - if (property2 == null) - return GetPropertyPreviewFilled(previewWidth, previewHeight, true, curveRanges, property, color, topFillColor, bottomFillColor); - else - return GetPropertyPreviewRegionFilled(previewWidth, previewHeight, true, curveRanges, property, property2, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color) - { - return GetPreview(previewWidth, previewHeight, property, property2, color, Color.clear, Color.clear); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, SerializedProperty property2, Color color, Color topFillColor, Color bottomFillColor) - { - if (property2 == null) - return GetPropertyPreviewFilled(previewWidth, previewHeight, false, new Rect(), property, color, topFillColor, bottomFillColor); - else - return GetPropertyPreviewRegionFilled(previewWidth, previewHeight, false, new Rect(), property, property2, color, topFillColor, bottomFillColor); - } - - // Regions as AnimationCurves - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) - { - return GetCurvePreviewRegionFilled(previewWidth, previewHeight, true, curveRanges, curve, curve2, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Rect curveRanges) - { - return GetPreview(previewWidth, previewHeight, curve, curve2, color, Color.clear, Color.clear, curveRanges); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color, Color topFillColor, Color bottomFillColor) - { - return GetCurvePreviewRegionFilled(previewWidth, previewHeight, false, new Rect(), curve, curve2, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, AnimationCurve curve2, Color color) - { - return GetPreview(previewWidth, previewHeight, curve, curve2, color, Color.clear, Color.clear, new Rect()); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) - { - return GetPropertyPreviewFilled(previewWidth, previewHeight, true, curveRanges, property, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Rect curveRanges) - { - return GetPreview(previewWidth, previewHeight, property, color, Color.clear, Color.clear, curveRanges); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color, Color topFillColor, Color bottomFillColor) - { - return GetPropertyPreviewFilled(previewWidth, previewHeight, false, new Rect(), property, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, SerializedProperty property, Color color) - { - return GetPreview(previewWidth, previewHeight, property, color, Color.clear, Color.clear, new Rect()); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Color topFillColor, Color bottomFillColor, Rect curveRanges) - { - return GetCurvePreviewFilled(previewWidth, previewHeight, true, curveRanges, curve, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Rect curveRanges) - { - return GetPreview(previewWidth, previewHeight, curve, color, Color.clear, Color.clear, curveRanges); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color, Color topFillColor, Color bottomFillColor) - { - return GetCurvePreviewFilled(previewWidth, previewHeight, false, new Rect(), curve, color, topFillColor, bottomFillColor); - } - - public static Texture2D GetPreview(int previewWidth, int previewHeight, AnimationCurve curve, Color color) - { - return GetPreview(previewWidth, previewHeight, curve, color, Color.clear, Color.clear, new Rect()); - } - - public static extern Texture2D GenerateCurvePreview(int previewWidth, int previewHeight, Rect curveRanges, AnimationCurve curve, Color color, Texture2D existingTexture); - - internal extern static void ClearCache(); - - private extern static Texture2D GetPropertyPreview(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, Color color); - private extern static Texture2D GetPropertyPreviewFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, Color color, Color topFillColor, Color bottomFillColor); - private extern static Texture2D GetPropertyPreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, SerializedProperty property2, Color color); - private extern static Texture2D GetPropertyPreviewRegionFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, SerializedProperty property, SerializedProperty property2, Color color, Color topFillColor, Color bottomFillColor); - private extern static Texture2D GetCurvePreview(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, Color color); - private extern static Texture2D GetCurvePreviewFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, Color color, Color topFillColor, Color bottomFillColor); - private extern static Texture2D GetCurvePreviewRegion(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, AnimationCurve curve2, Color color); - private extern static Texture2D GetCurvePreviewRegionFilled(int previewWidth, int previewHeight, bool useCurveRanges, Rect curveRanges, AnimationCurve curve, AnimationCurve curve2, Color color, Color topFillColor, Color bottomFillColor); - } -} diff --git a/Editor/Mono/AnimatorController.bindings.cs b/Editor/Mono/AnimatorController.bindings.cs deleted file mode 100644 index 6c36bcf3e0..0000000000 --- a/Editor/Mono/AnimatorController.bindings.cs +++ /dev/null @@ -1,138 +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.Playables; -using UnityEngine.Animations; -using UnityEngine.Bindings; -using UnityEngine.Scripting; -using UnityEngineInternal; -using UnityEditor; -using System.Runtime.InteropServices; - -namespace UnityEditor.Animations -{ - [NativeHeader("Runtime/Animation/Animator.h")] - [NativeHeader("Editor/Src/Animation/StateMachineBehaviourScripting.h")] - [NativeHeader("Editor/Src/Animation/AnimatorController.bindings.h")] - [NativeHeader("Runtime/Animation/AnimatorController.h")] - public partial class AnimatorController : RuntimeAnimatorController - { - public AnimatorController() - { - Internal_Create(this); - } - - [FreeFunction("AnimatorControllerBindings::Internal_Create")] - extern private static void Internal_Create([Writable] AnimatorController self); - - extern public AnimatorControllerLayer[] layers - { - [FreeFunction(Name = "AnimatorControllerBindings::GetLayers", HasExplicitThis = true)] - get; - [FreeFunction(Name = "AnimatorControllerBindings::SetLayers", HasExplicitThis = true)] - set; - } - - extern public AnimatorControllerParameter[] parameters - { - [FreeFunction(Name = "AnimatorControllerBindings::GetParameters", HasExplicitThis = true)] - get; - [FreeFunction(Name = "AnimatorControllerBindings::SetParameters", HasExplicitThis = true)] - set; - } - - [FreeFunction(Name = "AnimatorControllerBindings::GetEffectiveAnimatorController")] - extern internal static AnimatorController GetEffectiveAnimatorController(Animator animator); - - - internal static AnimatorControllerPlayable FindAnimatorControllerPlayable(Animator animator, AnimatorController controller) - { - PlayableHandle handle = new PlayableHandle(); - Internal_FindAnimatorControllerPlayable(ref handle, animator, controller); - if (!handle.IsValid()) - return AnimatorControllerPlayable.Null; - return new AnimatorControllerPlayable(handle); - } - - [FreeFunction(Name = "AnimatorControllerBindings::Internal_FindAnimatorControllerPlayable")] - extern internal static void Internal_FindAnimatorControllerPlayable(ref PlayableHandle ret, Animator animator, AnimatorController controller); - - public static void SetAnimatorController(Animator animator, AnimatorController controller) - { - animator.runtimeAnimatorController = controller; - } - - extern internal int IndexOfParameter(string name); - extern internal void RenameParameter(string prevName, string newName); - extern public string MakeUniqueParameterName(string name); - extern public string MakeUniqueLayerName(string name); - - static public StateMachineBehaviourContext[] FindStateMachineBehaviourContext(StateMachineBehaviour behaviour) - { - return Internal_FindStateMachineBehaviourContext(behaviour); - } - - [FreeFunction("FindStateMachineBehaviourContext")] - extern internal static StateMachineBehaviourContext[] Internal_FindStateMachineBehaviourContext(ScriptableObject behaviour); - - [FreeFunction("AnimatorControllerBindings::Internal_CreateStateMachineBehaviour")] - extern public static int CreateStateMachineBehaviour(MonoScript script); - - [FreeFunction("AnimatorControllerBindings::CanAddStateMachineBehaviours")] - extern internal static bool CanAddStateMachineBehaviours(); - - extern internal MonoScript GetBehaviourMonoScript(AnimatorState state, int layerIndex, int behaviourIndex); - - [FreeFunction] - extern private static ScriptableObject ScriptingAddStateMachineBehaviourWithType(Type stateMachineBehaviourType, AnimatorController controller, AnimatorState state, int layerIndex); - - - [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] - public StateMachineBehaviour AddEffectiveStateMachineBehaviour(Type stateMachineBehaviourType, AnimatorState state, int layerIndex) - { - return (StateMachineBehaviour)ScriptingAddStateMachineBehaviourWithType(stateMachineBehaviourType, this, state, layerIndex); - } - - public T AddEffectiveStateMachineBehaviour(AnimatorState state, int layerIndex) where T : StateMachineBehaviour - { - return AddEffectiveStateMachineBehaviour(typeof(T), state, layerIndex) as T; - } - - public T[] GetBehaviours() where T : StateMachineBehaviour - { - return ConvertStateMachineBehaviour(InternalGetBehaviours(typeof(T))); - } - - [FreeFunction(Name = "AnimatorControllerBindings::Internal_GetBehaviours", HasExplicitThis = true)] - extern internal ScriptableObject[] InternalGetBehaviours([NotNull] Type type); - - internal static T[] ConvertStateMachineBehaviour(ScriptableObject[] rawObjects) where T : StateMachineBehaviour - { - if (rawObjects == null) return null; - T[] typedObjects = new T[rawObjects.Length]; - for (int i = 0; i < typedObjects.Length; i++) - typedObjects[i] = (T)rawObjects[i]; - return typedObjects; - } - - extern internal UnityEngine.Object[] CollectObjectsUsingParameter(string parameterName); - - internal extern bool isAssetBundled - { - [NativeName("IsAssetBundled")] - get; - } - - extern internal void AddStateEffectiveBehaviour([NotNull] AnimatorState state, int layerIndex, int instanceID); - extern internal void RemoveStateEffectiveBehaviour([NotNull] AnimatorState state, int layerIndex, int behaviourIndex); - - [FreeFunction(Name = "AnimatorControllerBindings::Internal_GetEffectiveBehaviours", HasExplicitThis = true)] - extern internal ScriptableObject[] Internal_GetEffectiveBehaviours([NotNull] AnimatorState state, int layerIndex); - - [FreeFunction(Name = "AnimatorControllerBindings::Internal_SetEffectiveBehaviours", HasExplicitThis = true)] - extern internal void Internal_SetEffectiveBehaviours([NotNull] AnimatorState state, int layerIndex, ScriptableObject[] behaviours); - } -} diff --git a/Editor/Mono/AnimatorControllerLayer.bindings.cs b/Editor/Mono/AnimatorControllerLayer.bindings.cs deleted file mode 100644 index 383ea6cfa0..0000000000 --- a/Editor/Mono/AnimatorControllerLayer.bindings.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.Bindings; -using UnityEngine.Scripting; -using UnityEditor; -using System.Runtime.InteropServices; - -namespace UnityEditor.Animations -{ - public enum AnimatorLayerBlendingMode - { - Override = 0, - Additive = 1, - } - - [NativeHeader("Editor/Src/Animation/AnimatorControllerLayer.h")] - [NativeHeader("Editor/Src/Animation/AnimatorControllerLayer.bindings.h")] - [StructLayout(LayoutKind.Sequential)] - [NativeType(CodegenOptions.Custom, "MonoStateMotionPair")] - internal struct StateMotionPair - { - public AnimatorState m_State; - public Motion m_Motion; - } - - [NativeHeader("Editor/Src/Animation/AnimatorControllerLayer.h")] - [NativeHeader("Editor/Src/Animation/AnimatorControllerLayer.bindings.h")] - [StructLayout(LayoutKind.Sequential)] - [NativeType(CodegenOptions.Custom, "MonoStateBehavioursPair")] - internal struct StateBehavioursPair - { - public AnimatorState m_State; - public ScriptableObject[] m_Behaviours; - } - - [NativeHeader("Editor/Src/Animation/AnimatorControllerLayer.h")] - [NativeHeader("Editor/Src/Animation/AnimatorControllerLayer.bindings.h")] - [StructLayout(LayoutKind.Sequential)] - [NativeAsStruct] - [NativeType(CodegenOptions.Custom, "MonoAnimatorControllerLayer")] - public partial class AnimatorControllerLayer - { - public string name { get { return m_Name; } set { m_Name = value; } } - public AnimatorStateMachine stateMachine { get { return m_StateMachine; } set { m_StateMachine = value; } } - public AvatarMask avatarMask { get { return m_AvatarMask; } set { m_AvatarMask = value; } } - public AnimatorLayerBlendingMode blendingMode { get { return m_BlendingMode; } set { m_BlendingMode = value; } } - public int syncedLayerIndex { get { return m_SyncedLayerIndex; } set { m_SyncedLayerIndex = value; } } - public bool iKPass { get { return m_IKPass; } set { m_IKPass = value; } } - public float defaultWeight { get { return m_DefaultWeight; } set { m_DefaultWeight = value; } } - public bool syncedLayerAffectsTiming { get { return m_SyncedLayerAffectsTiming; } set { m_SyncedLayerAffectsTiming = value; }} - - public Motion GetOverrideMotion(AnimatorState state) - { - if (m_Motions != null) - foreach (StateMotionPair pair in m_Motions) - if (pair.m_State == state) - return pair.m_Motion; - - return null; - } - - public void SetOverrideMotion(AnimatorState state, Motion motion) - { - if (m_Motions == null) m_Motions = new StateMotionPair[] {}; - for (int i = 0; i < m_Motions.Length; ++i) - { - if (m_Motions[i].m_State == state) - { - m_Motions[i].m_Motion = motion; - return; - } - } - - StateMotionPair newPair; - newPair.m_State = state; - newPair.m_Motion = motion; - ArrayUtility.Add(ref m_Motions, newPair); - } - - public StateMachineBehaviour[] GetOverrideBehaviours(AnimatorState state) - { - if (m_Behaviours != null) - { - foreach (StateBehavioursPair pair in m_Behaviours) - { - if (pair.m_State == state) - return pair.m_Behaviours as StateMachineBehaviour[]; - } - } - return new StateMachineBehaviour[0]; - } - - public void SetOverrideBehaviours(AnimatorState state, StateMachineBehaviour[] behaviours) - { - if (m_Behaviours == null) m_Behaviours = new StateBehavioursPair[] {}; - for (int i = 0; i < m_Behaviours.Length; ++i) - { - if (m_Behaviours[i].m_State == state) - { - m_Behaviours[i].m_Behaviours = behaviours; - return; - } - } - - StateBehavioursPair newPair; - newPair.m_State = state; - newPair.m_Behaviours = behaviours; - ArrayUtility.Add(ref m_Behaviours, newPair); - } - - string m_Name; - AnimatorStateMachine m_StateMachine; - AvatarMask m_AvatarMask; - StateMotionPair[] m_Motions; - StateBehavioursPair[] m_Behaviours; - AnimatorLayerBlendingMode m_BlendingMode; - int m_SyncedLayerIndex = -1; - bool m_IKPass; - float m_DefaultWeight; - bool m_SyncedLayerAffectsTiming; - } -} diff --git a/Editor/Mono/AssemblyReloadEvents.cs b/Editor/Mono/AssemblyReloadEvents.cs deleted file mode 100644 index 9a908f5235..0000000000 --- a/Editor/Mono/AssemblyReloadEvents.cs +++ /dev/null @@ -1,29 +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.Scripting; - -namespace UnityEditor -{ - public static class AssemblyReloadEvents - { - public delegate void AssemblyReloadCallback(); - public static event AssemblyReloadCallback beforeAssemblyReload; - public static event AssemblyReloadCallback afterAssemblyReload; - - [RequiredByNativeCode] - static void OnBeforeAssemblyReload() - { - if (beforeAssemblyReload != null) - beforeAssemblyReload(); - } - - [RequiredByNativeCode] - static void OnAfterAssemblyReload() - { - if (afterAssemblyReload != null) - afterAssemblyReload(); - } - } -} diff --git a/Editor/Mono/AssetDatabase/AssetDatabase.cs b/Editor/Mono/AssetDatabase/AssetDatabase.cs deleted file mode 100644 index ebe376d4ee..0000000000 --- a/Editor/Mono/AssetDatabase/AssetDatabase.cs +++ /dev/null @@ -1,57 +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.Scripting; - -namespace UnityEditor -{ - public sealed partial class AssetDatabase - { - // Delegate to be called from [[AssetDatabase.ImportPackage]] callbacks - public delegate void ImportPackageCallback(string packageName); - - // Delegate to be called from [[AssetDatabase.ImportPackage]] callbacks in the event of failure - public delegate void ImportPackageFailedCallback(string packageName, string errorMessage); - - // Delegate to be called when package import begins - public static event ImportPackageCallback importPackageStarted; - - // Delegate to be called when package import completes - public static event ImportPackageCallback importPackageCompleted; - - // Delegate to be called when package import is cancelled - public static event ImportPackageCallback importPackageCancelled; - - // Delegate to be called when package import fails - public static event ImportPackageFailedCallback importPackageFailed; - - [RequiredByNativeCode] - private static void Internal_CallImportPackageStarted(string packageName) - { - if (importPackageStarted != null) - importPackageStarted(packageName); - } - - [RequiredByNativeCode] - private static void Internal_CallImportPackageCompleted(string packageName) - { - if (importPackageCompleted != null) - importPackageCompleted(packageName); - } - - [RequiredByNativeCode] - private static void Internal_CallImportPackageCancelled(string packageName) - { - if (importPackageCancelled != null) - importPackageCancelled(packageName); - } - - [RequiredByNativeCode] - private static void Internal_CallImportPackageFailed(string packageName, string errorMessage) - { - if (importPackageFailed != null) - importPackageFailed(packageName, errorMessage); - } - } -} diff --git a/Editor/Mono/AssetDatabase/AssetDatabase.deprecated.cs b/Editor/Mono/AssetDatabase/AssetDatabase.deprecated.cs deleted file mode 100644 index 80ce597ddd..0000000000 --- a/Editor/Mono/AssetDatabase/AssetDatabase.deprecated.cs +++ /dev/null @@ -1,52 +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.Runtime.InteropServices; - -namespace UnityEditor -{ - partial class AssetDatabase - { - // Gets the path to the text .meta file associated with an asset - [Obsolete("GetTextMetaDataPathFromAssetPath has been renamed to GetTextMetaFilePathFromAssetPath (UnityUpgradable) -> GetTextMetaFilePathFromAssetPath(*)")] - public static string GetTextMetaDataPathFromAssetPath(string path) { return null; } - } - - // Used to be part of Asset Server, and public API for some reason. - [Obsolete("AssetStatus enum is not used anymore (Asset Server has been removed)")] - public enum AssetStatus - { - Calculating = -1, - ClientOnly = 0, - ServerOnly = 1, - Unchanged = 2, - Conflict = 3, - Same = 4, - NewVersionAvailable = 5, - NewLocalVersion = 6, - RestoredFromTrash = 7, - Ignored = 8, - BadState = 9 - } - - // Used to be part of Asset Server, and public API for some reason. - [Obsolete("AssetsItem class is not used anymore (Asset Server has been removed)")] - [StructLayout(LayoutKind.Sequential)] - [System.Serializable] - public sealed class AssetsItem - { - public string guid; - public string pathName; - public string message; - public string exportedAssetPath; - public string guidFolder; - public int enabled; - public int assetIsDir; - public int changeFlags; - public string previewPath; - public int exists; - } -} - diff --git a/Editor/Mono/AssetDatabase/AssetImportInProgressProxy.bindings.cs b/Editor/Mono/AssetDatabase/AssetImportInProgressProxy.bindings.cs deleted file mode 100644 index ede1d22e40..0000000000 --- a/Editor/Mono/AssetDatabase/AssetImportInProgressProxy.bindings.cs +++ /dev/null @@ -1,41 +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.Bindings; -using UnityEngine; - -namespace UnityEditor -{ - [NativeType(Header = "Modules/AssetDatabase/Editor/Public/AssetImportInProgressProxy.h")] - class AssetImportInProgressProxy : UnityEngine.Object - { - public extern GUID asset - { - [NativeMethod("GetAsset")] - get; - [NativeMethod("SetAsset")] - set; - } - - [NativeMethod] - public extern static bool IsProxyAsset(int instanceID); - } - - [CustomEditor(typeof(AssetImportInProgressProxy))] - class AssetImportInProgressProxyEditor : Editor - { - public override void OnInspectorGUI() - { - var proxy = (AssetImportInProgressProxy)target; - - if (GUILayout.Button("Import")) - { - var mainAsset = AssetDatabase.LoadMainAssetAtGUID(proxy.asset); - Selection.activeObject = mainAsset; - //@TODO: Properly call this from C++ when asset import completes... - //EditorApplication.projectWindowChanged(); - } - } - } -} diff --git a/Editor/Mono/AssetPipeline/AssemblyDefinitionImporter.cs b/Editor/Mono/AssetPipeline/AssemblyDefinitionImporter.cs deleted file mode 100644 index 850f67d5e6..0000000000 --- a/Editor/Mono/AssetPipeline/AssemblyDefinitionImporter.cs +++ /dev/null @@ -1,20 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditorInternal -{ - public sealed partial class AssemblyDefinitionImporter : AssetImporter - { - } - - public sealed partial class AssemblyDefinitionAsset : TextAsset - { - private AssemblyDefinitionAsset() {} - - private AssemblyDefinitionAsset(string text) {} - } -} diff --git a/Editor/Mono/AssetPipeline/AssetImporter.bindings.cs b/Editor/Mono/AssetPipeline/AssetImporter.bindings.cs deleted file mode 100644 index 1ce6f36838..0000000000 --- a/Editor/Mono/AssetPipeline/AssetImporter.bindings.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 System.Collections.Generic; -using UnityEngine; -using Object = UnityEngine.Object; -using UnityEngine.Bindings; - -namespace UnityEditor -{ - [NativeHeader("Editor/Src/AssetPipeline/AssetImporter.h")] - [NativeHeader("Editor/Src/AssetPipeline/AssetImporter.bindings.h")] - [ExcludeFromObjectFactory] - public partial class AssetImporter : Object - { - [NativeType(CodegenOptions.Custom, "MonoSourceAssetIdentifier")] - public struct SourceAssetIdentifier - { - public SourceAssetIdentifier(Object asset) - { - if (asset == null) - { - throw new ArgumentNullException("asset"); - } - - this.type = asset.GetType(); - this.name = asset.name; - } - - public SourceAssetIdentifier(Type type, string name) - { - if (type == null) - { - throw new ArgumentNullException("type"); - } - - if (name == null) - { - throw new ArgumentNullException("name"); - } - - if (string.IsNullOrEmpty(name)) - { - throw new ArgumentException("The name is empty", "name"); - } - - this.type = type; - this.name = name; - } - - public Type type; - public string name; - } - - [NativeName("AssetPathName")] - public extern string assetPath - { - get; - } - - public extern bool importSettingsMissing - { - get; - } - - public extern ulong assetTimeStamp - { - get; - } - - public extern string userData - { - get; - set; - } - - public extern string assetBundleName - { - get; - set; - } - - public extern string assetBundleVariant - { - get; - set; - } - - [NativeName("SetAssetBundleName")] - extern public void SetAssetBundleNameAndVariant(string assetBundleName, string assetBundleVariant); - - [FreeFunction("FindAssetImporterAtAssetPath")] - extern public static AssetImporter GetAtPath(string path); - - public void SaveAndReimport() - { - AssetDatabase.ImportAsset(assetPath); - } - - [FreeFunction("AssetImporterBindings::LocalFileIDToClassID")] - extern internal static int LocalFileIDToClassID(long fileId); - - extern public void AddRemap(SourceAssetIdentifier identifier, Object externalObject); - - extern public bool RemoveRemap(SourceAssetIdentifier identifier); - - [FreeFunction("AssetImporterBindings::GetIdentifiers")] - extern private static SourceAssetIdentifier[] GetIdentifiers(AssetImporter self); - [FreeFunction("AssetImporterBindings::GetExternalObjects")] - extern private static Object[] GetExternalObjects(AssetImporter self); - - public Dictionary GetExternalObjectMap() - { - // bogdanc: this is not optimal - we should have only one call to get both the identifiers and the external objects. - // However, the new bindings do not support well output array parameters. - // FIXME: change this to a single call when the bindings are fixed - SourceAssetIdentifier[] identifiers = GetIdentifiers(this); - Object[] externalObjects = GetExternalObjects(this); - - Dictionary map = new Dictionary(); - - for (int i = 0; i < identifiers.Length; ++i) - { - map.Add(identifiers[i], externalObjects[i]); - } - - return map; - } - - [FreeFunction("AssetImporterBindings::RegisterImporter")] - extern internal static void RegisterImporter(Type importer, int importerVersion, int queuePos, string fileExt, bool supportsImportDependencyHinting); - } -} diff --git a/Editor/Mono/AssetPipeline/LocalCacheServer.cs b/Editor/Mono/AssetPipeline/LocalCacheServer.cs deleted file mode 100644 index 8dababbb4d..0000000000 --- a/Editor/Mono/AssetPipeline/LocalCacheServer.cs +++ /dev/null @@ -1,230 +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.Diagnostics; -using System.IO; -using System; -using System.Net; -using System.Net.Sockets; -using UnityEditor.Scripting; -using UnityEditor.Utils; -using UnityEngine; -using UnityEngine.Scripting; - -namespace UnityEditor -{ - internal class LocalCacheServer : ScriptableSingleton - { - [SerializeField] public string path; - [SerializeField] public int port; - [SerializeField] public ulong size; - [SerializeField] public int pid = -1; - [SerializeField] public string time; - - public const string SizeKey = "LocalCacheServerSize"; - public const string PathKey = "LocalCacheServerPath"; - public const string CustomPathKey = "LocalCacheServerCustomPath"; - - public static string GetCacheLocation() - { - var cachePath = EditorPrefs.GetString(PathKey); - var enableCustomPath = EditorPrefs.GetBool(CustomPathKey); - var result = cachePath; - if (!enableCustomPath || string.IsNullOrEmpty(cachePath)) - result = Paths.Combine(OSUtil.GetDefaultCachePath(), "CacheServer"); - return result; - } - - public static void CreateCacheDirectory() - { - string cacheDirectoryPath = GetCacheLocation(); - if (Directory.Exists(cacheDirectoryPath) == false) - Directory.CreateDirectory(cacheDirectoryPath); - } - - void Create(int _port, ulong _size) - { - var nodeExecutable = Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "nodejs"); - if (Application.platform == RuntimePlatform.WindowsEditor) - nodeExecutable = Paths.Combine(nodeExecutable, "node.exe"); - else - nodeExecutable = Paths.Combine(nodeExecutable, "bin", "node"); - - CreateCacheDirectory(); - path = GetCacheLocation(); - var cacheServerJs = Paths.Combine(EditorApplication.applicationContentsPath, "Tools", "CacheServer", "main.js"); - var processStartInfo = new ProcessStartInfo(nodeExecutable) - { - Arguments = "\"" + cacheServerJs + "\"" - + " --port " + _port - + " --path \"" + path - + "\" --nolegacy" - + " --monitor-parent-process " + Process.GetCurrentProcess().Id - // node.js has issues running on windows with stdout not redirected. - // so we silence logging to avoid that. And also to avoid CacheServer - // spamming the editor logs on OS X. - + " --silent" - + " --size " + _size, - UseShellExecute = false, - CreateNoWindow = true - }; - - var p = new Process(); - p.StartInfo = processStartInfo; - p.Start(); - - port = _port; - pid = p.Id; - size = _size; - time = p.StartTime.ToString(); - Save(true); - } - - public static int GetRandomUnusedPort() - { - var listener = new TcpListener(IPAddress.Any, 0); - listener.Start(); - var port = ((IPEndPoint)listener.LocalEndpoint).Port; - listener.Stop(); - return port; - } - - public static bool PingHost(string host, int port, int timeout) - { - try - { - using (var client = new TcpClient()) - { - var result = client.BeginConnect(host, port, null, null); - result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout)); - return client.Connected; - } - } - catch - { - return false; - } - } - - public static bool WaitForServerToComeAlive(int port) - { - DateTime start = DateTime.Now; - DateTime maximum = start.AddSeconds(5); - while (DateTime.Now < maximum) - { - if (PingHost("localhost", port, 10)) - { - System.Console.WriteLine("Server Came alive after {0} ms", (DateTime.Now - start).TotalMilliseconds); - return true; - } - } - return false; - } - - public static void Kill() - { - if (instance.pid == -1) - return; - - Process p = null; - try - { - p = Process.GetProcessById(instance.pid); - p.Kill(); - instance.pid = -1; - } - catch - { - // if we could not get a process, there is non alive. continue. - } - } - - public static void CreateIfNeeded() - { - // See if we can get an existing process with the PID we remembered. - Process p = null; - try - { - p = Process.GetProcessById(instance.pid); - } - catch - { - // if we could not get a process, there is non alive. continue. - } - - ulong size = (ulong)EditorPrefs.GetInt(SizeKey, 10) * 1024 * 1024 * 1024; - // Check if this process is really the one we used (and not another one reusing the PID). - if (p != null && p.StartTime.ToString() == instance.time) - { - if (instance.size == size && instance.path == GetCacheLocation()) - { - // We have a server running for this setup, which we can reuse, but make sure that the cache server directory exists in case it was cleaned earlier - CreateCacheDirectory(); - return; - } - else - { - // This server does not match our setup. Kill it, so we can start a new one. - Kill(); - } - } - - // No existing server we can use. Start a new one. - instance.Create(GetRandomUnusedPort(), size); - WaitForServerToComeAlive(instance.port); - } - - public static void Setup() - { - var mode = (CacheServerPreferences.CacheServerMode)EditorPrefs.GetInt("CacheServerMode"); - - if (mode == CacheServerPreferences.CacheServerMode.Local) - CreateIfNeeded(); - else - Kill(); - } - - [UsedByNativeCode] - public static int GetLocalCacheServerPort() - { - Setup(); - return instance.port; - } - - public static void Clear() - { - Kill(); - string cacheDirectoryPath = GetCacheLocation(); - if (Directory.Exists(cacheDirectoryPath)) - Directory.Delete(cacheDirectoryPath, true); - } - - public static bool CheckCacheLocationExists() - { - return Directory.Exists(GetCacheLocation()); - } - - public static bool CheckValidCacheLocation(string path) - { - if (Directory.Exists(path)) - { - var contents = Directory.GetFileSystemEntries(path); - foreach (var dir in contents) - { - var name = Path.GetFileName(dir).ToLower(); - if (name.Length == 2) - continue; - if (name == "temp") - continue; - if (name == ".ds_store") - continue; - if (name == "desktop.ini") - continue; - return false; - } - } - return true; - } - } -} diff --git a/Editor/Mono/AssetPipeline/TextureImporter.bindings.cs b/Editor/Mono/AssetPipeline/TextureImporter.bindings.cs index 001ec95022..90bdb7af92 100644 --- a/Editor/Mono/AssetPipeline/TextureImporter.bindings.cs +++ b/Editor/Mono/AssetPipeline/TextureImporter.bindings.cs @@ -20,6 +20,14 @@ namespace UnityEditor [NativeHeader("Editor/Src/EditorUserBuildSettings.h")] public sealed partial class TextureImporter : AssetImporter, ISpriteEditorDataProvider { + private string GetFixedPlatformName(string platform) + { + var targetGroup = BuildPipeline.GetBuildTargetGroupByName(platform); + if (targetGroup != BuildTargetGroup.Unknown) + return BuildPipeline.GetBuildTargetGroupName(targetGroup); + return platform; + } + [Obsolete("textureFormat is no longer accessible at the TextureImporter level. For old 'simple' formats use the textureCompression property for the equivalent automatic choice (Uncompressed for TrueColor, Compressed and HQCommpressed for 16 bits). For platform specific formats use the [[PlatformTextureSettings]] API. Using this setter will setup various parameters to match the new automatic system as well as possible. Getter will return the last value set.")] public extern TextureImporterFormat textureFormat { @@ -96,6 +104,9 @@ public bool GetPlatformTextureSettings(string platform, out int maxTextureSize, // public API will always return a valid TextureImporterPlatformSettings, creating it based on the default one if it did not exist. public TextureImporterPlatformSettings GetPlatformTextureSettings(string platform) { + // make sure we are converting the settings to use the proper BuildTargetGroupName to get them (the way it works on other importers) + platform = GetFixedPlatformName(platform); + TextureImporterPlatformSettings dest = GetPlatformTextureSetting_Internal(platform); if (platform != dest.name) { @@ -112,6 +123,7 @@ public TextureImporterPlatformSettings GetDefaultPlatformTextureSettings() public TextureImporterFormat GetAutomaticFormat(string platform) { + platform = GetFixedPlatformName(platform); TextureImporterSettings settings = new TextureImporterSettings(); ReadTextureSettings(settings); TextureImporterPlatformSettings platformSettings = GetPlatformTextureSettings(platform); @@ -161,11 +173,25 @@ public void SetPlatformTextureSettings(string platform, int maxTextureSize, Text SetPlatformTextureSettings(dest); } + [NativeName("SetPlatformTextureSettings")] + private extern void SetPlatformTextureSettings_Internal(TextureImporterPlatformSettings platformSettings); + // Set specific target platform settings - public extern void SetPlatformTextureSettings(TextureImporterPlatformSettings platformSettings); + public void SetPlatformTextureSettings(TextureImporterPlatformSettings platformSettings) + { + // we need to fix the name in case the user changed it to some mismatching value + platformSettings.name = GetFixedPlatformName(platformSettings.name); + SetPlatformTextureSettings_Internal(platformSettings); + } // Clear specific target platform settings - public extern void ClearPlatformTextureSettings(string platform); + [NativeName("ClearPlatformTextureSettings")] + private extern void ClearPlatformTextureSettings_Internal(string platform); + + public void ClearPlatformTextureSettings(string platform) + { + ClearPlatformTextureSettings_Internal(GetFixedPlatformName(platform)); + } [FreeFunction] internal static extern TextureImporterFormat DefaultFormatFromTextureParameters([NotNull] TextureImporterSettings settings, TextureImporterPlatformSettings platformSettings, bool doesTextureContainAlpha, bool sourceWasHDR, BuildTarget destinationPlatform); diff --git a/Editor/Mono/AssetPostprocessor.cs b/Editor/Mono/AssetPostprocessor.cs index 798978522f..00ba6ae26f 100644 --- a/Editor/Mono/AssetPostprocessor.cs +++ b/Editor/Mono/AssetPostprocessor.cs @@ -263,10 +263,10 @@ static string GetMeshProcessorsHashString() var inst = Activator.CreateInstance(assetPostprocessorClass) as AssetPostprocessor; var type = inst.GetType(); bool hasPreProcessMethod = type.GetMethod("OnPreprocessModel", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null; - bool hasProcessMeshAssignMethod = type.GetMethod("OnProcessMeshAssingModel", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null; + bool hasPostprocessMeshHierarchy = type.GetMethod("OnPostprocessMeshHierarchy", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null; bool hasPostProcessMethod = type.GetMethod("OnPostprocessModel", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) != null; uint version = inst.GetVersion(); - if (version != 0 && (hasPreProcessMethod || hasProcessMeshAssignMethod || hasPostProcessMethod)) + if (version != 0 && (hasPreProcessMethod || hasPostprocessMeshHierarchy || hasPostProcessMethod)) { versionsByType.Add(type.FullName, version); } @@ -356,6 +356,16 @@ static bool ProcessMeshHasAssignMaterial() return false; } + [RequiredByNativeCode] + static void PostprocessMeshHierarchy(GameObject root) + { + foreach (AssetPostprocessor inst in m_ImportProcessors) + { + object[] args = { root }; + AttributeHelper.InvokeMemberIfAvailable(inst, "OnPostprocessMeshHierarchy", args); + } + } + static void PostprocessMesh(GameObject gameObject) { foreach (AssetPostprocessor inst in m_ImportProcessors) diff --git a/Editor/Mono/AssetPreviewUpdater.cs b/Editor/Mono/AssetPreviewUpdater.cs deleted file mode 100644 index 3d310838d5..0000000000 --- a/Editor/Mono/AssetPreviewUpdater.cs +++ /dev/null @@ -1,52 +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; - -namespace UnityEditor -{ - internal static class AssetPreviewUpdater - { - // Generate a preview texture for an asset - public static Texture2D CreatePreviewForAsset(Object obj, Object[] subAssets, string assetPath) - { - if (obj == null) - return null; - - System.Type type = CustomEditorAttributes.FindCustomEditorType(obj, false); - if (type == null) - return null; - - System.Reflection.MethodInfo info = type.GetMethod("RenderStaticPreview"); - if (info == null) - { - Debug.LogError("Fail to find RenderStaticPreview base method"); - return null; - } - - if (info.DeclaringType == typeof(Editor)) - return null; - - - Editor editor = Editor.CreateEditor(obj); - - if (editor == null) - return null; - - Texture2D tex = editor.RenderStaticPreview(assetPath, subAssets, 128, 128); - - // For debugging we write the preview to a file (keep) - //{ - // var bytes = tex.EncodeToPNG(); - // string previewFilePath = string.Format ("{0}/../SavedPreview{1}.png", Application.dataPath, (int)(EditorApplication.timeSinceStartup*1000)); - // System.IO.File.WriteAllBytes(previewFilePath, bytes); - // Debug.Log ("Wrote preview file to: " +previewFilePath); - //} - - Object.DestroyImmediate(editor); - - return tex; - } - } -} diff --git a/Editor/Mono/AssetStore/AssetStoreContext.cs b/Editor/Mono/AssetStore/AssetStoreContext.cs index 068e39c522..7669651041 100644 --- a/Editor/Mono/AssetStore/AssetStoreContext.cs +++ b/Editor/Mono/AssetStore/AssetStoreContext.cs @@ -12,6 +12,7 @@ using System.Linq; using System.IO; using UnityEditor.Web; +using UnityEditor.Analytics; namespace UnityEditor { @@ -163,6 +164,15 @@ public void OpenBrowser(string url) Application.OpenURL(url); } + [Serializable] + public struct DownloadAssetInfo + { + public string package_id; + public string package_name; + public string publisher_name; + public string category_name; + } + public void Download(Package package, DownloadInfo downloadInfo) { Download( @@ -205,6 +215,13 @@ public static void Download(string package_id, string url, string key, string pa parameters["download"] = download; AssetStoreUtils.Download(package_id, url, dest, key, parameters.ToString(), resumeOK, doneCallback); + EditorAnalytics.SendAssetDownloadEvent(new DownloadAssetInfo() + { + package_id = package_id, + package_name = package_name, + publisher_name = publisher_name, + category_name = category_name + }); } /// diff --git a/Editor/Mono/AssetStore/Json.cs b/Editor/Mono/AssetStore/Json.cs deleted file mode 100644 index 9f3431c893..0000000000 --- a/Editor/Mono/AssetStore/Json.cs +++ /dev/null @@ -1,676 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -/* - * Simple recursive descending JSON parser and - * JSON string builder. - * - * Jonas Drewsen - (C) Unity3d.com - 2010 - * - * JSONParser parser = new JSONParser(" { \"hello\" : 42.3 } "); - * JSONValue value = parser.Parse(); - * - * bool is_it_float = value.isFloat(); - * float the_float = value.asFloat(); - * - */ - -using System.Collections.Generic; -using System; -using UnityEngine; - -namespace UnityEditorInternal -{ - /* - * JSON value structure - * - * Example: - * JSONValue v = JSONValue.NewDict(); - * v["hello"] = JSONValue.NewString("world"); - * asset(v["hello"].AsString() == "world"); - * - */ - internal struct JSONValue - { - public JSONValue(object o) - { - data = o; - } - - public bool IsString() { return data is string; } - public bool IsFloat() { return data is float; } - public bool IsList() { return data is List; } - public bool IsDict() { return data is Dictionary; } - public bool IsBool() { return data is bool; } - public bool IsNull() { return data == null; } - - public static implicit operator JSONValue(string s) - { - return new JSONValue(s); - } - - public static implicit operator JSONValue(float s) - { - return new JSONValue(s); - } - - public static implicit operator JSONValue(bool s) - { - return new JSONValue(s); - } - - public static implicit operator JSONValue(int s) - { - return new JSONValue((float)s); - } - - public object AsObject() - { - return data; - } - - public string AsString(bool nothrow) - { - if (data is string) - return (string)data; - if (!nothrow) - throw new JSONTypeException("Tried to read non-string json value as string"); - return ""; - } - - public string AsString() - { - return AsString(false); - } - - public float AsFloat(bool nothrow) - { - if (data is float) - return (float)data; - if (!nothrow) - throw new JSONTypeException("Tried to read non-float json value as float"); - return 0.0f; - } - - public float AsFloat() - { - return AsFloat(false); - } - - public bool AsBool(bool nothrow) - { - if (data is bool) - return (bool)data; - if (!nothrow) - throw new JSONTypeException("Tried to read non-bool json value as bool"); - return false; - } - - public bool AsBool() - { - return AsBool(false); - } - - public List AsList(bool nothrow) - { - if (data is List) - return (List)data; - if (!nothrow) - throw new JSONTypeException("Tried to read " + data.GetType().Name + " json value as list"); - return null; - } - - public List AsList() - { - return AsList(false); - } - - public Dictionary AsDict(bool nothrow) - { - if (data is Dictionary) - return (Dictionary)data; - if (!nothrow) - throw new JSONTypeException("Tried to read non-dictionary json value as dictionary"); - return null; - } - - public Dictionary AsDict() - { - return AsDict(false); - } - - public static JSONValue NewString(string val) - { - return new JSONValue(val); - } - - public static JSONValue NewFloat(float val) - { - return new JSONValue(val); - } - - public static JSONValue NewDict() - { - return new JSONValue(new Dictionary()); - } - - public static JSONValue NewList() - { - return new JSONValue(new List()); - } - - public static JSONValue NewBool(bool val) - { - return new JSONValue(val); - } - - public static JSONValue NewNull() - { - return new JSONValue(null); - } - - public JSONValue this[string index] - { - get - { - Dictionary dict = AsDict(); - return dict[index]; - } - set - { - if (data == null) - data = new Dictionary(); - Dictionary dict = AsDict(); - dict[index] = value; - } - } - - public bool ContainsKey(string index) - { - if (!IsDict()) - return false; - return AsDict().ContainsKey(index); - } - - // Get the specified field in a dict or null json value if - // no such field exists. The key can point to a nested structure - // e.g. key1.key2 in { key1 : { key2 : 32 } } - public JSONValue Get(string key) - { - if (!IsDict()) - return new JSONValue(null); - JSONValue value = this; - foreach (string part in key.Split('.')) - { - if (!value.ContainsKey(part)) - return new JSONValue(null); - value = value[part]; - } - return value; - } - - // Convenience dict value setting - public void Set(string key, string value) - { - if (value == null) - { - this[key] = NewNull(); - return; - } - this[key] = NewString(value); - } - - // Convenience dict value setting - public void Set(string key, float value) - { - this[key] = NewFloat(value); - } - - // Convenience dict value setting - public void Set(string key, bool value) - { - this[key] = NewBool(value); - } - - // Convenience list value add - public void Add(string value) - { - List list = AsList(); - if (value == null) - { - list.Add(NewNull()); - return; - } - list.Add(NewString(value)); - } - - // Convenience list value add - public void Add(float value) - { - List list = AsList(); - list.Add(NewFloat(value)); - } - - // Convenience list value add - public void Add(bool value) - { - List list = AsList(); - list.Add(NewBool(value)); - } - - /* - * Serialize a JSON value to string. - * This will recurse down through dicts and list type JSONValues. - */ - public override string ToString() - { - if (IsString()) - { - return "\"" + EncodeString(AsString()) + "\""; - } - else if (IsFloat()) - { - return AsFloat().ToString(); - } - else if (IsList()) - { - string res = "["; - string delim = ""; - foreach (JSONValue i in AsList()) - { - res += delim + i.ToString(); - delim = ", "; - } - return res + "]"; - } - else if (IsDict()) - { - string res = "{"; - string delim = ""; - foreach (KeyValuePair kv in AsDict()) - { - res += delim + '"' + EncodeString(kv.Key) + "\" : " + kv.Value.ToString(); - delim = ", "; - } - return res + "}"; - } - else if (IsBool()) - { - return AsBool() ? "true" : "false"; - } - else if (IsNull()) - { - return "null"; - } - else - { - throw new JSONTypeException("Cannot serialize json value of unknown type"); - } - } - - // Encode a string into a json string - private static string EncodeString(string str) - { - str = str.Replace("\"", "\\\""); - str = str.Replace("\\", "\\\\"); - str = str.Replace("\b", "\\b"); - str = str.Replace("\f", "\\f"); - str = str.Replace("\n", "\\n"); - str = str.Replace("\r", "\\r"); - str = str.Replace("\t", "\\t"); - // We do not use \uXXXX specifier but direct unicode in the string. - return str; - } - - object data; - } - - class JSONParseException : Exception - { - public JSONParseException(string msg) : base(msg) - { - } - } - - class JSONTypeException : Exception - { - public JSONTypeException(string msg) : base(msg) - { - } - } - - /* - * Top down recursive JSON parser - * - * Example: - * string json = "{ \"hello\" : \"world\", \"age\" : 100000, "sister" : null }"; - * JSONValue val = JSONParser.SimpleParse(json); - * asset( val["hello"].AsString() == "world" ); - * - */ - class JSONParser - { - private string json; - private int line; - private int linechar; - private int len; - private int idx; - private int pctParsed; - private char cur; - - public static JSONValue SimpleParse(string jsondata) - { - var parser = new JSONParser(jsondata); - try - { - return parser.Parse(); - } - catch (JSONParseException ex) - { - Debug.LogError(ex.Message); - } - return new JSONValue(null); - } - - /* - * Setup a parse to be ready for parsing the given string - */ - public JSONParser(string jsondata) - { - // TODO: fix that parser needs trailing spaces; - json = jsondata + " "; - line = 1; - linechar = 1; - len = json.Length; - idx = 0; - pctParsed = 0; - } - - /* - * Parse the entire json data string into a JSONValue structure hierarchy - */ - public JSONValue Parse() - { - cur = json[idx]; - return ParseValue(); - } - - private char Next() - { - if (cur == '\n') - { - line++; - linechar = 0; - } - idx++; - if (idx >= len) - throw new JSONParseException("End of json while parsing at " + PosMsg()); - - linechar++; - - int newPct = (int)((float)idx * 100f / (float)len); - if (newPct != pctParsed) - { - pctParsed = newPct; - } - cur = json[idx]; - return cur; - } - - private void SkipWs() - { - string ws = " \n\t\r"; - while (ws.IndexOf(cur) != -1) Next(); - } - - private string PosMsg() - { - return "line " + line.ToString() + ", column " + linechar.ToString(); - } - - private JSONValue ParseValue() - { - // Skip spaces - SkipWs(); - - switch (cur) - { - case '[': - return ParseArray(); - case '{': - return ParseDict(); - case '"': - return ParseString(); - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return ParseNumber(); - case 't': - case 'f': - case 'n': - return ParseConstant(); - default: - throw new JSONParseException("Cannot parse json value starting with '" + json.Substring(idx, 5) + "' at " + PosMsg()); - } - } - - private JSONValue ParseArray() - { - Next(); - SkipWs(); - List arr = new List(); - while (cur != ']') - { - arr.Add(ParseValue()); - SkipWs(); - if (cur == ',') - { - Next(); - SkipWs(); - } - } - Next(); - return new JSONValue(arr); - } - - private JSONValue ParseDict() - { - Next(); - SkipWs(); - Dictionary dict = new Dictionary(); - while (cur != '}') - { - JSONValue key = ParseValue(); - if (!key.IsString()) - throw new JSONParseException("Key not string type at " + PosMsg()); - SkipWs(); - if (cur != ':') - throw new JSONParseException("Missing dict entry delimiter ':' at " + PosMsg()); - Next(); - dict.Add(key.AsString(), ParseValue()); - SkipWs(); - if (cur == ',') - { - Next(); - SkipWs(); - } - } - Next(); - return new JSONValue(dict); - } - - static char[] endcodes = new char[] { '\\', '"' }; - - private JSONValue ParseString() - { - string res = ""; - - Next(); - - while (idx < len) - { - int endidx = json.IndexOfAny(endcodes, idx); - if (endidx < 0) - throw new JSONParseException("missing '\"' to end string at " + PosMsg()); - - res += json.Substring(idx, endidx - idx); - - if (json[endidx] == '"') - { - cur = json[endidx]; - idx = endidx; - break; - } - - endidx++; // get escape code - if (endidx >= len) - throw new JSONParseException("End of json while parsing while parsing string at " + PosMsg()); - - // char at endidx is \ - char ncur = json[endidx]; - switch (ncur) - { - case '"': - goto case '/'; - case '\\': - goto case '/'; - case '/': - res += ncur; - break; - case 'b': - res += '\b'; - break; - case 'f': - res += '\f'; - break; - case 'n': - res += '\n'; - break; - case 'r': - res += '\r'; - break; - case 't': - res += '\t'; - break; - case 'u': - // Unicode char specified by 4 hex digits - string digit = ""; - if (endidx + 4 >= len) - throw new JSONParseException("End of json while parsing while parsing unicode char near " + PosMsg()); - digit += json[endidx + 1]; - digit += json[endidx + 2]; - digit += json[endidx + 3]; - digit += json[endidx + 4]; - try - { - int d = System.Int32.Parse(digit, System.Globalization.NumberStyles.AllowHexSpecifier); - res += (char)d; - } - catch (FormatException) - { - throw new JSONParseException("Invalid unicode escape char near " + PosMsg()); - } - endidx += 4; - break; - default: - throw new JSONParseException("Invalid escape char '" + ncur + "' near " + PosMsg()); - } - idx = endidx + 1; - } - if (idx >= len) - throw new JSONParseException("End of json while parsing while parsing string near " + PosMsg()); - - cur = json[idx]; - - Next(); - return new JSONValue(res); - } - - private JSONValue ParseNumber() - { - string resstr = ""; - - if (cur == '-') - { - resstr = "-"; - Next(); - } - - while (cur >= '0' && cur <= '9') - { - resstr += cur; - Next(); - } - if (cur == '.') - { - Next(); - resstr += '.'; - while (cur >= '0' && cur <= '9') - { - resstr += cur; - Next(); - } - } - - if (cur == 'e' || cur == 'E') - { - resstr += "e"; - Next(); - if (cur != '-' && cur != '+') - { - // throw new JSONParseException("Missing - or + in 'e' potent specifier at " + PosMsg()); - resstr += cur; - Next(); - } - while (cur >= '0' && cur <= '9') - { - resstr += cur; - Next(); - } - } - - try - { - float f = System.Convert.ToSingle(resstr); - return new JSONValue(f); - } - catch (Exception) - { - throw new JSONParseException("Cannot convert string to float : '" + resstr + "' at " + PosMsg()); - } - } - - private JSONValue ParseConstant() - { - string c = ""; - c = "" + cur + Next() + Next() + Next(); - Next(); - if (c == "true") - { - return new JSONValue(true); - } - else if (c == "fals") - { - if (cur == 'e') - { - Next(); - return new JSONValue(false); - } - } - else if (c == "null") - { - return new JSONValue(null); - } - throw new JSONParseException("Invalid token at " + PosMsg()); - } - } -} diff --git a/Editor/Mono/AsyncHTTPClient.bindings.cs b/Editor/Mono/AsyncHTTPClient.bindings.cs deleted file mode 100644 index 896fb806a7..0000000000 --- a/Editor/Mono/AsyncHTTPClient.bindings.cs +++ /dev/null @@ -1,30 +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.Bindings; - -namespace UnityEditor -{ - [NativeHeader("Editor/Mono/AsyncHTTPClient.bindings.h")] - internal partial class AsyncHTTPClient - { - private delegate void RequestProgressCallback(AsyncHTTPClient.State status, int downloaded, int totalSize); - private delegate void RequestDoneCallback(AsyncHTTPClient.State status, int httpStatus); - - private static extern IntPtr SubmitClientRequest(string tag, string url, string[] headers, string method, string data, RequestDoneCallback doneDelegate, RequestProgressCallback progressDelegate = null); - - private static extern byte[] GetBytesByHandle(IntPtr handle); - - private static extern Texture2D GetTextureByHandle(IntPtr handle); - - public static extern void AbortByTag(string tag); - - private static extern void AbortByHandle(IntPtr handle); - - [FreeFunction] - public static extern void CurlRequestCheck(); - } -} diff --git a/Editor/Mono/AsyncHTTPClient.cs b/Editor/Mono/AsyncHTTPClient.cs deleted file mode 100644 index 573ac6cccd..0000000000 --- a/Editor/Mono/AsyncHTTPClient.cs +++ /dev/null @@ -1,231 +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.Net; -using System.IO; -using System.Text; -using System.Threading; -using System.Collections.Generic; -using UnityEngine; -using System.Linq; - -namespace UnityEditor -{ - /* - * A HTTP job for performing HTTP requests in a thread - * This class is primarily used by the Server class. - */ - internal partial class AsyncHTTPClient - { - internal enum State - { - INIT, - CONNECTING, - CONNECTED, - UPLOADING, - DOWNLOADING, - CONFIRMING, - DONE_OK, - DONE_FAILED, - ABORTED, - TIMEOUT - } - private IntPtr m_Handle; - public delegate void DoneCallback(AsyncHTTPClient client); - public delegate void StatusCallback(State status, int bytesDone, int bytesTotal); - - public StatusCallback statusCallback; - public DoneCallback doneCallback; - - string m_ToUrl; - string m_FromData; - string m_Method; - - public string url - { - get { return m_ToUrl; } - } - - public string text - { - get - { - System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); - byte[] b = bytes; - if (b == null) return null; - return encoding.GetString(b); - } - } - - public byte[] bytes - { - get - { - return GetBytesByHandle(m_Handle); - } - } - public Texture2D texture - { - get - { - return GetTextureByHandle(m_Handle); - } - } - public State state { get; private set; } - public int responseCode { get; private set; } - public string tag { get; set; } - - public Dictionary header; - - /* GET request - * - */ - public AsyncHTTPClient(string _toUrl) - { - m_ToUrl = _toUrl; - m_FromData = null; - m_Method = ""; - state = State.INIT; - header = new Dictionary(StringComparer.OrdinalIgnoreCase); - m_Handle = (IntPtr)0; - tag = ""; - statusCallback = null; - } - - /* Any method request - * - */ - public AsyncHTTPClient(string _toUrl, string _method) - { - m_ToUrl = _toUrl; - m_FromData = null; - m_Method = _method; - state = State.INIT; - header = new Dictionary(StringComparer.OrdinalIgnoreCase); - m_Handle = (IntPtr)0; - tag = ""; - statusCallback = null; - } - - /* If this job has been set as a POST job this will overwrite the - * data to be posted. The job must not have been started yet - * ie. Begin() should not have been called. - */ - public string postData - { - set - { - m_FromData = value; - if (m_Method == "") - m_Method = "POST"; - if (!header.ContainsKey("Content-Type")) - header["Content-Type"] = "application/x-www-form-urlencoded"; - } - } - - /* - * POST request for uploading url application/x-www-form-urlencoded dictionary. - * The encoding normally allows for duplicate keys, but this method is restricted - * to unique keys. - */ - public Dictionary postDictionary - { - set - { - postData = string.Join("&", value.Select(kv => EscapeLong(kv.Key) + "=" + EscapeLong(kv.Value)).ToArray()); - } - } - - /* - * - */ - public void Abort() - { - state = State.ABORTED; - - AbortByHandle(m_Handle); - } - - public bool IsAborted() - { - return state == State.ABORTED; - } - - public bool IsDone() - { - return IsDone(state); - } - - public static bool IsDone(State state) - { - switch (state) - { - case State.DONE_OK: - case State.DONE_FAILED: - case State.ABORTED: - case State.TIMEOUT: - return true; - default: return false; - } - } - - public bool IsSuccess() - { - return state == State.DONE_OK; - } - - public static bool IsSuccess(State state) - { - return state == State.DONE_OK; - } - - public void Begin() - { - if (IsAborted()) - { - state = State.ABORTED; - return; - } - if (m_Method == "") - m_Method = "GET"; - - string[] headerFlattened = header.Select(kv => string.Format("{0}: {1}", kv.Key, kv.Value)).ToArray(); - - m_Handle = SubmitClientRequest(tag, m_ToUrl, headerFlattened, m_Method, m_FromData, Done, Progress); - } - - private void Done(State status, int i_ResponseCode) - { - state = status; - responseCode = i_ResponseCode; - - if (doneCallback != null) - doneCallback(this); - - m_Handle = (IntPtr)0; // The CurlRequestMessage will be deallocated after this callback returns - } - - private void Progress(State status, int bytesDone, int bytesTotal) - { - state = status; - if (statusCallback != null) - statusCallback(status, bytesDone, bytesTotal); - } - - /* - * The normal escape function does not support strings longer than 32766 characters - */ - private string EscapeLong(string v) - { - StringBuilder q = new StringBuilder(); - const int c_ChunkLength = 32766; - for (int i = 0; i < v.Length; i += c_ChunkLength) - { - q.Append(System.Uri.EscapeDataString(v.Substring(i, v.Length - i > c_ChunkLength ? c_ChunkLength : v.Length - i))); - } - return q.ToString(); - } - } -} diff --git a/Editor/Mono/AsyncProgressBar.bindings.cs b/Editor/Mono/AsyncProgressBar.bindings.cs deleted file mode 100644 index d1715ba480..0000000000 --- a/Editor/Mono/AsyncProgressBar.bindings.cs +++ /dev/null @@ -1,25 +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.Bindings; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace UnityEditor -{ - // Progress bar located in the status bar. A non blocking way of showing progress of tasks, e.g. lightmapping. - // Currently can properly show progress only for one task at a time. - [StaticAccessor("GetAsyncProgressBar()", StaticAccessorType.Dot)] - [NativeHeader("Editor/Src/AsyncProgressBar.h")] - internal partial class AsyncProgressBar - { - public static extern float progress { get; } - public static extern string progressInfo { get; } - public static extern bool isShowing {[NativeName("IsShowing")] get; } - - public static extern void Display(string progressInfo, float progress); - public static extern void Clear(); - } -} diff --git a/Editor/Mono/Audio/Effects/AudioMixerEffectPlugin.cs b/Editor/Mono/Audio/Effects/AudioMixerEffectPlugin.cs deleted file mode 100644 index c2d159ed8b..0000000000 --- a/Editor/Mono/Audio/Effects/AudioMixerEffectPlugin.cs +++ /dev/null @@ -1,67 +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 System.Text; -using UnityEngine; -using UnityEditor; -using UnityEditor.Audio; - -namespace UnityEditor.Audio -{ - public class AudioMixerEffectPlugin : IAudioEffectPlugin - { - public override bool SetFloatParameter(string name, float value) - { - m_Effect.SetValueForParameter(m_Controller, m_Controller.TargetSnapshot, name, value); - return true; - } - - public override bool GetFloatParameter(string name, out float value) - { - value = m_Effect.GetValueForParameter(m_Controller, m_Controller.TargetSnapshot, name); - return true; - } - - public override bool GetFloatParameterInfo(string name, out float minRange, out float maxRange, out float defaultValue) - { - foreach (var p in m_ParamDefs) - { - if (p.name == name) - { - minRange = p.minRange; - maxRange = p.maxRange; - defaultValue = p.defaultValue; - return true; - } - } - minRange = 0.0f; - maxRange = 1.0f; - defaultValue = 0.5f; - return false; - } - - public override bool GetFloatBuffer(string name, out float[] data, int numsamples) - { - m_Effect.GetFloatBuffer(m_Controller, name, out data, numsamples); - return true; - } - - public override int GetSampleRate() - { - return AudioSettings.outputSampleRate; - } - - public override bool IsPluginEditableAndEnabled() - { - return AudioMixerController.EditingTargetSnapshot() && !m_Effect.bypass; - } - - internal AudioMixerController m_Controller; - internal AudioMixerEffectController m_Effect; - internal MixerParameterDefinition[] m_ParamDefs; - } -} diff --git a/Editor/Mono/Audio/Effects/IAudioEffectPlugin.cs b/Editor/Mono/Audio/Effects/IAudioEffectPlugin.cs deleted file mode 100644 index 68a0256bdd..0000000000 --- a/Editor/Mono/Audio/Effects/IAudioEffectPlugin.cs +++ /dev/null @@ -1,23 +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 System.Text; -using UnityEngine; -using UnityEditor; - -namespace UnityEditor -{ - public abstract class IAudioEffectPlugin - { - public abstract bool SetFloatParameter(string name, float value); - public abstract bool GetFloatParameter(string name, out float value); - public abstract bool GetFloatParameterInfo(string name, out float minRange, out float maxRange, out float defaultValue); - public abstract bool GetFloatBuffer(string name, out float[] data, int numsamples); - public abstract int GetSampleRate(); - public abstract bool IsPluginEditableAndEnabled(); - } -} diff --git a/Editor/Mono/Audio/Effects/IAudioEffectPluginGUI.cs b/Editor/Mono/Audio/Effects/IAudioEffectPluginGUI.cs deleted file mode 100644 index f22f756a0f..0000000000 --- a/Editor/Mono/Audio/Effects/IAudioEffectPluginGUI.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; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEngine; -using UnityEditor; - -namespace UnityEditor -{ - public abstract class IAudioEffectPluginGUI - { - public abstract string Name { get; } - public abstract string Description { get; } - public abstract string Vendor { get; } - public abstract bool OnGUI(IAudioEffectPlugin plugin); - } -} diff --git a/Editor/Mono/Audio/Mixer/AudioMixerDescription.cs b/Editor/Mono/Audio/Mixer/AudioMixerDescription.cs deleted file mode 100644 index c85637695e..0000000000 --- a/Editor/Mono/Audio/Mixer/AudioMixerDescription.cs +++ /dev/null @@ -1,156 +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 UnityEditor; -using System; -using System.Collections.Generic; - -//FIXME: change this to nested namespaces when we merge in trunk -namespace UnityEditor.Audio -{ - internal class MixerEffectDefinition - { - public MixerEffectDefinition(string name, MixerParameterDefinition[] parameters) - { - this.m_EffectName = name; - this.m_Parameters = new MixerParameterDefinition[parameters.Length]; - Array.Copy(parameters, this.m_Parameters, parameters.Length); - } - - public string name - { - get { return this.m_EffectName; } - } - - public MixerParameterDefinition[] parameters - { - get { return this.m_Parameters; } - } - - private readonly string m_EffectName; - //TODO: GUI callback - private readonly MixerParameterDefinition[] m_Parameters; - } - - - [InitializeOnLoad] - static class MixerEffectDefinitionReloader - { - // We use this class with InitializeOnLoad attribute for ensuring MixerEffectDefinitions are refreshed - // when needed: 1) At startup, 2) after script recompile and 3) when project changes (new effects can have been added) - static MixerEffectDefinitionReloader() - { - MixerEffectDefinitions.Refresh(); - - EditorApplication.projectChanged += OnProjectChanged; - } - - static void OnProjectChanged() - { - MixerEffectDefinitions.Refresh(); - } - } - - - internal sealed partial class MixerEffectDefinitions - { - public static void Refresh() - { - ClearDefinitions(); - - RegisterAudioMixerEffect("Attenuation", new MixerParameterDefinition[0]); - RegisterAudioMixerEffect("Send", new MixerParameterDefinition[0]); - RegisterAudioMixerEffect("Receive", new MixerParameterDefinition[0]); - - var duckVolDef = new MixerParameterDefinition[7]; - duckVolDef[0] = new MixerParameterDefinition { name = "Threshold", units = "dB", displayScale = 1.0f, displayExponent = 1.0f, minRange = -80.0f, maxRange = 0.0f, defaultValue = -10.0f, description = "Threshold of side-chain level detector" }; - duckVolDef[1] = new MixerParameterDefinition { name = "Ratio", units = "%", displayScale = 100.0f, displayExponent = 1.0f, minRange = 0.2f, maxRange = 10.0f, defaultValue = 2.0f, description = "Ratio of compression applied when side-chain signal exceeds threshold" }; - duckVolDef[2] = new MixerParameterDefinition { name = "Attack Time", units = "ms", displayScale = 1000.0f, displayExponent = 3.0f, minRange = 0.0f, maxRange = 10.0f, defaultValue = 0.1f, description = "Level detector attack time" }; - duckVolDef[3] = new MixerParameterDefinition { name = "Release Time", units = "ms", displayScale = 1000.0f, displayExponent = 3.0f, minRange = 0.0f, maxRange = 10.0f, defaultValue = 0.1f, description = "Level detector release time" }; - duckVolDef[4] = new MixerParameterDefinition { name = "Make-up Gain", units = "dB", displayScale = 1.0f, displayExponent = 1.0f, minRange = -80.0f, maxRange = 40.0f, defaultValue = 0.0f, description = "Make-up gain" }; - duckVolDef[5] = new MixerParameterDefinition { name = "Knee", units = "dB", displayScale = 1.0f, displayExponent = 1.0f, minRange = 0.0f, maxRange = 50.0f, defaultValue = 10.0f, description = "Sharpness of compression curve knee" }; - duckVolDef[6] = new MixerParameterDefinition { name = "Sidechain Mix", units = "%", displayScale = 100.0f, displayExponent = 1.0f, minRange = 0.0f, maxRange = 1.0f, defaultValue = 1.0f, description = "Sidechain/source mix. If set to 100% the compressor detects level entirely from sidechain signal." }; - RegisterAudioMixerEffect("Duck Volume", duckVolDef); - AddDefinitionRuntime("Duck Volume", duckVolDef); - - string[] effectNames = GetAudioEffectNames(); - foreach (var effectName in effectNames) - { - MixerParameterDefinition[] paramDesc = GetAudioEffectParameterDesc(effectName); - RegisterAudioMixerEffect(effectName, paramDesc); - } - } - - public static bool EffectExists(string name) - { - foreach (MixerEffectDefinition definition in s_MixerEffectDefinitions) - { - if (definition.name == name) - { - return true; - } - } - - return false; - } - - public static string[] GetEffectList() - { - string[] effectNames = new string[s_MixerEffectDefinitions.Count]; - for (int i = 0; i < s_MixerEffectDefinitions.Count; i++) - { - effectNames[i] = s_MixerEffectDefinitions[i].name; - } - - return effectNames; - } - - public static void ClearDefinitions() - { - s_MixerEffectDefinitions.Clear(); - ClearDefinitionsRuntime(); - } - - public static MixerParameterDefinition[] GetEffectParameters(string effect) - { - foreach (MixerEffectDefinition definition in s_MixerEffectDefinitions) - { - if (definition.name == effect) - { - return definition.parameters; - } - } - - return new MixerParameterDefinition[0]; - } - - public static bool RegisterAudioMixerEffect(string name, MixerParameterDefinition[] definitions) - { - foreach (MixerEffectDefinition definition in s_MixerEffectDefinitions) - { - if (definition.name == name) - { - //Cannot add this type, already exists in the system. - return false; - } - } - - MixerEffectDefinition newDefinition = new MixerEffectDefinition(name, definitions); - s_MixerEffectDefinitions.Add(newDefinition); - - //Wasteful - Clears the runtime representation each time a new effect is added and rebuilds all runtime - //representations. - ClearDefinitionsRuntime(); - foreach (MixerEffectDefinition definition in s_MixerEffectDefinitions) - { - AddDefinitionRuntime(definition.name, definition.parameters); - } - - return true; - } - - private static readonly List s_MixerEffectDefinitions = new List(); - } -} diff --git a/Editor/Mono/Audio/Mixer/Bindings/AudioMixerGroup.cs b/Editor/Mono/Audio/Mixer/Bindings/AudioMixerGroup.cs deleted file mode 100644 index fa92fd4ebc..0000000000 --- a/Editor/Mono/Audio/Mixer/Bindings/AudioMixerGroup.cs +++ /dev/null @@ -1,72 +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 UnityEditor; -using UnityEditor.Audio; -using System.IO; -using System.Collections.Generic; -using System; - -namespace UnityEditor.Audio -{ - [ExcludeFromPreset] - internal partial class AudioMixerGroupController - { - public void InsertEffect(AudioMixerEffectController effect, int index) - { - var modifiedEffectsList = new List(effects); - modifiedEffectsList.Add(null); - for (int i = modifiedEffectsList.Count - 1; i > index; i--) - modifiedEffectsList[i] = modifiedEffectsList[i - 1]; - modifiedEffectsList[index] = effect; - effects = modifiedEffectsList.ToArray(); - } - - public bool HasAttenuation() - { - foreach (var e in effects) - if (e.IsAttenuation()) - return true; - return false; - } - - public void DumpHierarchy(string title, int level) - { - if (title != "") - Console.WriteLine(title); - - string prefix = ""; - int l = level; - while (l-- > 0) - prefix += " "; - Console.WriteLine(prefix + "name=" + name); - - prefix += " "; - foreach (var f in effects) - Console.WriteLine(prefix + "effect=" + f.ToString()); - - foreach (var g in children) - g.DumpHierarchy("", level + 1); - } - - public string GetDisplayString() - { - return name; // AudioMixerController.FixNameForPopupMenu(name); - } - - public override string ToString() - { - return name; - } - } - - internal class MixerGroupControllerCompareByName : IComparer - { - public int Compare(AudioMixerGroupController x, AudioMixerGroupController y) - { - return StringComparer.InvariantCultureIgnoreCase.Compare(x.GetDisplayString(), y.GetDisplayString()); - } - } -} diff --git a/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectGUI.cs b/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectGUI.cs deleted file mode 100644 index de2802e4d2..0000000000 --- a/Editor/Mono/Audio/Mixer/GUI/AudioMixerEffectGUI.cs +++ /dev/null @@ -1,167 +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 UnityEditor.Audio; - -namespace UnityEditor -{ - internal static class AudioMixerEffectGUI - { - const string kAudioSliderFloatFormat = "F2"; - const string kExposedParameterUnicodeChar = " \u2794"; - - public static void EffectHeader(string text) - { - GUILayout.Label(text, styles.headerStyle); - } - - public static bool Slider(GUIContent label, ref float value, float displayScale, float displayExponent, string unit, float leftValue, float rightValue, AudioMixerController controller, AudioParameterPath path, params GUILayoutOption[] options) - { - EditorGUI.BeginChangeCheck(); - - float oldNumberWidth = EditorGUIUtility.fieldWidth; - string origFormat = EditorGUI.kFloatFieldFormatString; - - bool exposed = controller.ContainsExposedParameter(path.parameter); - - EditorGUIUtility.fieldWidth = 70f; // do not go over 70 because then sliders will not be shown when inspector has minimal width - EditorGUI.kFloatFieldFormatString = kAudioSliderFloatFormat; - EditorGUI.s_UnitString = unit; - GUIContent content = label; - if (exposed) - content = GUIContent.Temp(label.text + kExposedParameterUnicodeChar, label.tooltip); - - float displayValue = value * displayScale; - displayValue = EditorGUILayout.PowerSlider(content, displayValue, leftValue * displayScale, rightValue * displayScale, displayExponent, options); - - EditorGUI.s_UnitString = null; - EditorGUI.kFloatFieldFormatString = origFormat; - EditorGUIUtility.fieldWidth = oldNumberWidth; - - if (Event.current.type == EventType.ContextClick) - { - Rect wholeSlider = GUILayoutUtility.topLevel.GetLast(); - if (wholeSlider.Contains(Event.current.mousePosition)) - { - Event.current.Use(); - - GenericMenu pm = new GenericMenu(); - if (!exposed) - pm.AddItem(EditorGUIUtility.TrTextContent("Expose '" + path.ResolveStringPath(false) + "' to script"), false, ExposePopupCallback, new ExposedParamContext(controller, path)); - else - pm.AddItem(EditorGUIUtility.TrTextContent("Unexpose"), false, UnexposePopupCallback, new ExposedParamContext(controller, path)); - - ParameterTransitionType existingType; - bool overrideExists = controller.TargetSnapshot.GetTransitionTypeOverride(path.parameter, out existingType); - System.Diagnostics.Debug.Assert(!overrideExists || existingType == ParameterTransitionType.Lerp); - - pm.AddSeparator(string.Empty); - pm.AddItem(EditorGUIUtility.TrTextContent("Linear Snapshot Transition"), existingType == ParameterTransitionType.Lerp, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Lerp)); - pm.AddItem(EditorGUIUtility.TrTextContent("Smoothstep Snapshot Transition"), existingType == ParameterTransitionType.Smoothstep, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Smoothstep)); - pm.AddItem(EditorGUIUtility.TrTextContent("Squared Snapshot Transition"), existingType == ParameterTransitionType.Squared, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.Squared)); - pm.AddItem(EditorGUIUtility.TrTextContent("SquareRoot Snapshot Transition"), existingType == ParameterTransitionType.SquareRoot, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.SquareRoot)); - pm.AddItem(EditorGUIUtility.TrTextContent("BrickwallStart Snapshot Transition"), existingType == ParameterTransitionType.BrickwallStart, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallStart)); - pm.AddItem(EditorGUIUtility.TrTextContent("BrickwallEnd Snapshot Transition"), existingType == ParameterTransitionType.BrickwallEnd, ParameterTransitionOverrideCallback, new ParameterTransitionOverrideContext(controller, path.parameter, ParameterTransitionType.BrickwallEnd)); - pm.AddSeparator(string.Empty); - - pm.ShowAsContext(); - } - } - - if (EditorGUI.EndChangeCheck()) - { - value = displayValue / displayScale; - return true; - } - return false; - } - - private class ExposedParamContext - { - public ExposedParamContext(AudioMixerController controller, AudioParameterPath path) - { - this.controller = controller; - this.path = path; - } - - public AudioMixerController controller; - public AudioParameterPath path; - } - - - public static void ExposePopupCallback(object obj) - { - ExposedParamContext context = (ExposedParamContext)obj; - Undo.RecordObject(context.controller, "Expose Mixer Parameter"); - context.controller.AddExposedParameter(context.path); - - AudioMixerUtility.RepaintAudioMixerAndInspectors(); - } - - public static void UnexposePopupCallback(object obj) - { - ExposedParamContext context = (ExposedParamContext)obj; - Undo.RecordObject(context.controller, "Unexpose Mixer Parameter"); - context.controller.RemoveExposedParameter(context.path.parameter); - - AudioMixerUtility.RepaintAudioMixerAndInspectors(); - } - - private class ParameterTransitionOverrideContext - { - public ParameterTransitionOverrideContext(AudioMixerController controller, GUID parameter, ParameterTransitionType type) - { - this.controller = controller; - this.parameter = parameter; - this.type = type; - } - - public AudioMixerController controller; - public GUID parameter; - public ParameterTransitionType type; - } - - private class ParameterTransitionOverrideRemoveContext - { - public ParameterTransitionOverrideRemoveContext(AudioMixerController controller, GUID parameter) - { - this.controller = controller; - this.parameter = parameter; - } - - public AudioMixerController controller; - public GUID parameter; - } - - public static void ParameterTransitionOverrideCallback(object obj) - { - ParameterTransitionOverrideContext context = (ParameterTransitionOverrideContext)obj; - Undo.RecordObject(context.controller, "Change Parameter Transition Type"); - if (context.type == ParameterTransitionType.Lerp) - context.controller.TargetSnapshot.ClearTransitionTypeOverride(context.parameter); - else - context.controller.TargetSnapshot.SetTransitionTypeOverride(context.parameter, context.type); - } - - public static bool PopupButton(GUIContent label, GUIContent buttonContent, GUIStyle style, out Rect buttonRect, params GUILayoutOption[] options) - { - if (label != null) - { - Rect r = EditorGUILayout.s_LastRect = EditorGUILayout.GetControlRect(true, EditorGUI.kSingleLineHeight, style, options); - int id = EditorGUIUtility.GetControlID("EditorPopup".GetHashCode(), FocusType.Keyboard, r); - buttonRect = EditorGUI.PrefixLabel(r, id, label); - } - else - { - Rect r = GUILayoutUtility.GetRect(buttonContent, style, options); - buttonRect = r; - } - - return EditorGUI.DropdownButton(buttonRect, buttonContent, FocusType.Passive, style); - } - - private static AudioMixerDrawUtils.Styles styles { get { return AudioMixerDrawUtils.styles; } } - } -} diff --git a/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParameterView.cs b/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParameterView.cs index 9832a5c637..8c86a45d7a 100644 --- a/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParameterView.cs +++ b/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParameterView.cs @@ -106,6 +106,10 @@ void DrawElement(Rect rect, int index, bool isActive, bool isFocused) public Vector2 CalcSize() { + if (m_ReorderableListWithRenameAndScrollView.list.count != m_Controller.exposedParameters.Length) + { + RecreateListControl(); + } float maxWidth = 0; for (int index = 0; index < m_ReorderableListWithRenameAndScrollView.list.count; index++) { diff --git a/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParametersPopup.cs b/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParametersPopup.cs index c2935d9343..b06409045d 100644 --- a/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParametersPopup.cs +++ b/Editor/Mono/Audio/Mixer/GUI/AudioMixerExposedParametersPopup.cs @@ -18,7 +18,7 @@ internal static void Popup(AudioMixerController controller, GUIStyle style, para Rect buttonRect = GUILayoutUtility.GetRect(content, style, options); if (EditorGUI.DropdownButton(buttonRect, content, FocusType.Passive, style)) { - PopupWindow.Show(buttonRect, new AudioMixerExposedParametersPopup(controller), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(buttonRect, new AudioMixerExposedParametersPopup(controller)); } } diff --git a/Editor/Mono/Audio/Mixer/GUI/AudioMixerSelection.cs b/Editor/Mono/Audio/Mixer/GUI/AudioMixerSelection.cs deleted file mode 100644 index 9780288e07..0000000000 --- a/Editor/Mono/Audio/Mixer/GUI/AudioMixerSelection.cs +++ /dev/null @@ -1,82 +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.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor.Audio; - -namespace UnityEditor -{ - internal class AudioMixerSelection - { - public AudioMixerSelection(AudioMixerController controller) - { - m_Controller = controller; - ChannelStripSelection = new List(); - SyncToUnitySelection(); - } - - private AudioMixerController m_Controller; - public List ChannelStripSelection { get; private set; } - - // Channelstrip selection - // We rely on SyncToUnitySelection is being called after setting Selection.objects through AudioWindow::OnSelectionChange () - public void SyncToUnitySelection() - { - if (m_Controller != null) - RefreshCachedChannelStripSelection(); - } - - public void SetChannelStrips(List newSelection) - { - Selection.objects = newSelection.ToArray(); - //Debug.Log("SetChannelStrips " + DebugUtils.ListToString(Selection.instanceIDs)); - } - - public void SetSingleChannelStrip(AudioMixerGroupController group) - { - Selection.objects = new[] {group}; - //Debug.Log("SetSingleChannelStrip " + DebugUtils.ListToString(Selection.instanceIDs)); - } - - public void ToggleChannelStrip(AudioMixerGroupController group) - { - var selection = new List(Selection.objects); - if (selection.Contains(group)) - selection.Remove(group); - else - selection.Add(group); - Selection.objects = selection.ToArray(); - } - - public void ClearChannelStrips() - { - Selection.objects = new Object[0]; - //Debug.Log("ClearChannelStrips " + DebugUtils.ListToString(Selection.instanceIDs)); - } - - public bool HasSingleChannelStripSelection() - { - return ChannelStripSelection.Count == 1; - } - - private void RefreshCachedChannelStripSelection() - { - var selected = Selection.GetFiltered(typeof(AudioMixerGroupController), SelectionMode.Deep); - ChannelStripSelection = new List(); - List allGroups = m_Controller.GetAllAudioGroupsSlow(); - - foreach (var g in allGroups) - if (selected.Contains(g)) - ChannelStripSelection.Add(g); - } - - // Call this after making changes to the group topology (when removing groups) - public void Sanitize() - { - RefreshCachedChannelStripSelection(); - } - } -} diff --git a/Editor/Mono/Audio/Mixer/GUI/AudioMixerSnapshotPopup.cs b/Editor/Mono/Audio/Mixer/GUI/AudioMixerSnapshotPopup.cs deleted file mode 100644 index bb6b5658c8..0000000000 --- a/Editor/Mono/Audio/Mixer/GUI/AudioMixerSnapshotPopup.cs +++ /dev/null @@ -1,42 +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 System.Collections.Generic; -using System.Linq; - -namespace UnityEditor -{/* - internal partial class AudioMixerSnapshotPopup : IPopupWindowContent - { - internal static void SnapshotPopup (GameViewSizeGroupType groupType, int selectedIndex, System.Action itemClickedCallback, GUIStyle style, params GUILayoutOption[] options) - { - Rect buttonRect = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight, style, options); - EditorGUI.GameViewSizePopup(buttonRect, groupType, selectedIndex, itemClickedCallback, style); - } - - public static void ToolbarButton () - { - - } - - readonly AudioMixerSnapshotListView m_SnapshotListView = new AudioMixerSnapshotListView(); - - public void OnGUI (EditorWindow caller, Rect rect) - { - m_SnapshotListView.OnGUI (rect); - } - - public Vector2 GetWindowSize () - { - return new Vector2 (300, 600); - } - - public void OnDisable () - { - - - }}*/ -} // namespace diff --git a/Editor/Mono/Audio/Mixer/GUI/AudioMixerUtility.cs b/Editor/Mono/Audio/Mixer/GUI/AudioMixerUtility.cs deleted file mode 100644 index c837ea7345..0000000000 --- a/Editor/Mono/Audio/Mixer/GUI/AudioMixerUtility.cs +++ /dev/null @@ -1,38 +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 UnityEditor.Audio; - -namespace UnityEditor -{ - internal class AudioMixerUtility - { - static public void RepaintAudioMixerAndInspectors() - { - InspectorWindow.RepaintAllInspectors(); - AudioMixerWindow.RepaintAudioMixerWindow(); - } - - public class VisitorFetchInstanceIDs - { - public List instanceIDs = new List(); - public void Visitor(AudioMixerGroupController group) - { - instanceIDs.Add(group.GetInstanceID()); - } - } - - public static void VisitGroupsRecursivly(AudioMixerGroupController group, Action visitorCallback) - { - foreach (var child in group.children) - VisitGroupsRecursivly(child, visitorCallback); - - if (visitorCallback != null) - visitorCallback(group); - } - } -} -// namespace diff --git a/Editor/Mono/Audio/Mixer/GUI/ObjectTreeSelector.cs b/Editor/Mono/Audio/Mixer/GUI/ObjectTreeSelector.cs deleted file mode 100644 index 087174e762..0000000000 --- a/Editor/Mono/Audio/Mixer/GUI/ObjectTreeSelector.cs +++ /dev/null @@ -1,378 +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.Text; -using UnityEngine; -using UnityEngine.Events; - -namespace UnityEditor -{ - // TODO: - // Undo collapsing etc see ObjectSelector - // Check if sendCommandEvent to client view is needed - - // Description: Since TreeView is not serialized the client should set the tree view when requested - // by ObjectTreeSelector. Requested by calling treeViewNeededCallback provided by the client, - // use SetTreeView() to set tree view. - /* - internal class ObjectTreeSelectorData - { - public ObjectTreeSelector objectTreeSelector; - public TreeViewState state; - public Rect treeViewRect; - public int userData; - } - - internal class ObjectTreeSelector : EditorWindow - { - static ObjectTreeSelector s_Instance = null; - TreeView m_TreeView; - TreeViewState m_TreeViewState; - bool m_FocusSearchFilter; - const int kNoneItemID = 0; - int m_ErrorCounter = 0; - int m_OriginalSelectedID; - int m_UserData; - int m_LastSelectedID = -1; - string m_SelectedPath = ""; - const string kSearchFieldTag = "TreeSearchField"; - const float kBottomBarHeight = 17f; - const float kTopBarHeight = 27f; - SelectionEvent m_SelectionEvent; - TreeViewNeededEvent m_TreeViewNeededEvent; - - [Serializable] public class SelectionEvent : UnityEvent { } - [Serializable] public class TreeViewNeededEvent : UnityEvent { } - - class Styles - { - public GUIStyle searchBg = new GUIStyle("ProjectBrowserTopBarBg"); - public GUIStyle bottomBarBg = new GUIStyle("ProjectBrowserBottomBarBg"); - public Styles () - { - searchBg.border = new RectOffset(0,0,2,2); - searchBg.fixedHeight = 0; - - bottomBarBg.alignment = TextAnchor.MiddleLeft; - bottomBarBg.fontSize = EditorStyles.label.fontSize; - bottomBarBg.padding = new RectOffset(5,5,0,0); - } - } - static Styles s_Styles; - - - public static void Show (string windowTitle, UnityAction treeViewNeededCallback, UnityAction selectionCallback, int initialSelectedTreeViewItemID, int userData) - { - if (s_Instance == null) - { - s_Instance = (ObjectTreeSelector)GetWindow (typeof (ObjectTreeSelector), true, windowTitle, false); - s_Instance.minSize = new Vector2 (205, 220); - s_Instance.maxSize = new Vector2 (1900, 3000); - s_Instance.ShowAuxWindow (); // Use this if auto close on lost focus is wanted. - } - else - { - s_Instance.Repaint (); - } - - s_Instance.Init (treeViewNeededCallback, selectionCallback, initialSelectedTreeViewItemID, userData); - } - - ObjectTreeSelector () - { - hideFlags = HideFlags.DontSave; // Because we are a utility we do not want to be saved to layout - } - - void Init (UnityAction treeViewNeededCallback, UnityAction selectionCallback, int initialSelectedTreeViewItemID, int userData) - { - if (m_TreeViewNeededEvent == null) - m_TreeViewNeededEvent = new TreeViewNeededEvent(); - m_TreeViewNeededEvent.AddPersistentListener (treeViewNeededCallback); - - if (m_SelectionEvent == null) - m_SelectionEvent = new SelectionEvent(); - m_SelectionEvent.AddPersistentListener (selectionCallback); - - m_OriginalSelectedID = initialSelectedTreeViewItemID; - m_UserData = userData; - - // Clear previous state to ensure fresh start - m_TreeView = null; - m_TreeViewState = null; - m_ErrorCounter = 0; - m_FocusSearchFilter = true; // start by focusing search field - - // Initial setup - EnsureTreeViewIsValid (GetTreeViewRect ()); - if (m_TreeView != null) - { - m_TreeView.SetSelection (new [] {m_OriginalSelectedID}, true); - } - } - - // Call this when requested by ObjectTreeSelector (it calls treeViewNeededCallback) - public void SetTreeView (TreeView treeView) - { - m_TreeView = treeView; - - // Hook up to tree view events - m_TreeView.selectionChangedCallback -= OnItemSelectionChanged; - m_TreeView.selectionChangedCallback += OnItemSelectionChanged; - m_TreeView.itemDoubleClickedCallback -= OnItemDoubleClicked; - m_TreeView.itemDoubleClickedCallback += OnItemDoubleClicked; - } - - bool EnsureTreeViewIsValid (Rect treeViewRect) - { - if (m_TreeViewState == null) - m_TreeViewState = new TreeViewState (); - - if (m_TreeView == null) - { - var input = new ObjectTreeSelectorData () - { - state = m_TreeViewState, - treeViewRect = treeViewRect, - userData = m_UserData, - objectTreeSelector = this - }; - - m_TreeViewNeededEvent.Invoke (input); - if (m_TreeView != null) - { - if (m_TreeView.data.root == null) - { - m_TreeView.ReloadData (); - } - } - - if (m_TreeView == null) - { - if (m_ErrorCounter == 0) - { - Debug.LogError ("ObjectTreeSelector is missing its tree view. Ensure to call 'SetTreeView()' when the treeViewNeededCallback is invoked!"); - m_ErrorCounter++; - } - return false; - } - } - return true; - } - - Rect GetTreeViewRect () - { - return new Rect (0, kTopBarHeight, position.width, position.height - kBottomBarHeight - kTopBarHeight); - } - - public void OnGUI () - { - if (s_Styles == null) - s_Styles = new Styles (); - - Rect rect = new Rect (0,0, position.width, position.height); - Rect toolbarRect = new Rect (rect.x, rect.y, rect.width, kTopBarHeight); - Rect bottomRect = new Rect (rect.x, rect.yMax - kBottomBarHeight, rect.width, kBottomBarHeight); - Rect treeViewRect = GetTreeViewRect (); - - if (!EnsureTreeViewIsValid (treeViewRect)) - return; - - int treeViewControlID = GUIUtility.GetControlID ("Tree".GetHashCode (), FocusType.Keyboard); - - HandleCommandEvents (); - HandleKeyboard (treeViewControlID); - SearchArea (toolbarRect); - TreeViewArea (treeViewRect, treeViewControlID); - BottomBar (bottomRect); - - // Close window cancel changes - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) - Cancel (); - } - - void BottomBar (Rect bottomRect) - { - int currentID = m_TreeView.GetSelection ().FirstOrDefault (); // 0 is none selected - - // Refresh cached string - if (currentID != m_LastSelectedID) - { - m_LastSelectedID = currentID; - m_SelectedPath = ""; - var selected = m_TreeView.FindNode (currentID); - if (selected != null) - { - StringBuilder sb = new StringBuilder(); - var item = selected; - while (item != null && item != m_TreeView.data.root) - { - if (item != selected) - sb.Insert (0, "/"); - sb.Insert(0, item.displayName); - item = item.parent; - } - m_SelectedPath = sb.ToString (); - } - } - - GUI.Label (bottomRect, GUIContent.none, s_Styles.bottomBarBg); - if (!string.IsNullOrEmpty (m_SelectedPath)) - GUI.Label (bottomRect, GUIContent.Temp (m_SelectedPath), EditorStyles.miniLabel); - } - - private void OnItemDoubleClicked (int id) - { - Close (); - } - - private void OnItemSelectionChanged (int[] selection) - { - if (m_SelectionEvent != null) - { - TreeViewItem item = null; - if (selection.Length > 0) - { - item = m_TreeView.FindNode (selection[0]); - } - FireSelectionEvent (item); - } - } - - void HandleKeyboard (int treeViewControlID) - { - if (Event.current.type != EventType.KeyDown) - return; - - switch (Event.current.keyCode) - { - case KeyCode.Return: - case KeyCode.KeypadEnter: - Event.current.Use (); - Close (); - GUI.changed = true; - GUIUtility.ExitGUI (); - break; - case KeyCode.DownArrow: - case KeyCode.UpArrow: - { - // When searchfield has focus give keyboard focus to the tree view on Down/UpArrow - bool hasSearchFilterFocus = GUI.GetNameOfFocusedControl () == kSearchFieldTag; - if (hasSearchFilterFocus) - { - GUIUtility.keyboardControl = treeViewControlID; - - // If nothing is selected ensure first item is selected, otherwise ensure current - // selection is visible (we just gave focus to the tree) - if (m_TreeView.IsLastClickedPartOfRows ()) - FrameSelectedTreeViewItem (); - else - m_TreeView.OffsetSelection (1); // Selects first item - - Event.current.Use (); - } - } - break; - default: - return; - } - } - - void FrameSelectedTreeViewItem () - { - m_TreeView.Frame (m_TreeView.state.lastClickedID, true, false); - } - - void HandleCommandEvents () - { - Event evt = Event.current; - - if (evt.type != EventType.ExecuteCommand && evt.type != EventType.ValidateCommand) - return; - - if (evt.commandName == EventCommandNames.FrameSelected) - { - if (evt.type == EventType.ExecuteCommand && m_TreeView.HasSelection ()) - { - m_TreeView.searchString = string.Empty; - FrameSelectedTreeViewItem (); - } - evt.Use (); - GUIUtility.ExitGUI (); - } - if (evt.commandName == EventCommandNames.Find) - { - if (evt.type == EventType.ExecuteCommand) - { - FocusSearchField (); - } - evt.Use (); - } - } - - void FireSelectionEvent (TreeViewItem item) - { - if (m_SelectionEvent != null) - m_SelectionEvent.Invoke (item); - } - - void Cancel () - { - FireSelectionEvent (m_TreeView.FindNode (m_OriginalSelectedID)); - - Close (); - GUI.changed = true; - GUIUtility.ExitGUI (); - } - - void TreeViewArea (Rect treeViewRect, int treeViewControlID) - { - bool hasRows = m_TreeView.data.GetRows ().Count > 0; - if (hasRows) - { - m_TreeView.OnGUI (treeViewRect, treeViewControlID); - } - } - - void SearchArea (Rect toolbarRect) - { - GUI.Label (toolbarRect, GUIContent.none, s_Styles.searchBg); - - // ESC clears search field and removes it's focus. But if we get an esc event we only want to clear search field. - // So we need special handling afterwards. - bool wasEscape = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; - GUI.SetNextControlName (kSearchFieldTag); - string newSearchFilter = EditorGUI.SearchField (new Rect (5, 5, toolbarRect.width - 10, 15), m_TreeView.searchString); - - if (wasEscape && Event.current.type == EventType.Used) - { - // If we hit esc and the string WAS empty, it's an actual cancel event. - if (m_TreeView.searchString == string.Empty) - Cancel (); - - // Otherwise the string has been cleared and focus has been lost. We don't have anything else to recieve focus, so we want to refocus the search field. - m_FocusSearchFilter = true; - } - - if (newSearchFilter != m_TreeView.searchString || m_FocusSearchFilter) - { - m_TreeView.searchString = newSearchFilter; - Repaint (); - } - - if (m_FocusSearchFilter) - { - EditorGUI.FocusTextInControl (kSearchFieldTag); - if (Event.current.type == EventType.Repaint) - m_FocusSearchFilter = false; - } - } - - internal void FocusSearchField () - { - m_FocusSearchFilter = true; - } - }*/ -} // namespace diff --git a/Editor/Mono/Audio/StreamedAudioClipPreview.cs b/Editor/Mono/Audio/StreamedAudioClipPreview.cs deleted file mode 100644 index 1fcfc9efe1..0000000000 --- a/Editor/Mono/Audio/StreamedAudioClipPreview.cs +++ /dev/null @@ -1,466 +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.Reflection; -using UnityEngine; - - -namespace UnityEditor -{ - class StreamedAudioClipPreview : WaveformPreview - { - static class AudioClipMinMaxOverview - { - static Dictionary s_Data = new Dictionary(); - public static float[] GetOverviewFor(AudioClip clip) - { - if (!s_Data.ContainsKey(clip)) - { - var path = AssetDatabase.GetAssetPath(clip); - if (path == null) - return null; - var importer = AssetImporter.GetAtPath(path); - if (importer == null) - return null; - - s_Data[clip] = AudioUtil.GetMinMaxData(importer as AudioImporter); - } - - return s_Data[clip]; - } - } - - struct ClipPreviewDetails - { - public float[] preview; - public int previewSamples; - public double normalizedDuration; - public double normalizedStart; - public double deltaStep; - public AudioClip clip; - public int previewPixelsToRender; - public double localStart; - public double localLength; - public bool looping; - - public ClipPreviewDetails(AudioClip clip, bool isLooping, int size, double localStart, double localLength) - { - if (size < 2) - throw new ArgumentException("Size has to be larger than 1"); - - if (localLength <= 0) - throw new ArgumentException("length has to be longer than zero", "localLength"); - - if (localStart < 0) - throw new ArgumentException("localStart has to be positive", "localStart"); - - if (clip == null) - throw new ArgumentNullException("clip"); - - this.clip = clip; - - preview = AudioClipMinMaxOverview.GetOverviewFor(clip); - - if (preview == null) - throw new ArgumentException("Clip " + clip + "'s overview preview is null"); - - looping = isLooping; - - this.localStart = localStart; - this.localLength = localLength; - - if (looping) - { - previewPixelsToRender = size; - } - else - { - var clampedLength = Math.Min(clip.length - localStart, localLength); - previewPixelsToRender = (int)Math.Min(size, size * Math.Max(0, clampedLength / localLength)); - } - - previewSamples = preview.Length / (clip.channels * 2); - normalizedDuration = localLength / clip.length; - normalizedStart = localStart / clip.length; - deltaStep = (previewSamples * normalizedDuration) / (size - 1); - } - - public bool IsCandidateForStreaming() - { - // shortcut, no need to start the stream if the start extends beyond the first clip region and the clip is "hold" - if (!looping && localStart >= clip.length) - return false; - - return deltaStep < 0.5; - } - } - struct Segment - { - public WaveformStreamer streamer; - public int streamingIndexOffset; - public int textureOffset; - public int segmentLength; - } - - class StreamingContext - { - public int index; - } - - Dictionary m_Contexts = new Dictionary(); - Segment[] m_StreamedSegments; - AudioClip m_Clip; - - public StreamedAudioClipPreview(AudioClip clip, int initialSize) - : base(clip, initialSize, clip.channels) - { - m_ClearTexture = false; - m_Clip = clip; - m_Start = 0; - m_Length = clip.length; - } - - protected override void InternalDispose() - { - base.InternalDispose(); - KillAndClearStreamers(); - m_StreamedSegments = null; - } - - protected override void OnModifications(MessageFlags cFlags) - { - bool restartStreaming = false; - - if (HasFlag(cFlags, MessageFlags.TextureChanged) || HasFlag(cFlags, MessageFlags.Size) || HasFlag(cFlags, MessageFlags.Length) || HasFlag(cFlags, MessageFlags.Looping)) - { - KillAndClearStreamers(); - - if (length <= 0) - return; - - var details = new ClipPreviewDetails(m_Clip, looping, (int)Size.x, start, length); - - UploadPreview(details); - - if (details.IsCandidateForStreaming()) - restartStreaming = true; - } - - if (!optimized) - { - KillAndClearStreamers(); - restartStreaming = false; - } - else if (HasFlag(cFlags, MessageFlags.Optimization) && !restartStreaming) - { - // optimization toggled on, need to query whether we should start streaming - var details = new ClipPreviewDetails(m_Clip, looping, (int)Size.x, start, length); - - if (details.IsCandidateForStreaming()) - restartStreaming = true; - } - - if (restartStreaming) - { - m_StreamedSegments = CalculateAndStartStreamers(start, length); - - if (m_StreamedSegments != null && m_StreamedSegments.Length > 0) - { - foreach (var r in m_StreamedSegments) - { - if (!m_Contexts.ContainsKey(r.streamer)) - m_Contexts.Add(r.streamer, new StreamingContext()); - } - } - } - - base.OnModifications(cFlags); - } - - void KillAndClearStreamers() - { - foreach (var c in m_Contexts) - { - c.Key.Stop(); - } - - m_Contexts.Clear(); - } - - Segment[] CalculateAndStartStreamers(double localStart, double localLength) - { - Segment[] segments = null; - var originalStart = localStart; - // we don't care about the global position, only the locally visible offset into the clip - localStart %= m_Clip.length; - - var secondsPerPixel = localLength / Size.x; - - if (!looping) - { - // holding (= !looping) is a special case handled before everything - // else, because it's very simple to implement since it defines a - // section capped by length of the clip - - if (originalStart > m_Clip.length) - return null; - - var clampedLength = Math.Min(m_Clip.length - originalStart, localLength); - var previewPixelsToRender = (int)Math.Min(Size.x, Size.x * Math.Max(0, clampedLength / localLength)); - - if (previewPixelsToRender < 1) - return null; - - segments = new Segment[1]; - - segments[0].streamer = new WaveformStreamer(m_Clip, originalStart, clampedLength, previewPixelsToRender, OnNewWaveformData); - segments[0].segmentLength = (int)Size.x; - segments[0].textureOffset = 0; - segments[0].streamingIndexOffset = 0; - - return segments; - } - - // epsilon added to discriminate between invisible floating point rounding errors - // and actual loops (i.e. more than a single pixel larger than then length) - if (localStart + localLength - secondsPerPixel > m_Clip.length) - { - var secondsToPixels = Size.x / localLength; - - // special case, the first part is clipped but at least one full length of the clip is available - // we can then use one streamer to fill in all visible segments - if (localLength >= m_Clip.length) - { - var numberOfLoops = localLength / m_Clip.length; - var streamer = new WaveformStreamer(m_Clip, 0, m_Clip.length, (int)(Size.x / numberOfLoops), OnNewWaveformData); - - var currentClipSegmentPart = m_Clip.length - localStart; - - var localPosition = 0.0; - - segments = new Segment[Mathf.CeilToInt((float)((localStart + localLength) / m_Clip.length))]; - - for (int i = 0; i < segments.Length; ++i) - { - var cappedLength = Math.Min(currentClipSegmentPart + localPosition, localLength) - localPosition; - segments[i].streamer = streamer; - segments[i].segmentLength = (int)(cappedLength * secondsToPixels); - segments[i].textureOffset = (int)(localPosition * secondsToPixels); - segments[i].streamingIndexOffset = (int)((m_Clip.length - currentClipSegmentPart) * secondsToPixels); - - localPosition += currentClipSegmentPart; - currentClipSegmentPart = m_Clip.length; - } - } - else - { - // two disjoint regions, since streaming is time-continuous we have to split it up in two portions - var firstPart = m_Clip.length - localStart; - var secondPart = localLength - firstPart; - - segments = new Segment[2]; - - segments[0].streamer = new WaveformStreamer(m_Clip, localStart, firstPart, (int)(firstPart * secondsToPixels), OnNewWaveformData); - segments[0].segmentLength = (int)(firstPart * secondsToPixels); - segments[0].textureOffset = 0; - segments[0].streamingIndexOffset = 0; - - segments[1].streamer = new WaveformStreamer(m_Clip, 0, secondPart, (int)(secondPart * secondsToPixels), OnNewWaveformData); - segments[1].segmentLength = (int)(secondPart * secondsToPixels); - segments[1].textureOffset = (int)(firstPart * secondsToPixels); - segments[1].streamingIndexOffset = 0; - } - } - else - { - // handle single visible part of clip, that does not extend beyond the end - // with a length less than a clip - equaling one streamer. - segments = new Segment[1]; - - segments[0].streamer = new WaveformStreamer(m_Clip, localStart, localLength, (int)Size.x, OnNewWaveformData); - segments[0].segmentLength = (int)Size.x; - segments[0].textureOffset = 0; - segments[0].streamingIndexOffset = 0; - } - - return segments; - } - - void UploadPreview(ClipPreviewDetails details) - { - var channels = details.clip.channels; - float[] resampledPreview = new float[(int)(channels * Size.x * 2)]; - - if (details.localStart + details.localLength > details.clip.length) - { - ResamplePreviewLooped(details, resampledPreview); - } - else - ResamplePreviewConfined(details, resampledPreview); - - SetMMWaveData(0, resampledPreview); - } - - void ResamplePreviewConfined(ClipPreviewDetails details, float[] resampledPreview) - { - var channels = m_Clip.channels; - var samples = details.previewSamples; - var delta = details.deltaStep; - var position = details.normalizedStart * samples; - var preview = details.preview; - - if (delta > 0.5) - { - int oldPosition = (int)position, floorPosition = oldPosition; - // for each step, there's more than one sample so we do min max on the min max data - // to avoid aliasing issues - for (int i = 0; i < details.previewPixelsToRender; ++i) - { - for (int c = 0; c < channels; ++c) - { - var x = oldPosition; - floorPosition = (int)position; - - float min = preview[2 * x * channels + c * 2]; - float max = preview[2 * x * channels + c * 2 + 1]; - - while (++x < floorPosition) - { - // yes, the data contained in the min max audio util overview is actually swapped (maxmin data) - min = Mathf.Max(min, preview[2 * x * channels + c * 2]); - max = Mathf.Min(max, preview[2 * x * channels + c * 2 + 1]); - } - - resampledPreview[2 * i * channels + c * 2] = max; - resampledPreview[2 * i * channels + c * 2 + 1] = min; - } - - position += delta; - oldPosition = floorPosition; - } - } - else - { - // fractionate interpolation - for (int i = 0; i < details.previewPixelsToRender; ++i) - { - var x = (int)(position - 1); - var x1 = x + 1; - float fraction = (float)((position - 1) - x); - - x = Mathf.Max(0, x); - x1 = Mathf.Min(x1, samples - 1); - - for (int c = 0; c < channels; ++c) - { - var minCurrent = preview[2 * x * channels + c * 2]; - var maxCurrent = preview[2 * x * channels + c * 2 + 1]; - - var minNext = preview[2 * x1 * channels + c * 2]; - var maxNext = preview[2 * x1 * channels + c * 2 + 1]; - - resampledPreview[2 * i * channels + c * 2] = fraction * maxNext + (1 - fraction) * maxCurrent; - resampledPreview[2 * i * channels + c * 2 + 1] = fraction * minNext + (1 - fraction) * minCurrent; - } - - position += delta; - } - } - } - - void ResamplePreviewLooped(ClipPreviewDetails details, float[] resampledPreview) - { - var previewSize = details.preview.Length; - var channels = m_Clip.channels; - var samples = details.previewSamples; - - var delta = details.deltaStep; - var position = details.normalizedStart * samples; - var preview = details.preview; - - if (delta > 0.5) - { - int oldPosition = (int)position, floorPosition = oldPosition; - // for each step, there's more than one sample so we do min max on the min max data - // to avoid aliasing issues - for (int i = 0; i < details.previewPixelsToRender; ++i) - { - for (int c = 0; c < channels; ++c) - { - var x = oldPosition; - floorPosition = (int)position; - - var wrappedIndex = (2 * x * channels + c * 2) % previewSize; - - float min = preview[wrappedIndex]; - float max = preview[wrappedIndex + 1]; - - while (++x < floorPosition) - { - wrappedIndex = (2 * x * channels + c * 2) % previewSize; - // yes, the data contained in the min max audio util overview is actually swapped (maxmin data) - min = Mathf.Max(min, preview[wrappedIndex]); - max = Mathf.Min(max, preview[wrappedIndex + 1]); - } - - resampledPreview[2 * i * channels + c * 2] = max; - resampledPreview[2 * i * channels + c * 2 + 1] = min; - } - - position += delta; - oldPosition = floorPosition; - } - } - else - { - // fractionate interpolation - for (int i = 0; i < details.previewPixelsToRender; ++i) - { - var x = (int)(position - 1); - var x1 = x + 1; - float fraction = (float)((position - 1) - x); - - for (int c = 0; c < channels; ++c) - { - var xWrapped = (2 * x * channels + c * 2) % previewSize; - - var minCurrent = preview[xWrapped]; - var maxCurrent = preview[xWrapped + 1]; - - var x1Wrapped = (2 * x1 * channels + c * 2) % previewSize; - - var minNext = preview[x1Wrapped]; - var maxNext = preview[x1Wrapped + 1]; - - resampledPreview[2 * i * channels + c * 2] = fraction * maxNext + (1 - fraction) * maxCurrent; - resampledPreview[2 * i * channels + c * 2 + 1] = fraction * minNext + (1 - fraction) * minCurrent; - } - - position += delta; - } - } - } - - bool OnNewWaveformData(WaveformStreamer streamer, float[] data, int remaining) - { - StreamingContext c = m_Contexts[streamer]; - - int pixelPos = c.index / m_Clip.channels; - - for (var i = 0; i < m_StreamedSegments.Length; i++) - { - if (m_StreamedSegments[i].streamer == streamer && pixelPos >= m_StreamedSegments[i].streamingIndexOffset && m_StreamedSegments[i].segmentLength > (pixelPos - m_StreamedSegments[i].streamingIndexOffset)) - { - SetMMWaveData((m_StreamedSegments[i].textureOffset - m_StreamedSegments[i].streamingIndexOffset) * m_Clip.channels + c.index, data); - } - } - - c.index += data.Length / 2; - - return remaining != 0; - } - } -} diff --git a/Editor/Mono/Audio/WaveformPreviewFactory.cs b/Editor/Mono/Audio/WaveformPreviewFactory.cs deleted file mode 100644 index 23578dd93e..0000000000 --- a/Editor/Mono/Audio/WaveformPreviewFactory.cs +++ /dev/null @@ -1,20 +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.Reflection; -using UnityEngine; - - -namespace UnityEditor -{ - static class WaveformPreviewFactory - { - public static WaveformPreview Create(int initialSize, AudioClip clip) - { - return new StreamedAudioClipPreview(clip, initialSize); - } - } -} diff --git a/Editor/Mono/Audio/WaveformStreamer.bindings.cs b/Editor/Mono/Audio/WaveformStreamer.bindings.cs deleted file mode 100644 index 0b6ec9ccf6..0000000000 --- a/Editor/Mono/Audio/WaveformStreamer.bindings.cs +++ /dev/null @@ -1,64 +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.Bindings; - -namespace UnityEditor -{ - [NativeType(Header = "Editor/Mono/Audio/WaveformStreamer.bindings.h")] - internal sealed partial class WaveformStreamer - { - internal IntPtr m_Data; - - public bool done - { - get { return Internal_WaveformStreamerQueryFinishedStatus(m_Data); } - } - public void Stop() - { - Internal_WaveformStreamerStop(m_Data); - } - - public WaveformStreamer(AudioClip clip, double start, double duration, - int numOutputSamples, Func onNewWaveformData) - { - m_Data = Internal_WaveformStreamerCreate(this, clip, start, duration, numOutputSamples, onNewWaveformData); - } - - private WaveformStreamer(AudioClip clip, double start, double duration, - int numOutputSamples, Func onNewWaveformData) - { - m_Data = Internal_WaveformStreamerCreateUntyped(this, clip, start, duration, numOutputSamples, onNewWaveformData); - } - - ~WaveformStreamer() - { - if (m_Data != IntPtr.Zero) - Internal_WaveformStreamerDestroy(m_Data); - } - - internal static object CreateUntypedWaveformStreamer(AudioClip clip, double start, double duration, - int numOutputSamples, Func onNewWaveformData) - { - return new WaveformStreamer(clip, start, duration, numOutputSamples, onNewWaveformData); - } - - [NativeThrows] - internal static extern IntPtr Internal_WaveformStreamerCreate(WaveformStreamer instance, [NotNull] AudioClip clip, double start, double duration, - int numOutputSamples, [NotNull] Func onNewWaveformData); - - internal static extern bool Internal_WaveformStreamerQueryFinishedStatus(IntPtr streamer); - - internal static extern void Internal_WaveformStreamerStop(IntPtr streamer); - - [NativeThrows] - internal static extern IntPtr Internal_WaveformStreamerCreateUntyped(object instance, [NotNull] AudioClip clip, double start, double duration, - int numOutputSamples, [NotNull] Func onNewWaveformData); - - [NativeMethod(IsThreadSafe = true)] - internal static extern void Internal_WaveformStreamerDestroy(IntPtr streamer); - } -} diff --git a/Editor/Mono/AvatarUtility.bindings.cs b/Editor/Mono/AvatarUtility.bindings.cs deleted file mode 100644 index 350561d434..0000000000 --- a/Editor/Mono/AvatarUtility.bindings.cs +++ /dev/null @@ -1,19 +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 UnityEditor; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor -{ - [NativeHeader("Runtime/Animation/Animator.h")] - [NativeHeader("Editor/Src/Animation/AvatarUtility.h")] - internal class AvatarUtility - { - extern static internal void SetHumanPose(Animator animator, float[] dof); - } -} diff --git a/Editor/Mono/BlendTree.bindings.cs b/Editor/Mono/BlendTree.bindings.cs deleted file mode 100644 index 835371be5c..0000000000 --- a/Editor/Mono/BlendTree.bindings.cs +++ /dev/null @@ -1,131 +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 System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEditor; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor.Animations -{ - public enum BlendTreeType - { - Simple1D = 0 , - SimpleDirectional2D = 1, - FreeformDirectional2D = 2, - FreeformCartesian2D = 3, - Direct = 4 - } - - [NativeType("Editor/Src/Animation/BlendTree.h")] - [StructLayout(LayoutKind.Sequential)] - public struct ChildMotion - { - public Motion motion { get { return m_Motion; } set { m_Motion = value; } } - public float threshold { get { return m_Threshold; } set { m_Threshold = value; } } - public Vector2 position { get { return m_Position; } set { m_Position = value; } } - public float timeScale { get { return m_TimeScale; } set { m_TimeScale = value; } } - public float cycleOffset { get { return m_CycleOffset; } set { m_CycleOffset = value; } } - public string directBlendParameter { get { return m_DirectBlendParameter; } set { m_DirectBlendParameter = value; }} - public bool mirror { get { return m_Mirror; } set { m_Mirror = value; } } - - Motion m_Motion; - float m_Threshold; - Vector2 m_Position; - float m_TimeScale; - float m_CycleOffset; - string m_DirectBlendParameter; - bool m_Mirror; - } - - [NativeHeader("Editor/Src/Animation/BlendTree.bindings.h")] - [NativeType("Editor/Src/Animation/BlendTree.h")] - public partial class BlendTree : Motion - { - public BlendTree() - { - Internal_Create(this); - } - - [FreeFunction("BlendTreeBindings::Internal_Create")] - extern private static void Internal_Create([Writable] BlendTree self); - - extern public string blendParameter - { - get; - set; - } - extern public string blendParameterY - { - get; - set; - } - extern public BlendTreeType blendType - { - get; - set; - } - - extern public ChildMotion[] children - { - get; - set; - } - - extern internal int GetChildMotionCount(); - - internal Motion GetChildMotion(int index) - { - if (index < 0 && index >= GetChildMotionCount()) - throw new ArgumentOutOfRangeException("index"); - - return Internal_GetChildMotion(index); - } - - [NativeMethod("GetChildMotion")] - extern internal Motion Internal_GetChildMotion(int index); - - [NativeMethod("SetDirectBlendParameter")] - extern internal void SetDirectBlendTreeParameter(int index, string parameter); - - [NativeMethod("GetDirectBlendParameter")] - extern internal string GetDirectBlendTreeParameter(int index); - - extern public bool useAutomaticThresholds - { - get; - set; - } - extern public float minThreshold - { - get; - set; - } - extern public float maxThreshold - { - get; - set; - } - - extern internal void SortChildren(); - - extern internal int recursiveBlendParameterCount - { - get; - } - extern internal string GetRecursiveBlendParameter(int index); - extern internal float GetRecursiveBlendParameterMin(int index); - extern internal float GetRecursiveBlendParameterMax(int index); - - extern internal void SetInputBlendValue(string blendValueName, float value); - extern internal float GetInputBlendValue(string blendValueName); - - [NativeMethod("GetAnimationClips")] - extern internal AnimationClip[] GetAnimationClipsFlattened(); - } -} diff --git a/Editor/Mono/BlendTreePreviewUtility.bindings.cs b/Editor/Mono/BlendTreePreviewUtility.bindings.cs deleted file mode 100644 index fc5ac39bd6..0000000000 --- a/Editor/Mono/BlendTreePreviewUtility.bindings.cs +++ /dev/null @@ -1,28 +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.Bindings; -using UnityEngine.Scripting; -using UnityEngine.Internal; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace UnityEditorInternal -{ - [NativeHeader("Editor/Src/Animation/BlendTreePreviewUtility.h")] - public class BlendTreePreviewUtility - { - extern public static void GetRootBlendTreeChildWeights(Animator animator, int layerIndex, int stateHash, [Out] float[] weightArray); - - extern public static void CalculateRootBlendTreeChildWeights(Animator animator, int layerIndex, int stateHash, [Out] float[] weightArray, float blendX, float blendY); - - public static void CalculateBlendTexture(Animator animator, int layerIndex, int stateHash, Texture2D blendTexture, Texture2D[] weightTextures, Rect rect) - { - CalculateBlendTexture(animator, layerIndex, stateHash, blendTexture, weightTextures, rect.x, rect.y, rect.x + rect.width, rect.y + rect.height); - } - - extern protected static void CalculateBlendTexture(Animator animator, int layerIndex, int stateHash, Texture2D blendTexture, Texture2D[] weightTextures, float minX, float minY, float maxX, float maxY); - } -} diff --git a/Editor/Mono/BuildPipeline.bindings.cs b/Editor/Mono/BuildPipeline.bindings.cs index 87dd7ed3cc..64e3257ace 100644 --- a/Editor/Mono/BuildPipeline.bindings.cs +++ b/Editor/Mono/BuildPipeline.bindings.cs @@ -9,6 +9,7 @@ using UnityEngine.Bindings; using UnityEditor.Build.Reporting; using Mono.Cecil; +using UnityEditor.Scripting.ScriptCompilation; namespace UnityEditor { @@ -179,6 +180,7 @@ public class BuildPipeline internal static extern BuildTargetGroup GetBuildTargetGroupByName(string platform); internal static extern BuildTarget GetBuildTargetByName(string platform); + internal static extern EditorScriptCompilationOptions GetScriptCompileFlags(BuildOptions buildOptions, BuildTarget buildTarget); [FreeFunction] internal static extern string GetBuildTargetGroupDisplayName(BuildTargetGroup targetPlatformGroup); diff --git a/Editor/Mono/BuildPipeline/AssemblyStripper.cs b/Editor/Mono/BuildPipeline/AssemblyStripper.cs index 69c450511f..94da574fe4 100644 --- a/Editor/Mono/BuildPipeline/AssemblyStripper.cs +++ b/Editor/Mono/BuildPipeline/AssemblyStripper.cs @@ -77,7 +77,7 @@ private static bool StripAssembliesTo(string[] assemblies, string[] searchDirs, args.AddRange(additionalBlacklist.Select(path => "-x \"" + path + "\"")); args.AddRange(searchDirs.Select(d => "-d \"" + d + "\"")); - args.AddRange(assemblies.Select(assembly => "-a \"" + Path.GetFullPath(assembly) + "\"")); + args.AddRange(assemblies.Select(assembly => "--include-unity-root-assembly=\"" + Path.GetFullPath(assembly) + "\"")); args.Add($"--dotnetruntime={GetRuntimeArgumentValueForLinker(buildTargetGroup)}"); args.Add($"--dotnetprofile={GetProfileArgumentValueForLinker(buildTargetGroup)}"); args.Add("--use-editor-options"); @@ -270,7 +270,6 @@ private static void RunAssemblyStripper(IEnumerable assemblies, string managedAs blacklists = blacklists.Concat(new[] { WriteMethodsToPreserveBlackList(rcr, platformProvider.target), - WriteUnityEngineBlackList(), MonoAssemblyStripping.GenerateLinkXmlToPreserveDerivedTypes(managedAssemblyFolderPath, rcr) }); } @@ -377,15 +376,6 @@ private static string WriteMethodsToPreserveBlackList(RuntimeClassRegistry rcr, return methodPerserveBlackList; } - private static string WriteUnityEngineBlackList() - { - // UnityEngine.dll would be stripped, as it contains no referenced symbols, only type forwarders. - // Since we need those type forwarders, we generate blacklist to preserve the assembly (but no members). - var unityEngineBlackList = Path.GetTempFileName(); - File.WriteAllText(unityEngineBlackList, ""); - return unityEngineBlackList; - } - private static string GetMethodPreserveBlacklistContents(RuntimeClassRegistry rcr, BuildTarget target) { if (rcr.GetMethodsToPreserve().Count == 0) diff --git a/Editor/Mono/BuildPipeline/AssemblyTypeInfoGenerator.cs b/Editor/Mono/BuildPipeline/AssemblyTypeInfoGenerator.cs deleted file mode 100644 index 82be57f2b6..0000000000 --- a/Editor/Mono/BuildPipeline/AssemblyTypeInfoGenerator.cs +++ /dev/null @@ -1,429 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -// #define DOLOG -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.InteropServices; -using Mono.Cecil; -using Unity.SerializationLogic; - -namespace UnityEditor -{ - using GenericInstanceTypeMap = System.Collections.Generic.Dictionary; - - internal class AssemblyTypeInfoGenerator - { - [Flags] - public enum FieldInfoFlags - { - None = 0, - FixedBuffer = (1 << 0) - } - - [StructLayout(LayoutKind.Sequential)] - public struct FieldInfo - { - public string name; - public string type; - public FieldInfoFlags flags; - public int fixedBufferLength; - public string fixedBufferTypename; - }; - - [StructLayout(LayoutKind.Sequential)] - public struct ClassInfo - { - public string name; - public FieldInfo[] fields; - }; - - - private AssemblyDefinition assembly_; - private List classes_ = new List(); - private TypeResolver typeResolver = new TypeResolver(null); - - public ClassInfo[] ClassInfoArray - { - get { return classes_.ToArray(); } - } - - private class AssemblyResolver : BaseAssemblyResolver - { - public static IAssemblyResolver WithSearchDirs(params string[] searchDirs) - { - var resolver = new AssemblyResolver(); - foreach (var searchDir in searchDirs) - resolver.AddSearchDirectory(searchDir); - - // remove the two directories installed by default as this can cause issues with assemblies outside of the Assets folder - resolver.RemoveSearchDirectory("."); - resolver.RemoveSearchDirectory("bin"); - - return resolver; - } - - readonly IDictionary m_Assemblies; - - private AssemblyResolver() - : this(new Hashtable()) - { - } - - private AssemblyResolver(IDictionary assemblyCache) - { - m_Assemblies = assemblyCache; - } - - public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) - { - var asm = (AssemblyDefinition)m_Assemblies[name.Name]; - if (asm != null) - return asm; - - asm = base.Resolve(name, parameters); - m_Assemblies[name.Name] = asm; - - return asm; - } - } - - public AssemblyTypeInfoGenerator(string assembly, string[] searchDirs) - { - assembly_ = AssemblyDefinition.ReadAssembly(assembly, new ReaderParameters - { - AssemblyResolver = AssemblyResolver.WithSearchDirs(searchDirs) - }); - } - - public AssemblyTypeInfoGenerator(string assembly, IAssemblyResolver resolver) - { - assembly_ = AssemblyDefinition.ReadAssembly(assembly, new ReaderParameters - { - AssemblyResolver = resolver - }); - } - - // In embedded API inner names are separated by plus instead of fwdslash, eg. MyClass+MyInner, not MyClass/MyInner - // so we convert '/' to '+' here. - // Generic parameters are placed in square brackets instead of angle brackets - private string GetMonoEmbeddedFullTypeNameFor(TypeReference type) - { - var typeSpec = type as TypeSpecification; - string typeName; - - // Strip modifiers like volatile, as Mono doesn't treat them as part of type - if (typeSpec != null && typeSpec.IsRequiredModifier) - { - type = typeSpec.ElementType; - } - else if (type.IsRequiredModifier) - { - type = type.GetElementType(); - } - - typeName = type.FullName; - - // Mono compiler generates internal types with names such as "__FixedBuffer0" and "c__Iterator0" - // so we only replace angle brackets with square brackets if the type is a generic instance or has generic parameters. - if (type.HasGenericParameters || type.IsGenericInstance) - typeName = typeName.Replace('<', '[').Replace('>', ']'); - - return typeName.Replace('/', '+'); - } - - /* We use this GenericInstanceTypeMap to map generic types to their generic instance types, - This is needed for correctly assess inheritance in cases like this: - - class One - { - public T one; - } - - class Two : One - { - } - - In this case, we look at type Two, and see that it inherits from type One, - so we map T -> int. When we come across looking at field "one", we see that its - declaring type is a generic instance type and that T maps to int, so it writes down - that class One has a field "int one". - - We use a new map for going through each type instance (check GatherClassInfo()). - */ - private TypeReference ResolveGenericInstanceType(TypeReference typeToResolve, GenericInstanceTypeMap genericInstanceTypeMap) - { - var arrayType = typeToResolve as ArrayType; - - if (arrayType != null) - { - typeToResolve = new ArrayType(ResolveGenericInstanceType(arrayType.ElementType, genericInstanceTypeMap), arrayType.Rank); - } - - while (genericInstanceTypeMap.ContainsKey(typeToResolve)) - { - typeToResolve = genericInstanceTypeMap[typeToResolve]; - } - - if (typeToResolve.IsGenericInstance) - { - // Handle the case of nested generics, like List>> - var genericInstance = ((GenericInstanceType)typeToResolve); - typeToResolve = MakeGenericInstance(genericInstance.ElementType, genericInstance.GenericArguments, genericInstanceTypeMap); - } - - return typeToResolve; - } - - private void AddType(TypeReference typeRef, GenericInstanceTypeMap genericInstanceTypeMap) - { - // Prevent duplicates - if (classes_.Any(x => x.name == GetMonoEmbeddedFullTypeNameFor(typeRef))) - { - return; - } - - TypeDefinition type; - - try - { - type = typeRef.Resolve(); - } // This will happen for types which we don't have access to, like Windows.Foundation.IAsyncOperation - catch (AssemblyResolutionException) - { - return; - } - catch (NotSupportedException) // "NotSupportedException: Version not supported: 255.255.255.255" is thrown when assembly references WinRT assembly (e.g. mscorlib) - { - return; - } - - if (type == null) return; - - if (typeRef.IsGenericInstance) - { - var arguments = ((GenericInstanceType)typeRef).GenericArguments; - var parameters = type.GenericParameters; - - for (int i = 0; i < arguments.Count; i++) - { - if (parameters[i] != arguments[i]) - { - genericInstanceTypeMap[parameters[i]] = arguments[i]; - } - } - - typeResolver.Add((GenericInstanceType)typeRef); - } - - /* Process class itself before nested/base types in case user does something evil, for example: - - class Outer - { - class Inner : Child - { - } - } - - class Child : Outer - { - } - */ - - bool shouldImplementDeserializable = false; - - try - { - shouldImplementDeserializable = UnitySerializationLogic.ShouldImplementIDeserializable(type); - } - catch - { - // If assembly has unknown reference (for ex., see tests VariousPlugins, where Metro plugins are used), skip field - } - - if (!shouldImplementDeserializable) - { - // In this case we only take care of processing the nested types, if any. - AddNestedTypes(type, genericInstanceTypeMap); - } - else - { - var ci = new ClassInfo(); - ci.name = GetMonoEmbeddedFullTypeNameFor(typeRef); - ci.fields = GetFields(type, typeRef.IsGenericInstance, genericInstanceTypeMap); - - classes_.Add(ci); - - // Fetch info for inner types - AddNestedTypes(type, genericInstanceTypeMap); - - // Add base type - AddBaseType(typeRef, genericInstanceTypeMap); - } - - if (typeRef.IsGenericInstance) - typeResolver.Remove((GenericInstanceType)typeRef); - } - - private void AddNestedTypes(TypeDefinition type, GenericInstanceTypeMap genericInstanceTypeMap) - { - foreach (TypeDefinition nestedType in type.NestedTypes) - { - AddType(nestedType, genericInstanceTypeMap); - } - } - - private void AddBaseType(TypeReference typeRef, GenericInstanceTypeMap genericInstanceTypeMap) - { - var baseType = typeRef.Resolve().BaseType; - if (baseType != null) - { - /* If we are processing generic instance type and - its base type happens to be a generic instance class as well, - we want to forward our generic arguments to the base. Consider: - - class One - { - T one; - } - - class Two : One - { - } - - class Three : Two - { - } - - In this case, three is inheriting from Two, - so we want Two to inherit from One, - however, cecil will tell us that base of Two is One, - therefore we have to create the generic instance type of One ourselves - */ - if (typeRef.IsGenericInstance && baseType.IsGenericInstance) - { - var genericInstance = ((GenericInstanceType)baseType); - baseType = MakeGenericInstance(genericInstance.ElementType, genericInstance.GenericArguments, genericInstanceTypeMap); - } - - AddType(baseType, genericInstanceTypeMap); - } - } - - private TypeReference MakeGenericInstance(TypeReference genericClass, IEnumerable arguments, GenericInstanceTypeMap genericInstanceTypeMap) - { - var genericInstance = new GenericInstanceType(genericClass); - - foreach (var argument in arguments.Select(x => ResolveGenericInstanceType(x, genericInstanceTypeMap))) - { - genericInstance.GenericArguments.Add(argument); - } - - return genericInstance; - } - - private FieldInfo[] GetFields(TypeDefinition type, bool isGenericInstance, GenericInstanceTypeMap genericInstanceTypeMap) - { - var fields = new List(); - - foreach (FieldDefinition field in type.Fields) - { - var fieldInfo = GetFieldInfo(type, field, isGenericInstance, genericInstanceTypeMap); - - if (fieldInfo != null) - { - fields.Add(fieldInfo.Value); - } - } - - return fields.ToArray(); - } - - private static CustomAttribute GetFixedBufferAttribute(FieldDefinition fieldDefinition) - { - if (!fieldDefinition.HasCustomAttributes) - return null; - - return fieldDefinition.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.FixedBufferAttribute"); - } - - private static int GetFixedBufferLength(CustomAttribute fixedBufferAttribute) - { - return (Int32)fixedBufferAttribute.ConstructorArguments[1].Value; - } - - private static string GetFixedBufferTypename(CustomAttribute fixedBufferAttribute) - { - var typeRef = (TypeReference)fixedBufferAttribute.ConstructorArguments[0].Value; - return typeRef.Name; - } - - private FieldInfo? GetFieldInfo(TypeDefinition type, FieldDefinition field, bool isDeclaringTypeGenericInstance, - GenericInstanceTypeMap genericInstanceTypeMap) - { - if (!WillSerialize(field)) - return null; - - var ti = new FieldInfo(); - ti.name = field.Name; - - TypeReference fieldType; - - if (isDeclaringTypeGenericInstance) - { - fieldType = ResolveGenericInstanceType(field.FieldType, genericInstanceTypeMap); - } - else - { - fieldType = field.FieldType; - } - - ti.type = GetMonoEmbeddedFullTypeNameFor(fieldType); - ti.flags = FieldInfoFlags.None; - - var fixedBufferAttribute = GetFixedBufferAttribute(field); - - if (fixedBufferAttribute != null) - { - ti.flags |= FieldInfoFlags.FixedBuffer; - ti.fixedBufferLength = GetFixedBufferLength(fixedBufferAttribute); - ti.fixedBufferTypename = GetFixedBufferTypename(fixedBufferAttribute); - } - return ti; - } - - private bool WillSerialize(FieldDefinition field) - { - try - { - return UnitySerializationLogic.WillUnitySerialize(field, typeResolver); - } - catch (Exception ex) - { - UnityEngine.Debug.LogFormat("Field '{0}' from '{1}', exception {2}", field.FullName, field.Module.FileName, ex.Message); - // If assembly has unknown reference (for ex., see tests VariousPlugins, where Metro plugins are used), skip field - return false; - } - } - - public ClassInfo[] GatherClassInfo() - { - foreach (ModuleDefinition module in assembly_.Modules) - { - foreach (TypeDefinition type in module.Types) - { - // Skip compiler-generated class - if (type.Name == "") - continue; - - AddType(type, new Dictionary()); - } - } - return classes_.ToArray(); - } - } -} diff --git a/Editor/Mono/BuildPipeline/BuildFailedException.cs b/Editor/Mono/BuildPipeline/BuildFailedException.cs deleted file mode 100644 index 5af2f66087..0000000000 --- a/Editor/Mono/BuildPipeline/BuildFailedException.cs +++ /dev/null @@ -1,29 +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.Scripting; - -namespace UnityEditor.Build -{ - [RequiredByNativeCode] - public class BuildFailedException : Exception - { - public BuildFailedException(string message) : - base(message) - { - } - - public BuildFailedException(Exception innerException) : - base(null, innerException) - { - } - - [RequiredByNativeCode] - private Exception BuildFailedException_GetInnerException() - { - return InnerException; - } - } -} diff --git a/Editor/Mono/BuildPipeline/BuildVerifier.cs b/Editor/Mono/BuildPipeline/BuildVerifier.cs deleted file mode 100644 index ea74b4fbc5..0000000000 --- a/Editor/Mono/BuildPipeline/BuildVerifier.cs +++ /dev/null @@ -1,81 +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.Xml.XPath; -using System.Collections.Generic; -using System.IO; -using UnityEngine; -namespace UnityEditor -{ - /// - /// Class intented to verify if build will compile / work on specified target platform - /// Currently only managed references are verified - /// - internal class BuildVerifier - { - private Dictionary> m_UnsupportedAssemblies = null; - private static BuildVerifier ms_Inst = null; - - protected BuildVerifier() - { - m_UnsupportedAssemblies = new Dictionary>(); - - var configPath = Path.Combine(Path.Combine(EditorApplication.applicationContentsPath, "Resources"), "BuildVerification.xml"); - var doc = new XPathDocument(configPath); - var navigator = doc.CreateNavigator(); - navigator.MoveToFirstChild(); - - var it = navigator.SelectChildren("assembly", ""); - - while (it.MoveNext()) - { - string name = it.Current.GetAttribute("name", ""); - if (string.IsNullOrEmpty(name)) - throw new ApplicationException(string.Format("Failed to load {0}, name attribute is empty", configPath)); - - string platform = it.Current.GetAttribute("platform", ""); - if (string.IsNullOrEmpty(platform)) - platform = "*"; - - if (!m_UnsupportedAssemblies.ContainsKey(platform)) - m_UnsupportedAssemblies.Add(platform, new HashSet()); - - m_UnsupportedAssemblies[platform].Add(name); - } - } - - protected void VerifyBuildInternal(BuildTarget target, string managedDllFolder) - { - foreach (var file in Directory.GetFiles(managedDllFolder)) - { - if (file.EndsWith(".dll")) - { - var fname = Path.GetFileName(file); - if (!VerifyAssembly(target, fname)) - Debug.LogWarningFormat( - "{0} assembly is referenced by user code, but is not supported" + - " on {1} platform. Various failures might follow.", fname, target.ToString()); - } - } - } - - protected bool VerifyAssembly(BuildTarget target, string assembly) - { - if (m_UnsupportedAssemblies.ContainsKey("*") && m_UnsupportedAssemblies["*"].Contains(assembly) || - m_UnsupportedAssemblies.ContainsKey(target.ToString()) && m_UnsupportedAssemblies[target.ToString()].Contains(assembly)) - return false; - - return true; - } - - public static void VerifyBuild(BuildTarget target, string managedDllFolder) - { - if (ms_Inst == null) - ms_Inst = new BuildVerifier(); - - ms_Inst.VerifyBuildInternal(target, managedDllFolder); - } - } -} diff --git a/Editor/Mono/BuildPipeline/DesktopStandaloneUserBuildSettings.cs b/Editor/Mono/BuildPipeline/DesktopStandaloneUserBuildSettings.cs deleted file mode 100644 index a82ab677e2..0000000000 --- a/Editor/Mono/BuildPipeline/DesktopStandaloneUserBuildSettings.cs +++ /dev/null @@ -1,23 +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.IO; -using UnityEngine; -using UnityEditor; -using UnityEditorInternal; -using UnityEditor.Modules; -using System.Collections.Generic; -using System.Text; - -internal static class DesktopStandaloneUserBuildSettings -{ - internal static string PlatformName - { - get - { - return "Standalone"; - } - } -} diff --git a/Editor/Mono/BuildPipeline/Il2Cpp/ICompilerSettings.cs b/Editor/Mono/BuildPipeline/Il2Cpp/ICompilerSettings.cs deleted file mode 100644 index e550bf6c0d..0000000000 --- a/Editor/Mono/BuildPipeline/Il2Cpp/ICompilerSettings.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -interface ICompilerSettings -{ - string[] LibPaths { get; } - string CompilerPath { get; } - string LinkerPath { get; } - string MachineSpecification { get; } -} diff --git a/Editor/Mono/BuildPipeline/Il2Cpp/INativeCompiler.cs b/Editor/Mono/BuildPipeline/Il2Cpp/INativeCompiler.cs deleted file mode 100644 index a6501d074e..0000000000 --- a/Editor/Mono/BuildPipeline/Il2Cpp/INativeCompiler.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 - -using System.Collections.Generic; - -interface INativeCompiler -{ - void CompileDynamicLibrary(string outFile, IEnumerable sources, IEnumerable includePaths, IEnumerable libraries, IEnumerable libraryPaths); -} diff --git a/Editor/Mono/BuildPipeline/Il2Cpp/Il2CppNativeCodeBuilder.cs b/Editor/Mono/BuildPipeline/Il2Cpp/Il2CppNativeCodeBuilder.cs deleted file mode 100644 index 7baea1079d..0000000000 --- a/Editor/Mono/BuildPipeline/Il2Cpp/Il2CppNativeCodeBuilder.cs +++ /dev/null @@ -1,125 +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.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; - -namespace UnityEditorInternal -{ - public abstract class Il2CppNativeCodeBuilder - { - /// - /// Implement this property to tell IL2CPP about the platform for the C++ compiler. - /// This platform must be known in the Unity.IL2CPP.Builder code. - /// - public abstract string CompilerPlatform { get; } - - /// - /// Implement this property to tell IL2CPP about the architecture for the C++ compiler. - /// This architecture must be known in the Unity.IL2CPP.Builder code. - /// - public abstract string CompilerArchitecture { get; } - - /// - /// Provide any compiler flags IL2CPP should use in addition to the default ones. - /// The default value of this property is an empty string. - /// - public virtual string CompilerFlags - { - get { return string.Empty; } - } - - /// - /// Provide any linker flags IL2CPP should use in addition to the default ones. - /// The default value of this property is an empty string. - /// - public virtual string LinkerFlags - { - get { return string.Empty; } - } - - /// - /// IL2CPP should not try to set up the environment for the C++ compiler internally. Instead, it will - /// use the environment it is provided. If this is true, SetupEnvironment will be called. - /// The default value of this property is false. - /// - public virtual bool SetsUpEnvironment - { - get { return false; } - } - - /// - /// Provide a cache directory for IL2CPP to use to save build artifacts used for incremental builds. - /// If this does not exist, a full build will occur. - /// The default value of this property is an empty string, which disables incremental builds. - /// - public virtual string CacheDirectory - { - get { return string.Empty; } - } - - /// - /// Provide the path to a plugin - /// - public virtual string PluginPath - { - get { return string.Empty; } - } - - - public virtual IEnumerable AdditionalIl2CPPArguments - { - get { return new string[0]; } - } - - /// - /// If this property returns true the argument "--libil2cpp-static" will be used when calling il2cpp.exe - - /// - public virtual bool LinkLibIl2CppStatically - { - get { return true; } - } - - /// - /// Change the relative include paths into absolute paths that can be passed to the C++ compiler. - /// By default this method returns its input with each path relative to the current directory. - /// - /// The list of relative paths to convert - /// A list of full paths - public virtual IEnumerable ConvertIncludesToFullPaths(IEnumerable relativeIncludePaths) - { - var workingDirectory = Directory.GetCurrentDirectory(); - return relativeIncludePaths.Select(path => Path.Combine(workingDirectory, path)); - } - - /// - /// Change the relative path to the output file to an absolute path that can be passed to the C++ compiler. - /// By default this method returns its input relative to the current directory. - /// - /// The relative output file path to convert - /// The full output file path - public virtual string ConvertOutputFileToFullPath(string outputFileRelativePath) - { - return Path.Combine(Directory.GetCurrentDirectory(), outputFileRelativePath); - } - - public void SetupStartInfo(ProcessStartInfo startInfo) - { - if (SetsUpEnvironment) - SetupEnvironment(startInfo); - } - - /// - /// Override this method if SetsUpEnvironment is override to return true. This will allow - /// the ProcessStartInfo for IL2CPP to be modified. - /// - /// The ProcessStartInfo for IL2CPP - protected virtual void SetupEnvironment(ProcessStartInfo startInfo) - { - } - } -} diff --git a/Editor/Mono/BuildPipeline/PostProcessStandalonePlayer.cs b/Editor/Mono/BuildPipeline/PostProcessStandalonePlayer.cs deleted file mode 100644 index 14f87b7be7..0000000000 --- a/Editor/Mono/BuildPipeline/PostProcessStandalonePlayer.cs +++ /dev/null @@ -1,14 +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.Text; -using UnityEditor; -using UnityEditor.Modules; -using UnityEngine; - -internal class PostProcessStandalonePlayer -{ -} diff --git a/Editor/Mono/BuildPipeline/WinRT/WinRTUtils.cs b/Editor/Mono/BuildPipeline/WinRT/WinRTUtils.cs deleted file mode 100644 index ec796520e2..0000000000 --- a/Editor/Mono/BuildPipeline/WinRT/WinRTUtils.cs +++ /dev/null @@ -1,25 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Reflection; -using UnityEditorInternal; -using System; -using System.Threading; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using System.Text.RegularExpressions; -using Mono.Cecil; - -internal class WinRTUtils -{ - public static string GetProcessorArchitecture(BuildTarget target) - { - return "x86"; - } -} diff --git a/Editor/Mono/Camera/BuiltinBakedReflectionSystem.bindings.cs b/Editor/Mono/Camera/BuiltinBakedReflectionSystem.bindings.cs index 7928108d9b..c2e20ef94f 100644 --- a/Editor/Mono/Camera/BuiltinBakedReflectionSystem.bindings.cs +++ b/Editor/Mono/Camera/BuiltinBakedReflectionSystem.bindings.cs @@ -64,6 +64,14 @@ public void Clear() Internal_Clear(); } + public bool BakeAllReflectionProbes() + { + if (disposed) + throw new ObjectDisposedException("BuiltinBakedReflectionSystem"); + + return Internal_BakeAllReflectionProbes(); + } + public void Cancel() { // Cancel is empty on purpose @@ -120,5 +128,6 @@ void Internal_BuiltinBakedReflectionSystem_SetIsDone(bool isDone) extern void Internal_SynchronizeReflectionProbes(); extern void Internal_Clear(); extern void Internal_SetPtr(BuiltinBakedReflectionSystem ptr); + extern bool Internal_BakeAllReflectionProbes(); } } diff --git a/Editor/Mono/Camera/IScriptableBakedReflectionSystem.cs b/Editor/Mono/Camera/IScriptableBakedReflectionSystem.cs index bcb1c439d4..2557f60973 100644 --- a/Editor/Mono/Camera/IScriptableBakedReflectionSystem.cs +++ b/Editor/Mono/Camera/IScriptableBakedReflectionSystem.cs @@ -16,5 +16,6 @@ public interface IScriptableBakedReflectionSystem : IDisposable void SynchronizeReflectionProbes(); void Clear(); void Cancel(); + bool BakeAllReflectionProbes(); } } diff --git a/Editor/Mono/Camera/ScriptableBakedReflectionSystem.cs b/Editor/Mono/Camera/ScriptableBakedReflectionSystem.cs index 45f1f55623..416f7574a1 100644 --- a/Editor/Mono/Camera/ScriptableBakedReflectionSystem.cs +++ b/Editor/Mono/Camera/ScriptableBakedReflectionSystem.cs @@ -21,6 +21,7 @@ public virtual void Tick(SceneStateHash sceneStateHash, IScriptableBakedReflecti public virtual void SynchronizeReflectionProbes() {} public virtual void Clear() {} public virtual void Cancel() {} + public virtual bool BakeAllReflectionProbes() { return false; } protected virtual void Dispose(bool disposing) {} diff --git a/Editor/Mono/Camera/ScriptableBakedReflectionSystemWrapper.bindings.cs b/Editor/Mono/Camera/ScriptableBakedReflectionSystemWrapper.bindings.cs index e2c26a0746..96d7c7cdcc 100644 --- a/Editor/Mono/Camera/ScriptableBakedReflectionSystemWrapper.bindings.cs +++ b/Editor/Mono/Camera/ScriptableBakedReflectionSystemWrapper.bindings.cs @@ -118,6 +118,18 @@ void Internal_ScriptableBakedReflectionSystemWrapper_Cancel() implementation.Cancel(); } + [RequiredByNativeCode] + bool Internal_ScriptableBakedReflectionSystemWrapper_BakeAllReflectionProbes() + { + if (Disposed) + throw new ObjectDisposedException("ScriptableBakedReflectionSystemWrapper"); + + if (implementation != null) + return implementation.BakeAllReflectionProbes(); + + return false; + } + [StaticAccessor("ScriptableBakedReflectionSystem", StaticAccessorType.DoubleColon)] static extern void ScriptingEnterStage(IntPtr objPtr, int stage, string progressMessage, float progress); diff --git a/Editor/Mono/ChangeTrackerHandle.bindings.cs b/Editor/Mono/ChangeTrackerHandle.bindings.cs deleted file mode 100644 index b415a0b992..0000000000 --- a/Editor/Mono/ChangeTrackerHandle.bindings.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 System; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor -{ - [NativeHeader("Editor/Src/Utility/ChangeTracker.h")] - [RequiredByNativeCode] - internal struct ChangeTrackerHandle - { - IntPtr m_Handle; - - internal static ChangeTrackerHandle AcquireTracker(UnityEngine.Object obj) - { - if (obj == null) - throw new ArgumentNullException("Not a valid unity engine object"); - return new ChangeTrackerHandle() { m_Handle = Internal_AcquireTracker(obj) }; - } - - [FreeFunction("ChangeTrackerRegistry::AcquireTracker")] - private static extern IntPtr Internal_AcquireTracker(UnityEngine.Object o); - - internal void ReleaseTracker() - { - if (m_Handle == IntPtr.Zero) - throw new ArgumentNullException("Not a valid handle, has it been released already?"); - - Internal_ReleaseTracker(m_Handle); - m_Handle = IntPtr.Zero; - } - - [FreeFunction("ChangeTrackerRegistry::ReleaseTracker")] - private static extern void Internal_ReleaseTracker(IntPtr handle); - - // returns true if object changed since last poll - internal bool PollForChanges() - { - if (m_Handle == IntPtr.Zero) - throw new ArgumentNullException("Not a valid handle, has it been released already?"); - return Internal_PollChanges(m_Handle); - } - - [FreeFunction("ChangeTrackerRegistry::PollChanges")] - private static extern bool Internal_PollChanges(IntPtr handle); - - internal void ForceDirtyNextPoll() - { - if (m_Handle == IntPtr.Zero) - throw new ArgumentNullException("Not a valid handle, has it been released already?"); - Internal_ForceUpdate(m_Handle); - } - - [FreeFunction("ChangeTrackerRegistry::ForceUpdate")] - private static extern void Internal_ForceUpdate(IntPtr handle); - } -} diff --git a/Editor/Mono/CloudBuild/CloudBuild.cs b/Editor/Mono/CloudBuild/CloudBuild.cs deleted file mode 100644 index 191d3a8919..0000000000 --- a/Editor/Mono/CloudBuild/CloudBuild.cs +++ /dev/null @@ -1,182 +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.IO; -using System.Collections.Generic; -using System.Diagnostics; -using UnityEngine; -using UnityEditor; -using UnityEditor.Utils; -using UnityEditor.Web; -using UnityEditorInternal; -using UnityEditor.Connect; - -namespace UnityEditor.CloudBuild -{ - [InitializeOnLoad] - internal class CloudBuild - { - static CloudBuild() - { - JSProxyMgr.GetInstance().AddGlobalObject("unity/cloudbuild", new CloudBuild()); - } - - public Dictionary> GetScmCandidates() - { - Dictionary> candidates = new Dictionary>(); - - Dictionary git = DetectGit(); - if (git != null) - { - candidates.Add("git", git); - } - Dictionary mercurial = DetectMercurial(); - if (mercurial != null) - { - candidates.Add("mercurial", mercurial); - } - - Dictionary subversion = DetectSubversion(); - if (subversion != null) - { - candidates.Add("subversion", subversion); - } - - Dictionary perforce = DetectPerforce(); - if (perforce != null) - { - candidates.Add("perforce", perforce); - } - return candidates; - } - - private Dictionary DetectGit() - { - Dictionary gitSettings = new Dictionary(); - - string url = RunCommand("git", "config --get remote.origin.url"); - if (String.IsNullOrEmpty(url)) - { - return null; - } - gitSettings.Add("url", url); - gitSettings.Add("branch", RunCommand("git", "rev-parse --abbrev-ref HEAD")); - gitSettings.Add("root", RemoveProjectDirectory(RunCommand("git", "rev-parse --show-toplevel"))); - return gitSettings; - } - - private Dictionary DetectMercurial() - { - Dictionary mercurialSettings = new Dictionary(); - - string url = RunCommand("hg", "paths default"); - if (String.IsNullOrEmpty(url)) - { - return null; - } - mercurialSettings.Add("url", url); - mercurialSettings.Add("branch", RunCommand("hg", "branch")); - mercurialSettings.Add("root", RemoveProjectDirectory(RunCommand("hg", "root"))); - return mercurialSettings; - } - - private Dictionary DetectSubversion() - { - Dictionary subversionSettings = new Dictionary(); - - string info = RunCommand("svn", "info"); - if (info == null) - { - return null; - } - string[] lines = info.Split(Environment.NewLine.ToCharArray()); - foreach (var s in lines) - { - string[] parts = s.Split(new char[] {':'}, 2); - if (parts.Length == 2) - { - if (parts[0].Equals("Repository Root")) - { - subversionSettings.Add("url", parts[1].Trim()); - } - - if (parts[0].Equals("URL")) - { - subversionSettings.Add("branch", parts[1].Trim()); - } - - if (parts[0].Equals("Working Copy Root Path")) - { - subversionSettings.Add("root", RemoveProjectDirectory(parts[1].Trim())); - } - } - } - if (!subversionSettings.ContainsKey("url")) - { - return null; - } - return subversionSettings; - } - - private Dictionary DetectPerforce() - { - Dictionary perforceSettings = new Dictionary(); - - string url = Environment.GetEnvironmentVariable("P4PORT"); - if (String.IsNullOrEmpty(url)) - { - return null; - } - perforceSettings.Add("url", url); - - string client = Environment.GetEnvironmentVariable("P4CLIENT"); - if (!String.IsNullOrEmpty(client)) - { - perforceSettings.Add("workspace", client); - } - return perforceSettings; - } - - private String RunCommand(string command, string arguments) - { - try - { - ProcessStartInfo startInfo = new ProcessStartInfo(command); - startInfo.Arguments = arguments; - Program program = new Program(startInfo); - program.Start(); - program.WaitForExit(); - if (program.ExitCode < 0) - { - return null; - } - var sb = new System.Text.StringBuilder(); - foreach (var s in program.GetStandardOutput()) - { - sb.AppendLine(s); - } - return sb.ToString().TrimEnd(Environment.NewLine.ToCharArray()); - } - catch (System.ComponentModel.Win32Exception) - { - // Problem executing, most likely Executable not found in path on Windows systems - return null; - } - } - - private String RemoveProjectDirectory(string workingDirectory) - { - string currentDirectory = Directory.GetCurrentDirectory(); - - // handle windows command line clients returning *nix like paths - if (currentDirectory.StartsWith(workingDirectory.Replace('/', '\\'))) - { - workingDirectory = workingDirectory.Replace('/', '\\'); - } - currentDirectory = currentDirectory.Replace(workingDirectory, ""); - return currentDirectory.Trim(Path.DirectorySeparatorChar); - } - } -} diff --git a/Editor/Mono/Collab/Collab.bindings.cs b/Editor/Mono/Collab/Collab.bindings.cs index e2755d5759..253f72c7b9 100644 --- a/Editor/Mono/Collab/Collab.bindings.cs +++ b/Editor/Mono/Collab/Collab.bindings.cs @@ -206,12 +206,17 @@ public extern void TestClearSoftLockAsCollaborator(string projectGuid, string pr [NativeMethod(HasExplicitThis = true, ThrowsException = true, IsThreadSafe = true)] extern void SetChangesToPublishInternal(ChangeItem[] changes); + [NativeMethod(HasExplicitThis = true, ThrowsException = true, IsThreadSafe = true)] + extern Change[] GetSelectedChangesInternal(); + [NativeMethod(Name = "GetJobProgress", HasExplicitThis = true, ThrowsException = true)] extern bool GetJobProgressInternal([Out] ProgressInfo info, int jobId); [NativeMethod(HasExplicitThis = true, ThrowsException = true)] public extern void Publish(string comment, bool useSelectedAssets, bool confirmMatchesPrevious); + [NativeMethod(HasExplicitThis = true, ThrowsException = true, IsThreadSafe = true)] + public extern void ClearSelectedChangesToPublish(); [NativeMethod(HasExplicitThis = true, ThrowsException = true)] public extern SoftLock[] GetSoftLocks(string assetGuid); diff --git a/Editor/Mono/Collab/Collab.cs b/Editor/Mono/Collab/Collab.cs index 2ab706e9eb..5a3a96c851 100644 --- a/Editor/Mono/Collab/Collab.cs +++ b/Editor/Mono/Collab/Collab.cs @@ -365,10 +365,21 @@ public bool SetConflictsResolvedTheirs(string[] paths) public PublishInfo GetChangesToPublish() { Change[] changes = GetChangesToPublishInternal(); + bool isFiltered = false; + + if (SupportsAsyncChanges()) + { + changes = GetSelectedChangesInternal(); + if (Toolbar.isLastShowRequestPartial) + { + isFiltered = true; + } + } + return new PublishInfo() { changes = changes, - filter = false + filter = isFiltered }; } diff --git a/Editor/Mono/Collab/CollabRevisionsData.cs b/Editor/Mono/Collab/CollabRevisionsData.cs deleted file mode 100644 index 0c13f70010..0000000000 --- a/Editor/Mono/Collab/CollabRevisionsData.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.Runtime.InteropServices; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor.Collaboration -{ - // Keep internal and undocumented until we expose more functionality - //*undocumented - [StructLayout(LayoutKind.Sequential)] - [UsedByNativeCode] - internal struct RevisionsData - { - private int m_RevisionsInRepo; - private int m_RevisionOffset; - private int m_ReturnedRevisions; - private Revision[] m_Revisions; - - public int RevisionsInRepo {get { return m_RevisionsInRepo; }} - public int RevisionOffset {get { return m_RevisionOffset; }} - public int ReturnedRevisions {get { return m_ReturnedRevisions; }} - public Revision[] Revisions {get { return m_Revisions; }} - } -} diff --git a/Editor/Mono/Collab/Softlocks/SoftlockUIData.cs b/Editor/Mono/Collab/Softlocks/SoftlockUIData.cs deleted file mode 100644 index e0d8c1df20..0000000000 --- a/Editor/Mono/Collab/Softlocks/SoftlockUIData.cs +++ /dev/null @@ -1,207 +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.SceneManagement; -using UnityEditor.SceneManagement; -using UnityEditor.Web; - -namespace UnityEditor.Collaboration -{ - // Composes Softlock data into structures used by the UI. - internal static class SoftLockUIData - { - private static Dictionary s_ImageCache = new Dictionary(); - private static Dictionary s_ImageNameCache = new Dictionary(); - private const string kIconMipSuffix = " Icon"; - - public enum SectionEnum - { - None, - Inspector, - Scene, - ProjectBrowser - } - - #region General - - // Provides the names of all additional users editing the asset - // with the given 'assetGuid'. - // Defaults to an empty list. - public static List GetLocksNamesOnAsset(string assetGuid) - { - List softLocks = null; - List names = new List(); - - if (SoftLockData.TryGetLocksOnAssetGUID(assetGuid, out softLocks)) - { - foreach (SoftLock softLock in softLocks) - { - names.Add(softLock.displayName); - } - } - return names; - } - - #endregion - #region Scene - - // Provides the names of all additional users editing the scene. - // Defaults to an empty list. - public static List GetLocksNamesOnScene(Scene scene) - { - List names = GetLockNamesOnScenePath(scene.path); - return names; - } - - public static List GetLockNamesOnScenePath(string scenePath) - { - string assetGuid = AssetDatabase.AssetPathToGUID(scenePath); - List names = GetLocksNamesOnAsset(assetGuid); - return names; - } - - public static string GetSceneNameFromPath(string scenePath) - { - string name = ""; - if (null != scenePath) - { - name = scenePath; - } - return name; - } - - // Provides the names of all additional users editing each scene. - // Defaults to an empty list, and may contain empty sub-lists. - public static List> GetLockNamesOnScenes(List scenes) - { - List> namesByScene = new List>(); - - if (scenes == null) - { - return namesByScene; - } - - foreach (Scene scene in scenes) - { - List names = GetLocksNamesOnScene(scene); - namesByScene.Add(names); - } - return namesByScene; - } - - // For each iteration, returns the pair (scene name : list of other users' names). - public static IEnumerable>> GetLockNamesOnOpenScenes() - { - if (Collab.instance.IsCollabEnabledForCurrentProject()) - { - for (int sceneIndex = 0; sceneIndex < EditorSceneManager.sceneCount; sceneIndex++) - { - Scene scene = SceneManager.GetSceneAt(sceneIndex); - List names = GetLocksNamesOnScene(scene); - string sceneName = scene.name; - if (String.IsNullOrEmpty(sceneName)) - { - // Default for unnamed scenes. - sceneName = "Untitled"; - } - KeyValuePair> sceneData = new KeyValuePair>(sceneName, names); - yield return sceneData; - } - } - } - - public static int CountOfLocksOnOpenScenes() - { - int count = 0; - - foreach (KeyValuePair> sceneData in GetLockNamesOnOpenScenes()) - { - count += sceneData.Value.Count; - } - return count; - } - - #endregion - #region Game Object - - // The usernames of additional people editing the given 'objectWithGUID'. - // Defaults to an empty list. - public static List GetLockNamesOnObject(UnityEngine.Object objectWithGUID) - { - string assetGUID = null; - AssetAccess.TryGetAssetGUIDFromObject(objectWithGUID, out assetGUID); - List names = GetLocksNamesOnAsset(assetGUID); - return names; - } - - #endregion - #region Icons - - // The icon for the particular section in the editor. - // Defaults to null. - public static Texture GetIconForSection(SectionEnum section) - { - string iconName = IconNameForSection(section); - Texture texture = GetIconForName(iconName); - return texture; - } - - private static string IconNameForSection(SectionEnum section) - { - string iconName; - if (!s_ImageNameCache.TryGetValue(section, out iconName)) - { - switch (section) - { - case SectionEnum.Inspector: - case SectionEnum.Scene: - iconName = "SoftlockInline.png"; - break; - - case SectionEnum.ProjectBrowser: - iconName = String.Format("SoftlockProjectBrowser{0}", kIconMipSuffix); - break; - - default: - return null; - } - s_ImageNameCache.Add(section, iconName); - } - return iconName; - } - - private static Texture GetIconForName(string fileName) - { - if (String.IsNullOrEmpty(fileName)) - { - return null; - } - - Texture texture; - // Note: a previous texture may have been destroyed - // by the system on the c++ side. - if (!s_ImageCache.TryGetValue(fileName, out texture) || texture == null) - { - if (fileName.EndsWith(kIconMipSuffix)) - { - texture = EditorGUIUtility.FindTexture(fileName) as Texture; - } - else - { - texture = EditorGUIUtility.LoadIconRequired(fileName) as Texture; - } - s_ImageCache.Remove(fileName); - s_ImageCache.Add(fileName, texture); - } - return texture; - } - - #endregion - } -} - diff --git a/Editor/Mono/Commands/GOCreationCommands.cs b/Editor/Mono/Commands/GOCreationCommands.cs index bc37a4b193..17755458d3 100644 --- a/Editor/Mono/Commands/GOCreationCommands.cs +++ b/Editor/Mono/Commands/GOCreationCommands.cs @@ -52,7 +52,12 @@ static void CreateEmptyChild(MenuCommand menuCommand) { var parent = menuCommand.context as GameObject; if (parent == null) - parent = Selection.activeGameObject; + { + var activeGO = Selection.activeGameObject; + if (activeGO != null && !EditorUtility.IsPersistent(activeGO)) + parent = activeGO; + } + var go = ObjectFactory.CreateGameObject("GameObject"); Place(go, parent); } diff --git a/Editor/Mono/CompilationPipeline.bindings.cs b/Editor/Mono/CompilationPipeline.bindings.cs deleted file mode 100644 index c182bbadd5..0000000000 --- a/Editor/Mono/CompilationPipeline.bindings.cs +++ /dev/null @@ -1,17 +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.Bindings; - -namespace UnityEditor.Compilation -{ - [NativeHeader("Editor/Src/ScriptCompilation/ScriptCompilationPipeline.h")] - public static partial class CompilationPipeline - { - [FreeFunction] - extern internal static void ClearEditorCompilationErrors(); - [FreeFunction] - extern internal static void LogEditorCompilationError(string message, int instanceID); - } -} diff --git a/Editor/Mono/ComponentUtility.cs b/Editor/Mono/ComponentUtility.cs deleted file mode 100644 index 607c5b08f8..0000000000 --- a/Editor/Mono/ComponentUtility.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 UnityEngine; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace UnityEditorInternal -{ - public partial class ComponentUtility - { - static private bool CompareComponentOrderAndTypes(List srcComponents, List dstComponents) - { - if (srcComponents.Count != dstComponents.Count) - return false; - - for (int i = 0; i != srcComponents.Count; i++) - { - if (srcComponents[i].GetType() != dstComponents[i].GetType()) - return false; - } - - return true; - } - - private static void DestroyComponents(List components) - { - // Delete in reverse order (to avoid errors when RequireComponent is used) - for (int i = components.Count - 1; i >= 0; i--) - UnityEngine.Object.DestroyImmediate(components[i]); - } - - public delegate bool IsDesiredComponent(Component c); - - public static void DestroyComponentsMatching(GameObject dst, IsDesiredComponent componentFilter) - { - var dstComponents = new List(); - dst.GetComponents(dstComponents); - dstComponents.RemoveAll(x => !componentFilter(x)); - DestroyComponents(dstComponents); - } - - public static void ReplaceComponentsIfDifferent(GameObject src, GameObject dst, IsDesiredComponent componentFilter) - { - var srcComponents = new List(); - src.GetComponents(srcComponents); - srcComponents.RemoveAll(x => !componentFilter(x)); - - var dstComponents = new List(); - dst.GetComponents(dstComponents); - dstComponents.RemoveAll(x => !componentFilter(x)); - - // Generate components - if (!CompareComponentOrderAndTypes(srcComponents, dstComponents)) - { - DestroyComponents(dstComponents); - - // Add src components to dst - dstComponents.Clear(); - for (int i = 0; i != srcComponents.Count; i++) - { - Component com = dst.AddComponent(srcComponents[i].GetType()); - dstComponents.Add(com); - } - } - - // Copy Data to components - for (int i = 0; i != srcComponents.Count; i++) - UnityEditor.EditorUtility.CopySerializedIfDifferent(srcComponents[i], dstComponents[i]); - } - } -} diff --git a/Editor/Mono/ConsoleWindow.cs b/Editor/Mono/ConsoleWindow.cs index 12d7ac5db0..4cb9501d5d 100644 --- a/Editor/Mono/ConsoleWindow.cs +++ b/Editor/Mono/ConsoleWindow.cs @@ -627,6 +627,7 @@ void OnGUI() EditorGUIUtility.SetIconSize(new Vector2(rowHeight, rowHeight)); GUIContent tempContent = new GUIContent(); int id = GUIUtility.GetControlID(0); + int rowDoubleClicked = -1; /////@TODO: Make Frame selected work with ListViewState using (new GettingLogEntriesScope(m_ListView)) @@ -712,11 +713,16 @@ void OnGUI() if (openSelectedItem) { - LogEntries.RowGotDoubleClicked(selectedRow); - Event.current.Use(); + rowDoubleClicked = selectedRow; + e.Use(); } } + // Prevent dead locking in EditorMonoConsole by delaying callbacks (which can log to the console) until after LogEntries.EndGettingEntries() has been + // called (this releases the mutex in EditorMonoConsole so logging again is allowed). Fix for case 1081060. + if (rowDoubleClicked != -1) + LogEntries.RowGotDoubleClicked(rowDoubleClicked); + EditorGUIUtility.SetIconSize(Vector2.zero); // Display active text (We want word wrapped text with a vertical scrollbar) diff --git a/Editor/Mono/ContainerWindow.bindings.cs b/Editor/Mono/ContainerWindow.bindings.cs index 2c427c9ead..d070126ab3 100644 --- a/Editor/Mono/ContainerWindow.bindings.cs +++ b/Editor/Mono/ContainerWindow.bindings.cs @@ -12,7 +12,7 @@ internal enum ShowMode { // Show as a normal window with max, min & close buttons. NormalWindow = 0, - // Used for a popup menu and tooltip. On mac this means light shadow and no titlebar. + // Used for a popup menu. On mac this means light shadow and no titlebar. PopupMenu = 1, // Utility window - floats above the app. Disappears when app loses focus. Utility = 2, @@ -22,8 +22,8 @@ internal enum ShowMode MainWindow = 4, // Aux windows. The ones that close the moment you move the mouse out of them. AuxWindow = 5, - // Like PopupMenu, but allows keyboard focus (e.g. AddComponentWindow) - PopupMenuWithKeyboardFocus = 6 + // Like PopupMenu, but without keyboard focus + Tooltip = 6 } //[StaticAccessor("ContainerWindowBindings", StaticAccessorType.DoubleColon)] diff --git a/Editor/Mono/ContainerWindow.cs b/Editor/Mono/ContainerWindow.cs index dea9694434..c1a379d446 100644 --- a/Editor/Mono/ContainerWindow.cs +++ b/Editor/Mono/ContainerWindow.cs @@ -59,20 +59,31 @@ internal void __internalAwake() internal static bool IsPopup(ShowMode mode) { - return (ShowMode.PopupMenu == mode || ShowMode.PopupMenuWithKeyboardFocus == mode); + return (ShowMode.PopupMenu == mode); } internal bool isPopup { get { return IsPopup((ShowMode)m_ShowMode); } } internal void ShowPopup() { - m_ShowMode = (int)ShowMode.PopupMenu; + ShowPopupWithMode(ShowMode.PopupMenu); + } + + internal void ShowTooltip() + { + ShowPopupWithMode(ShowMode.Tooltip); + } + + internal void ShowPopupWithMode(ShowMode mode) + { + m_ShowMode = (int)mode; Internal_Show(m_PixelRect, m_ShowMode, m_MinSize, m_MaxSize); if (m_RootView) m_RootView.SetWindowRecurse(this); Internal_SetTitle(m_Title); Save(); - Internal_BringLiveAfterCreation(false, false); + // only set focus iff mode is a popupMenu. + Internal_BringLiveAfterCreation(false, mode == ShowMode.PopupMenu); } static Color skinBackgroundColor @@ -84,7 +95,7 @@ static Color skinBackgroundColor } // Show the editor window. - public void Show(ShowMode showMode, bool loadPosition, bool displayImmediately) + public void Show(ShowMode showMode, bool loadPosition, bool displayImmediately, bool setFocus) { if (showMode == ShowMode.AuxWindow) showMode = ShowMode.Utility; @@ -107,7 +118,7 @@ public void Show(ShowMode showMode, bool loadPosition, bool displayImmediately) SetBackgroundColor(skinBackgroundColor); - Internal_BringLiveAfterCreation(displayImmediately, true); + Internal_BringLiveAfterCreation(displayImmediately, setFocus); // Window could be killed by now in user callbacks... if (!this) diff --git a/Editor/Mono/CustomEditorAttributes.cs b/Editor/Mono/CustomEditorAttributes.cs deleted file mode 100644 index b57a830a1e..0000000000 --- a/Editor/Mono/CustomEditorAttributes.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.Collections.Generic; -using System.Linq; -using UnityEngine; -using System; -using System.Reflection; -using UnityEngine.Rendering; - -namespace UnityEditor -{ - /// Remap Viewed type to inspector type - internal class CustomEditorAttributes - { - private static readonly Dictionary> kSCustomEditors = new Dictionary>(); - private static readonly Dictionary> kSCustomMultiEditors = new Dictionary>(); - private static bool s_Initialized; - - class MonoEditorType - { - public Type m_InspectedType; - public Type m_InspectorType; - public Type m_RenderPipelineType; - public bool m_EditorForChildClasses; - public bool m_IsFallback; - } - - internal static Type FindCustomEditorType(UnityEngine.Object o, bool multiEdit) - { - return FindCustomEditorTypeByType(o.GetType(), multiEdit); - } - - private static List s_SearchCache = new List(); - internal static Type FindCustomEditorTypeByType(Type type, bool multiEdit) - { - if (!s_Initialized) - { - var editorAssemblies = EditorAssemblies.loadedAssemblies; - for (int i = editorAssemblies.Length - 1; i >= 0; i--) - Rebuild(editorAssemblies[i]); - - s_Initialized = true; - } - - if (type == null) - return null; - - var editors = multiEdit ? kSCustomMultiEditors : kSCustomEditors; - for (int pass = 0; pass < 2; ++pass) - { - for (Type inspected = type; inspected != null; inspected = inspected.BaseType) - { - List foundEditors; - if (!editors.TryGetValue(inspected, out foundEditors)) - { - if (!inspected.IsGenericType) - continue; - - inspected = inspected.GetGenericTypeDefinition(); - - if (!editors.TryGetValue(inspected, out foundEditors)) - continue; - } - - s_SearchCache.Clear(); - foreach (var result in foundEditors) - { - if (!IsAppropriateEditor(result, inspected, type != inspected, pass == 1)) - continue; - - s_SearchCache.Add(result); - } - - Type toUse = null; - - // we have a render pipeline... - // we need to select the one with the correct RP asset - if (GraphicsSettings.renderPipelineAsset != null) - { - var rpType = GraphicsSettings.renderPipelineAsset.GetType(); - foreach (var editor in s_SearchCache) - { - if (editor.m_RenderPipelineType == rpType) - { - toUse = editor.m_InspectorType; - break; - } - } - } - - // no RP, fallback! - if (toUse == null) - { - foreach (var editor in s_SearchCache) - { - if (editor.m_RenderPipelineType == null) - { - toUse = editor.m_InspectorType; - break; - } - } - } - - s_SearchCache.Clear(); - if (toUse != null) - return toUse; - } - } - return null; - } - - private static bool IsAppropriateEditor(MonoEditorType editor, Type parentClass, bool isChildClass, bool isFallback) - { - if (isChildClass && !editor.m_EditorForChildClasses) - // skip if it's a child class and this editor doesn't want to match on children - return false; - if (isFallback != editor.m_IsFallback) - return false; - - return parentClass == editor.m_InspectedType || - (parentClass.IsGenericType && parentClass.GetGenericTypeDefinition() == editor.m_InspectedType); - } - - internal static void Rebuild(Assembly assembly) - { - Type[] types = AssemblyHelper.GetTypesFromAssembly(assembly); - foreach (var type in types) - { - object[] attrs = type.GetCustomAttributes(typeof(CustomEditor), false); - - foreach (CustomEditor inspectAttr in attrs) - { - var t = new MonoEditorType(); - if (inspectAttr.m_InspectedType == null) - Debug.Log("Can't load custom inspector " + type.Name + " because the inspected type is null."); - else if (!type.IsSubclassOf(typeof(Editor))) - { - // Suppress a warning on TweakMode, we did this bad in the default project folder - // and it's going to be too hard for customers to figure out how to fix it and also quite pointless. - if (type.FullName == "TweakMode" && type.IsEnum && - inspectAttr.m_InspectedType.FullName == "BloomAndFlares") - continue; - - Debug.LogWarning( - type.Name + - " uses the CustomEditor attribute but does not inherit from Editor.\nYou must inherit from Editor. See the Editor class script documentation."); - } - else - { - t.m_InspectedType = inspectAttr.m_InspectedType; - t.m_InspectorType = type; - t.m_EditorForChildClasses = inspectAttr.m_EditorForChildClasses; - t.m_IsFallback = inspectAttr.isFallback; - var attr = inspectAttr as CustomEditorForRenderPipelineAttribute; - if (attr != null) - t.m_RenderPipelineType = attr.renderPipelineType; - - List editors; - if (!kSCustomEditors.TryGetValue(inspectAttr.m_InspectedType, out editors)) - { - editors = new List(); - kSCustomEditors[inspectAttr.m_InspectedType] = editors; - } - editors.Add(t); - - if (type.GetCustomAttributes(typeof(CanEditMultipleObjects), false).Length > 0) - { - List multiEditors; - if (!kSCustomMultiEditors.TryGetValue(inspectAttr.m_InspectedType, out multiEditors)) - { - multiEditors = new List(); - kSCustomMultiEditors[inspectAttr.m_InspectedType] = multiEditors; - } - multiEditors.Add(t); - } - } - } - } - } - } -} diff --git a/Editor/Mono/DisplayUtility.cs b/Editor/Mono/DisplayUtility.cs deleted file mode 100644 index 66a71687f4..0000000000 --- a/Editor/Mono/DisplayUtility.cs +++ /dev/null @@ -1,44 +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 UnityEditor; -using System; -using System.Collections; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace UnityEditor -{ - internal class DisplayUtility - { - static string s_DisplayStr = "Display {0}"; - private static GUIContent[] s_GenericDisplayNames = - { - EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 1)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 2)), - EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 3)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 4)), - EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 5)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 6)), - EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 7)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 8)) - }; - - private static readonly int[] s_DisplayIndices = { 0, 1, 2, 3, 4, 5, 6, 7 }; - - public static GUIContent[] GetGenericDisplayNames() - { - return s_GenericDisplayNames; - } - - public static int[] GetDisplayIndices() - { - return s_DisplayIndices; - } - - public static GUIContent[] GetDisplayNames() - { - GUIContent[] platformDisplayNames = Modules.ModuleManager.GetDisplayNames(EditorUserBuildSettings.activeBuildTarget.ToString()); - return platformDisplayNames != null ? platformDisplayNames : s_GenericDisplayNames; - } - } -} diff --git a/Editor/Mono/DrivenPropertyManagerInternal.bindings.cs b/Editor/Mono/DrivenPropertyManagerInternal.bindings.cs deleted file mode 100644 index 19059a6ed5..0000000000 --- a/Editor/Mono/DrivenPropertyManagerInternal.bindings.cs +++ /dev/null @@ -1,23 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEngine; -using UnityEngine.Bindings; - -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - [NativeHeader("Editor/Src/DrivenPropertyManagerInternal.bindings.h")] - [StaticAccessor("DrivenPropertyManagerInternal", StaticAccessorType.DoubleColon)] - internal class DrivenPropertyManagerInternal - { - extern public static bool IsDriven(Object target, string propertyPath); - extern public static bool IsDriving(Object driver, Object target, string propertyPath); - } -} diff --git a/Editor/Mono/DrivenRectTransformUndo.cs b/Editor/Mono/DrivenRectTransformUndo.cs deleted file mode 100644 index 816771f88a..0000000000 --- a/Editor/Mono/DrivenRectTransformUndo.cs +++ /dev/null @@ -1,25 +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; - -namespace UnityEditor -{ - [InitializeOnLoad] - internal class DrivenRectTransformUndo - { - // Static constructor - static DrivenRectTransformUndo() - { - Undo.willFlushUndoRecord += ForceUpdateCanvases; - // After undo or redo performed, the 'driven values' & 'driven properties mask' need to be updated. - Undo.undoRedoPerformed += ForceUpdateCanvases; - } - - static void ForceUpdateCanvases() - { - Canvas.ForceUpdateCanvases(); - } - } -} diff --git a/Editor/Mono/DropInfo.cs b/Editor/Mono/DropInfo.cs deleted file mode 100644 index 71d061b94f..0000000000 --- a/Editor/Mono/DropInfo.cs +++ /dev/null @@ -1,38 +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 UnityEditor; - -namespace UnityEditor -{ - internal class DropInfo - { - internal enum Type - { - // The window will be inserted as a tab into dropArea - Tab = 0, - // The window will be a new pane (inside a scrollView) - Pane = 1, - // A new window should be created. - Window - } - - public DropInfo(IDropArea source) - { - dropArea = source; - } - - // Who claimed the drop? - public IDropArea dropArea; - - // Extra data for the recipient to communicate between DragOVer and PerformDrop - public object userData = null; - - // Which type of dropzone are we looking for? - public Type type = Type.Window; - // Where should the preview end up on screen. - public Rect rect; - } -} diff --git a/Editor/Mono/EditorApplication.cs b/Editor/Mono/EditorApplication.cs index ef237e355f..9d941b3959 100644 --- a/Editor/Mono/EditorApplication.cs +++ b/Editor/Mono/EditorApplication.cs @@ -187,6 +187,11 @@ public static void DirtyHierarchyWindowSorting() // Global key up/down event that was not handled by anyone internal static CallbackFunction globalEventHandler; + // Returns true when the pressed keys are defined in the Trigger + internal static Func doPressedKeysTriggerAnyShortcut; + + internal static event Action focusChanged; + // Windows were reordered internal static CallbackFunction windowsReordered; @@ -313,6 +318,14 @@ static void Internal_CallWindowsReordered() windowsReordered(); } + [RequiredByNativeCode] + static bool DoPressedKeysTriggerAnyShortcutHandler() + { + if (doPressedKeysTriggerAnyShortcut != null) + return doPressedKeysTriggerAnyShortcut(); + return false; + } + [RequiredByNativeCode] static void Internal_CallGlobalEventHandler() { @@ -324,5 +337,11 @@ static void Internal_CallGlobalEventHandler() Event.current = null; } + + [RequiredByNativeCode] + static void Internal_FocusChanged(bool isFocused) + { + focusChanged?.Invoke(isFocused); + } } } diff --git a/Editor/Mono/EditorApplication.deprecated.cs b/Editor/Mono/EditorApplication.deprecated.cs deleted file mode 100644 index d9b2c2184a..0000000000 --- a/Editor/Mono/EditorApplication.deprecated.cs +++ /dev/null @@ -1,124 +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 UnityEngine.SceneManagement; -using UnityEditor.SceneManagement; -using UnityEngine; - -namespace UnityEditor -{ - public sealed partial class EditorApplication - { - [Obsolete("Use EditorSceneManager.NewScene (NewSceneSetup.DefaultGameObjects)")] - public static void NewScene() - { - EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects); - } - - [Obsolete("Use EditorSceneManager.NewScene (NewSceneSetup.EmptyScene)")] - public static void NewEmptyScene() - { - EditorSceneManager.NewScene(NewSceneSetup.EmptyScene); - } - - // Opens the scene at /path/. - [Obsolete("Use EditorSceneManager.OpenScene")] - public static bool OpenScene(string path) - { - // Check that we're not in play mode first before opening the scene. - if (!isPlaying) - { - Scene scene = EditorSceneManager.OpenScene(path); - return scene.IsValid(); - } - else - { - throw new InvalidOperationException( - "EditorApplication.OpenScene() cannot be called when in the Unity Editor is in play mode."); - } - } - - [Obsolete("Use EditorSceneManager.OpenScene")] - public static void OpenSceneAdditive(string path) - { - // Case 712517: - // Behaviour change introduced in 5.3 - // Previously we allowed OpenSceneAdditive to be called during playmode. - // This is no longer allowed, if it happens we exit playmode which is - // consistent with EditorSceneManager.OpenScene(path, OpenSceneMode.Additive) - - if (Application.isPlaying) - { - Debug.LogWarning("Exiting playmode.\n" + - "OpenSceneAdditive was called at a point where there was no active scene.\n" + - "This usually means it was called in a PostprocessScene function during scene loading or it was called during playmode.\n" + - "This is no longer allowed. Use SceneManager.LoadScene to load scenes at runtime or in playmode."); - } - - Scene srcScene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive); - Scene dstScene = EditorSceneManager.GetActiveScene(); - SceneManager.MergeScenes(srcScene, dstScene); - } - - [Obsolete("Use EditorSceneManager.SaveScene")] - public static bool SaveScene() - { - return EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), "", false); - } - - [Obsolete("Use EditorSceneManager.SaveScene")] - public static bool SaveScene(string path) - { - return EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), path, false); - } - - [Obsolete("Use EditorSceneManager.SaveScene")] - public static bool SaveScene(string path, bool saveAsCopy) - { - return EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), path, saveAsCopy); - } - - [Obsolete("Use EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo")] - public static bool SaveCurrentSceneIfUserWantsTo() - { - return EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo(); - } - - [Obsolete("This function is internal and no longer supported")] - static internal bool SaveCurrentSceneIfUserWantsToForce() - { - return false; - } - - [Obsolete("Use EditorSceneManager.MarkSceneDirty or EditorSceneManager.MarkAllScenesDirty")] - public static void MarkSceneDirty() - { - EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene()); - } - - [Obsolete("Use Scene.isDirty instead. Use EditorSceneManager.GetScene API to get each open scene")] - public static bool isSceneDirty - { - get { return EditorSceneManager.GetActiveScene().isDirty; } - } - - [Obsolete("Use EditorSceneManager to see which scenes are currently loaded")] - public static string currentScene - { - get - { - Scene scene = EditorSceneManager.GetActiveScene(); - if (scene.IsValid()) - return scene.path; - - return ""; - } - set - { - } - } - } -} diff --git a/Editor/Mono/EditorAssemblies.bindings.cs b/Editor/Mono/EditorAssemblies.bindings.cs deleted file mode 100644 index 36f6892b94..0000000000 --- a/Editor/Mono/EditorAssemblies.bindings.cs +++ /dev/null @@ -1,54 +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 System.Reflection; -using UnityEngine.Bindings; - -namespace UnityEditor -{ - [NativeHeader("Runtime/Mono/MonoAttributeHelpers.h")] - static partial class EditorAssemblies - { - const BindingFlags k_DefaultMethodBindingFlags = - BindingFlags.Public - | BindingFlags.NonPublic - | BindingFlags.Instance - | BindingFlags.Static; - - internal static IEnumerable GetAllMethodsWithAttribute(BindingFlags bindingFlags = k_DefaultMethodBindingFlags) - where T : Attribute - { - return Internal_GetAllMethodsWithAttribute(typeof(T), bindingFlags).Cast(); - } - - [FreeFunction(Name = "GetAllMethodsWithAttribute")] - extern static object[] Internal_GetAllMethodsWithAttribute(Type attrType, BindingFlags staticness); - - internal static IEnumerable GetAllTypesWithAttribute() where T : Attribute - { - return Internal_GetAllTypesWithAttribute(typeof(T)); - } - - [FreeFunction(Name = "GetAllTypesWithAttribute")] - extern static Type[] Internal_GetAllTypesWithAttribute(Type attrType); - - internal static IEnumerable GetAllTypesWithInterface() where T : class - { - return GetAllTypesWithInterface(typeof(T)); - } - - private static IEnumerable GetAllTypesWithInterface(Type interfaceType) - { - if (!interfaceType.IsInterface) - throw new ArgumentException(string.Format("Specified type {0} is not an interface.", interfaceType), nameof(interfaceType)); - return Internal_GetAllTypesWithInterface(interfaceType); - } - - [FreeFunction(Name = "GetAllTypesWithInterface")] - extern static Type[] Internal_GetAllTypesWithInterface(Type interfaceType); - } -} diff --git a/Editor/Mono/EditorGUI.cs b/Editor/Mono/EditorGUI.cs index 6b63726c98..8fad8a4c1f 100644 --- a/Editor/Mono/EditorGUI.cs +++ b/Editor/Mono/EditorGUI.cs @@ -18,6 +18,7 @@ using UnityEditor.Build; using UnityEditor.StyleSheets; using UnityEngine.Internal; +using UnityEngine.Rendering; using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; namespace UnityEditor @@ -1050,6 +1051,7 @@ internal static string DoTextField(RecycledTextEditor editor, int id, Rect posit // Note, OS X send characters for the following keys that we need to eat: // ASCII 25: "End Of Medium" on pressing shift tab // ASCII 27: "Escape" on pressing ESC + nonPrintableTab = true; } else if (editor.IsEditingControl(id)) { @@ -2534,7 +2536,7 @@ private static float DoSlider( if (sliderBackground != null && Event.current.type == EventType.Repaint) { var bgRect = sliderStyle.overflow.Add(sliderStyle.padding.Remove(sliderRect)); - Graphics.DrawTexture(bgRect, sliderBackground, new Rect(.5f / sliderBackground.width, .5f / sliderBackground.height, 1 - 1f / sliderBackground.width, 1 - 1f / sliderBackground.height), 0, 0, 0, 0, Color.grey); + Graphics.DrawTexture(bgRect, sliderBackground, new Rect(.5f / sliderBackground.width, .5f / sliderBackground.height, 1 - 1f / sliderBackground.width, 1 - 1f / sliderBackground.height), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f)); } newSliderValue = GUI.Slider(sliderRect, newSliderValue, 0, remapLeft, remapRight, sliderStyle, showMixedValue ? "SliderMixed" : thumbStyle, true, sliderId); @@ -4337,6 +4339,14 @@ private static Color DoColorField(Rect position, int id, Color value, bool showE break; case EventType.ExecuteCommand: + + // Cancel EyeDropper if we change focus. + if (showEyedropper && Event.current.commandName == EventCommandNames.NewKeyboardFocus) + { + EyeDropper.End(); + s_ColorPickID = 0; + } + // when ColorPicker sends an event back to this control's GUIView, it someties retains keyboardControl if (GUIUtility.keyboardControl == id || ColorPicker.originalKeyboardControl == id) { @@ -5639,11 +5649,11 @@ internal static void ShowRepaints() // Draws the alpha channel of a texture within a rectangle. internal static void DrawTextureAlphaInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel) { - DrawPreviewTextureInternal(position, image, alphaMaterial, scaleMode, imageAspect, mipLevel); + DrawPreviewTextureInternal(position, image, alphaMaterial, scaleMode, imageAspect, mipLevel, ColorWriteMask.All); } // Draws texture transparently using the alpha channel. - internal static void DrawTextureTransparentInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel) + internal static void DrawTextureTransparentInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel, ColorWriteMask colorWriteMask) { if (imageAspect == 0f && image == null) { @@ -5656,7 +5666,7 @@ internal static void DrawTextureTransparentInternal(Rect position, Texture image DrawTransparencyCheckerTexture(position, scaleMode, imageAspect); if (image != null) - DrawPreviewTexture(position, image, transparentMaterial, scaleMode, imageAspect, mipLevel); + DrawPreviewTexture(position, image, transparentMaterial, scaleMode, imageAspect, mipLevel, colorWriteMask); } internal static void DrawTransparencyCheckerTexture(Rect position, ScaleMode scaleMode, float imageAspect) @@ -5678,15 +5688,27 @@ internal static void DrawTransparencyCheckerTexture(Rect position, ScaleMode sca } // Draws the texture within a rectangle. - internal static void DrawPreviewTextureInternal(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect, float mipLevel) + internal static void DrawPreviewTextureInternal(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect, float mipLevel, ColorWriteMask colorWriteMask) { if (Event.current.type == EventType.Repaint) { if (imageAspect == 0) imageAspect = image.width / (float)image.height; + Color colorMask = new Color(1, 1, 1, 1); + + if ((colorWriteMask & ColorWriteMask.Red) == 0) + colorMask.r = 0; + if ((colorWriteMask & ColorWriteMask.Green) == 0) + colorMask.g = 0; + if ((colorWriteMask & ColorWriteMask.Blue) == 0) + colorMask.b = 0; + if ((colorWriteMask & ColorWriteMask.Alpha) == 0) + colorMask.a = 0; + if (mat == null) mat = GetMaterialForSpecialTexture(image, colorMaterial); + mat.SetColor("_ColorMask", colorMask); mat.SetFloat("_Mip", mipLevel); RenderTexture rt = image as RenderTexture; @@ -6343,9 +6365,9 @@ public static void DrawTextureAlpha(Rect position, Texture image, ScaleMode scal } // Draws texture transparently using the alpha channel. - public static void DrawTextureTransparent(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel) + public static void DrawTextureTransparent(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel, [DefaultValue("ColorWriteMask.All")] ColorWriteMask colorWriteMask) { - DrawTextureTransparentInternal(position, image, scaleMode, imageAspect, mipLevel); + DrawTextureTransparentInternal(position, image, scaleMode, imageAspect, mipLevel, colorWriteMask); } [ExcludeFromDocs] @@ -6360,16 +6382,35 @@ public static void DrawTextureTransparent(Rect position, Texture image) DrawTextureTransparent(position, image, ScaleMode.StretchToFill, 0); } + [ExcludeFromDocs] public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) { - DrawTextureTransparentInternal(position, image, scaleMode, imageAspect, -1); + DrawTextureTransparent(position, image, scaleMode, imageAspect, -1); + } + + [ExcludeFromDocs] + public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel) + { + DrawTextureTransparent(position, image, scaleMode, imageAspect, mipLevel, ColorWriteMask.All); } // Draws the texture within a rectangle. public static void DrawPreviewTexture(Rect position, Texture image, [DefaultValue("null")] Material mat, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, - [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel) + [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel, [DefaultValue("ColorWriteMask.All")] ColorWriteMask colorWriteMask) { - DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect, mipLevel); + DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect, mipLevel, colorWriteMask); + } + + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect, float mipLevel) + { + DrawPreviewTexture(position, image, mat, scaleMode, imageAspect, mipLevel, ColorWriteMask.All); + } + + [ExcludeFromDocs] + public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect) + { + DrawPreviewTexture(position, image, mat, scaleMode, imageAspect, -1); } [ExcludeFromDocs] @@ -6390,12 +6431,6 @@ public static void DrawPreviewTexture(Rect position, Texture image) DrawPreviewTexture(position, image, null, ScaleMode.StretchToFill, 0); } - [ExcludeFromDocs] - public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect) - { - DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect, -1); - } - [ExcludeFromDocs] public static void LabelField(Rect position, string label) { diff --git a/Editor/Mono/EditorHandles/BoundsHandle/BoxBoundsHandle.cs b/Editor/Mono/EditorHandles/BoundsHandle/BoxBoundsHandle.cs deleted file mode 100644 index 75a24010e1..0000000000 --- a/Editor/Mono/EditorHandles/BoundsHandle/BoxBoundsHandle.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 System; -using UnityEngine; - -namespace UnityEditor.IMGUI.Controls -{ - public class BoxBoundsHandle : PrimitiveBoundsHandle - { - [Obsolete("Use parameterless constructor instead.")] - public BoxBoundsHandle(int controlIDHint) : base(controlIDHint) {} - - public BoxBoundsHandle() : base() {} - - public UnityEngine.Vector3 size { get { return GetSize(); } set { SetSize(value); } } - - protected override void DrawWireframe() - { - Handles.DrawWireCube(center, size); - } - } -} diff --git a/Editor/Mono/EditorHandles/BoundsHandle/CapsuleBoundsHandle.cs b/Editor/Mono/EditorHandles/BoundsHandle/CapsuleBoundsHandle.cs deleted file mode 100644 index 116b4fac3b..0000000000 --- a/Editor/Mono/EditorHandles/BoundsHandle/CapsuleBoundsHandle.cs +++ /dev/null @@ -1,203 +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.IMGUI.Controls -{ - public class CapsuleBoundsHandle : PrimitiveBoundsHandle - { - public enum HeightAxis { X, Y, Z } - - private const int k_DirectionX = 0; - private const int k_DirectionY = 1; - private const int k_DirectionZ = 2; - - private static readonly Vector3[] s_HeightAxes = new[] { Vector3.right, Vector3.up, Vector3.forward }; - private static readonly int[] s_NextAxis = new[] { 1, 2, 0 }; - - public HeightAxis heightAxis - { - get { return (HeightAxis)m_HeightAxis; } - set - { - int newValue = (int)value; - if (m_HeightAxis == newValue) - return; - Vector3 size = Vector3.one * radius * 2f; - size[newValue] = GetSize()[m_HeightAxis]; - m_HeightAxis = newValue; - SetSize(size); - } - } - private int m_HeightAxis = k_DirectionY; - - public float height - { - get - { - // zero out height if height axis is disabled - return !IsAxisEnabled(m_HeightAxis) ? 0f : Mathf.Max(GetSize()[m_HeightAxis], 2f * radius); - } - set - { - // height cannot be less than diameter - value = Mathf.Max(Mathf.Abs(value), 2f * radius); - if (height == value) - return; - Vector3 size = GetSize(); - size[m_HeightAxis] = value; - SetSize(size); - } - } - - public float radius - { - get - { - int radiusAxis; - // return 0 if only enabled axis is a single radius axis - if (GetRadiusAxis(out radiusAxis) || IsAxisEnabled(m_HeightAxis)) - return 0.5f * GetSize()[radiusAxis]; - else - return 0f; - } - set - { - Vector3 size = GetSize(); - float diameter = 2f * value; - // height cannot be less than diameter - for (int axis = 0; axis < 3; ++axis) - size[axis] = axis == m_HeightAxis ? Mathf.Max(size[axis], diameter) : diameter; - SetSize(size); - } - } - - [Obsolete("Use parameterless constructor instead.")] - public CapsuleBoundsHandle(int controlIDHint) : base(controlIDHint) {} - - public CapsuleBoundsHandle() : base() {} - - protected override void DrawWireframe() - { - HeightAxis radAxis1 = HeightAxis.Y; - HeightAxis radAxis2 = HeightAxis.Z; - switch (heightAxis) - { - case HeightAxis.Y: - radAxis1 = HeightAxis.Z; - radAxis2 = HeightAxis.X; - break; - case HeightAxis.Z: - radAxis1 = HeightAxis.X; - radAxis2 = HeightAxis.Y; - break; - } - bool doHeightAxis = IsAxisEnabled((int)heightAxis); - bool doRadiusAxis1 = IsAxisEnabled((int)radAxis1); - bool doRadiusAxis2 = IsAxisEnabled((int)radAxis2); - - Vector3 hgtAx = s_HeightAxes[m_HeightAxis]; - Vector3 radAx1 = s_HeightAxes[s_NextAxis[m_HeightAxis]]; - Vector3 radAx2 = s_HeightAxes[s_NextAxis[s_NextAxis[m_HeightAxis]]]; - float rad = radius; - float hgt = height; - Vector3 top = center + hgtAx * (hgt * 0.5f - rad); - Vector3 bottom = center - hgtAx * (hgt * 0.5f - rad); - - // draw caps and connecting lines for each enabled axis if height axis is enabled - if (doHeightAxis) - { - if (doRadiusAxis2) - { - Handles.DrawWireArc(top, radAx1, radAx2, 180f, rad); - Handles.DrawWireArc(bottom, radAx1, radAx2, -180f, rad); - Handles.DrawLine(top + radAx2 * rad, bottom + radAx2 * rad); - Handles.DrawLine(top - radAx2 * rad, bottom - radAx2 * rad); - } - if (doRadiusAxis1) - { - Handles.DrawWireArc(top, radAx2, radAx1, -180f, rad); - Handles.DrawWireArc(bottom, radAx2, radAx1, 180f, rad); - Handles.DrawLine(top + radAx1 * rad, bottom + radAx1 * rad); - Handles.DrawLine(top - radAx1 * rad, bottom - radAx1 * rad); - } - } - - // do cross-section if both radius axes are enabled - if (doRadiusAxis1 && doRadiusAxis2) - { - Handles.DrawWireArc(top, hgtAx, radAx1, 360f, rad); - Handles.DrawWireArc(bottom, hgtAx, radAx1, -360f, rad); - } - } - - protected override Bounds OnHandleChanged(HandleDirection handle, Bounds boundsOnClick, Bounds newBounds) - { - int changedAxis = k_DirectionX; - switch (handle) - { - case HandleDirection.NegativeY: - case HandleDirection.PositiveY: - changedAxis = k_DirectionY; - break; - case HandleDirection.NegativeZ: - case HandleDirection.PositiveZ: - changedAxis = k_DirectionZ; - break; - } - - Vector3 upperBound = newBounds.max; - Vector3 lowerBound = newBounds.min; - - // ensure height cannot be made less than diameter - if (changedAxis == m_HeightAxis) - { - int radiusAxis; - GetRadiusAxis(out radiusAxis); - float diameter = upperBound[radiusAxis] - lowerBound[radiusAxis]; - float newHeight = upperBound[m_HeightAxis] - lowerBound[m_HeightAxis]; - if (newHeight < diameter) - { - if (handle == HandleDirection.PositiveX || handle == HandleDirection.PositiveY || handle == HandleDirection.PositiveZ) - upperBound[m_HeightAxis] = lowerBound[m_HeightAxis] + diameter; - else - lowerBound[m_HeightAxis] = upperBound[m_HeightAxis] - diameter; - } - } - // ensure radius changes uniformly and enlarges the height if necessary - else - { - // try to return height to its value at the time handle was clicked - upperBound[m_HeightAxis] = boundsOnClick.center[m_HeightAxis] + 0.5f * boundsOnClick.size[m_HeightAxis]; - lowerBound[m_HeightAxis] = boundsOnClick.center[m_HeightAxis] - 0.5f * boundsOnClick.size[m_HeightAxis]; - - float rad = 0.5f * (upperBound[changedAxis] - lowerBound[changedAxis]); - float halfCurrentHeight = 0.5f * (upperBound[m_HeightAxis] - lowerBound[m_HeightAxis]); - for (int axis = 0; axis < 3; ++axis) - { - if (axis == changedAxis) - continue; - float amt = axis == m_HeightAxis ? Mathf.Max(halfCurrentHeight, rad) : rad; - lowerBound[axis] = center[axis] - amt; - upperBound[axis] = center[axis] + amt; - } - } - return new Bounds((upperBound + lowerBound) * 0.5f, upperBound - lowerBound); - } - - // returns true only if both radius axes are enabled - private bool GetRadiusAxis(out int radiusAxis) - { - radiusAxis = s_NextAxis[m_HeightAxis]; - if (!IsAxisEnabled(radiusAxis)) - { - radiusAxis = s_NextAxis[radiusAxis]; - return false; - } - return IsAxisEnabled(s_NextAxis[radiusAxis]); - } - } -} diff --git a/Editor/Mono/EditorHandles/BoundsHandle/PrimitiveBoundsHandle.cs b/Editor/Mono/EditorHandles/BoundsHandle/PrimitiveBoundsHandle.cs index f10253d950..7f9efafb9a 100644 --- a/Editor/Mono/EditorHandles/BoundsHandle/PrimitiveBoundsHandle.cs +++ b/Editor/Mono/EditorHandles/BoundsHandle/PrimitiveBoundsHandle.cs @@ -122,8 +122,8 @@ public void DrawHandle() // handles int prevHotControl = GUIUtility.hotControl; - Vector3 cameraLocalPos = Handles.inverseMatrix.MultiplyPoint(Camera.current.transform.position); - bool isCameraInsideBox = m_Bounds.Contains(cameraLocalPos); + bool isCameraInsideBox = Camera.current != null + && m_Bounds.Contains(Handles.inverseMatrix.MultiplyPoint(Camera.current.transform.position)); EditorGUI.BeginChangeCheck(); using (new Handles.DrawingScope(Handles.color * handleColor)) MidpointHandles(ref minPos, ref maxPos, isCameraInsideBox); diff --git a/Editor/Mono/EditorHandles/BoundsHandle/SphereBoundsHandle.cs b/Editor/Mono/EditorHandles/BoundsHandle/SphereBoundsHandle.cs deleted file mode 100644 index d06fbb469e..0000000000 --- a/Editor/Mono/EditorHandles/BoundsHandle/SphereBoundsHandle.cs +++ /dev/null @@ -1,81 +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.IMGUI.Controls -{ - public class SphereBoundsHandle : PrimitiveBoundsHandle - { - [Obsolete("Use parameterless constructor instead.")] - public SphereBoundsHandle(int controlIDHint) : base(controlIDHint) {} - - public SphereBoundsHandle() : base() {} - - public float radius - { - get - { - Vector3 size = GetSize(); - float diameter = 0f; - for (int axis = 0; axis < 3; ++axis) - { - // only consider size values on enabled axes - if (IsAxisEnabled(axis)) - diameter = Mathf.Max(diameter, Mathf.Abs(size[axis])); - } - return diameter * 0.5f; - } - set { SetSize(2f * value * Vector3.one); } - } - - protected override void DrawWireframe() - { - bool x = IsAxisEnabled(Axes.X); - bool y = IsAxisEnabled(Axes.Y); - bool z = IsAxisEnabled(Axes.Z); - if (x && y) - Handles.DrawWireArc(center, Vector3.forward, Vector3.up, 360f, radius); - if (x && z) - Handles.DrawWireArc(center, Vector3.up, Vector3.right, 360f, radius); - if (y && z) - Handles.DrawWireArc(center, Vector3.right, Vector3.forward, 360f, radius); - if (x && !y && !z) - Handles.DrawLine(Vector3.right * radius, Vector3.left * radius); - if (!x && y && !z) - Handles.DrawLine(Vector3.up * radius, Vector3.down * radius); - if (!x && !y && z) - Handles.DrawLine(Vector3.forward * radius, Vector3.back * radius); - } - - protected override Bounds OnHandleChanged(HandleDirection handle, Bounds boundsOnClick, Bounds newBounds) - { - Vector3 upperBound = newBounds.max; - Vector3 lowerBound = newBounds.min; - // ensure radius changes uniformly - int changedAxis = 0; - switch (handle) - { - case HandleDirection.NegativeY: - case HandleDirection.PositiveY: - changedAxis = 1; - break; - case HandleDirection.NegativeZ: - case HandleDirection.PositiveZ: - changedAxis = 2; - break; - } - float rad = 0.5f * (upperBound[changedAxis] - lowerBound[changedAxis]); - for (int axis = 0; axis < 3; ++axis) - { - if (axis == changedAxis) - continue; - lowerBound[axis] = center[axis] - rad; - upperBound[axis] = center[axis] + rad; - } - return new Bounds((upperBound + lowerBound) * 0.5f, upperBound - lowerBound); - } - } -} diff --git a/Editor/Mono/EditorHandles/Button.cs b/Editor/Mono/EditorHandles/Button.cs deleted file mode 100644 index f924e1de24..0000000000 --- a/Editor/Mono/EditorHandles/Button.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; - -namespace UnityEditorInternal -{ - internal class Button - { - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - public static bool Do(int id, Vector3 position, Quaternion direction, float size, float pickSize, Handles.DrawCapFunction capFunc) - #pragma warning restore 618 - { - Event evt = Event.current; - - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - if (GUI.enabled) - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position, pickSize)); - break; - case EventType.MouseMove: - if (HandleUtility.nearestControl == id && evt.button == 0) - HandleUtility.Repaint(); - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = id; // Grab mouse focus - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - evt.Use(); - - if (HandleUtility.nearestControl == id) - return true; - } - break; - case EventType.Repaint: - Color origColor = Handles.color; - if (HandleUtility.nearestControl == id && GUI.enabled && GUIUtility.hotControl == 0) - Handles.color = Handles.preselectionColor; - - capFunc(id, position, direction, size); - - Handles.color = origColor; - break; - } - return false; - } - - public static bool Do(int id, Vector3 position, Quaternion direction, float size, float pickSize, Handles.CapFunction capFunction) - { - Event evt = Event.current; - - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - if (GUI.enabled) - capFunction(id, position, direction, pickSize, EventType.Layout); - break; - case EventType.MouseMove: - if (HandleUtility.nearestControl == id && evt.button == 0) - HandleUtility.Repaint(); - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = id; // Grab mouse focus - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - evt.Use(); - - if (HandleUtility.nearestControl == id) - return true; - } - break; - case EventType.Repaint: - Color origColor = Handles.color; - if (HandleUtility.nearestControl == id && GUI.enabled && GUIUtility.hotControl == 0) - Handles.color = Handles.preselectionColor; - - capFunction(id, position, direction, size, EventType.Repaint); - - Handles.color = origColor; - break; - } - return false; - } - } -} diff --git a/Editor/Mono/EditorHandles/Disc.cs b/Editor/Mono/EditorHandles/Disc.cs deleted file mode 100644 index 82982da2b8..0000000000 --- a/Editor/Mono/EditorHandles/Disc.cs +++ /dev/null @@ -1,207 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditorInternal -{ - internal class Disc - { - const int k_MaxSnapMarkers = 360 / 5; - const float k_RotationUnitSnapMajorMarkerStep = 45; - const float k_RotationUnitSnapMarkerSize = 0.1f; - const float k_RotationUnitSnapMajorMarkerSize = 0.2f; - const float k_GrabZoneScale = 0.3f; - - static Vector2 s_StartMousePosition, s_CurrentMousePosition; - static Vector3 s_StartPosition, s_StartAxis; - static Quaternion s_StartRotation; - static float s_RotationDist; - - public static Quaternion Do(int id, Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) - { - return Do(id, rotation, position, axis, size, cutoffPlane, snap, true, true, Handles.secondaryColor); - } - - public static Quaternion Do(int id, Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap, bool enableRayDrag, bool showHotArc, Color fillColor) - { - if (Mathf.Abs(Vector3.Dot(Camera.current.transform.forward, axis)) > .999f) - cutoffPlane = false; - - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - { - float d; - if (cutoffPlane) - { - Vector3 from = Vector3.Cross(axis, Camera.current.transform.forward).normalized; - d = HandleUtility.DistanceToArc(position, axis, from, 180, size) * k_GrabZoneScale; - } - else - { - d = HandleUtility.DistanceToDisc(position, axis, size) * k_GrabZoneScale; - } - - HandleUtility.AddControl(id, d); - break; - } - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0) - { - GUIUtility.hotControl = id; // Grab mouse focus - Tools.LockHandlePosition(); - if (cutoffPlane) - { - Vector3 from = Vector3.Cross(axis, Camera.current.transform.forward).normalized; - s_StartPosition = HandleUtility.ClosestPointToArc(position, axis, from, 180, size); - } - else - { - s_StartPosition = HandleUtility.ClosestPointToDisc(position, axis, size); - } - s_RotationDist = 0; - s_StartRotation = rotation; - s_StartAxis = axis; - s_CurrentMousePosition = s_StartMousePosition = Event.current.mousePosition; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - // handle look to point rotation - bool rayDrag = EditorGUI.actionKey && evt.shift && enableRayDrag; - if (rayDrag) - { - if (HandleUtility.ignoreRaySnapObjects == null) - Handles.SetupIgnoreRaySnapObjects(); - object hit = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(evt.mousePosition)); - if (hit != null && Vector3.Dot(axis.normalized, rotation * Vector3.forward) < 0.999) - { - RaycastHit rh = (RaycastHit)hit; - Vector3 lookPoint = rh.point - position; - Vector3 lookPointProjected = lookPoint - Vector3.Dot(lookPoint, axis.normalized) * axis.normalized; - rotation = Quaternion.LookRotation(lookPointProjected, rotation * Vector3.up); - } - } - else - { - Vector3 direction = Vector3.Cross(axis, position - s_StartPosition).normalized; - s_CurrentMousePosition += evt.delta; - s_RotationDist = HandleUtility.CalcLineTranslation(s_StartMousePosition, s_CurrentMousePosition, s_StartPosition, direction) / size * 30; - s_RotationDist = Handles.SnapValue(s_RotationDist, snap); - rotation = Quaternion.AngleAxis(s_RotationDist * -1, s_StartAxis) * s_StartRotation; - } - - GUI.changed = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - Tools.UnlockHandlePosition(); - GUIUtility.hotControl = 0; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.KeyDown: - if (evt.keyCode == KeyCode.Escape && GUIUtility.hotControl == id) - { - // We do not use the event nor clear hotcontrol to ensure auto revert value kicks in from native side - Tools.UnlockHandlePosition(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.Repaint: - Color temp = Color.white; - - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - // If we're dragging it, we'll go a bit further and draw a selection pie - if (GUIUtility.hotControl == id) - { - Color t = Handles.color; - Vector3 from = (s_StartPosition - position).normalized; - Handles.color = fillColor; - Handles.DrawLine(position, position + from * size); - var d = -Mathf.Sign(s_RotationDist) * Mathf.Repeat(Mathf.Abs(s_RotationDist), 360); - Vector3 to = Quaternion.AngleAxis(d, axis) * from; - Handles.DrawLine(position, position + to * size); - - Handles.color = fillColor * new Color(1, 1, 1, .2f); - for (int i = 0, revolutions = (int)Mathf.Abs(s_RotationDist * 0.002777777778f); i < revolutions; ++i) - Handles.DrawSolidDisc(position, axis, size); - Handles.DrawSolidArc(position, axis, from, d, size); - - // Draw snap markers - if (EditorGUI.actionKey && snap > 0) - { - DrawRotationUnitSnapMarkers(position, axis, size, k_RotationUnitSnapMarkerSize, snap, @from); - DrawRotationUnitSnapMarkers(position, axis, size, k_RotationUnitSnapMajorMarkerSize, k_RotationUnitSnapMajorMarkerStep, @from); - } - Handles.color = t; - } - - if (showHotArc && GUIUtility.hotControl == id || GUIUtility.hotControl != id && !cutoffPlane) - Handles.DrawWireDisc(position, axis, size); - else if (GUIUtility.hotControl != id && cutoffPlane) - { - Vector3 from = Vector3.Cross(axis, Camera.current.transform.forward).normalized; - Handles.DrawWireArc(position, axis, from, 180, size); - } - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - break; - } - - return rotation; - } - - static void DrawRotationUnitSnapMarkers(Vector3 position, Vector3 axis, float handleSize, float markerSize, float snap, Vector3 @from) - { - var iterationCount = Mathf.FloorToInt(360 / snap); - var performFading = iterationCount > k_MaxSnapMarkers; - var limitedIterationCount = Mathf.Min(iterationCount, k_MaxSnapMarkers); - - // center the markers around the current angle - var count = Mathf.RoundToInt(limitedIterationCount * 0.5f); - - for (var i = -count; i < count; ++i) - { - var rot = Quaternion.AngleAxis(i * snap, axis); - var u = rot * @from; - var startPoint = position + (1 - markerSize) * handleSize * u; - var endPoint = position + 1 * handleSize * u; - Handles.color = Handles.selectedColor; - if (performFading) - { - var alpha = 1 - Mathf.SmoothStep(0, 1, Mathf.Abs(i / ((float)limitedIterationCount - 1) - 0.5f) * 2); - Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, alpha); - } - Handles.DrawLine(startPoint, endPoint); - } - } - } -} diff --git a/Editor/Mono/EditorHandles/FreeMove.cs b/Editor/Mono/EditorHandles/FreeMove.cs deleted file mode 100644 index e360b44307..0000000000 --- a/Editor/Mono/EditorHandles/FreeMove.cs +++ /dev/null @@ -1,300 +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; - -namespace UnityEditorInternal -{ - internal class FreeMove - { - private static Vector2 s_StartMousePosition, s_CurrentMousePosition; - private static Vector3 s_StartPosition; - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - public static Vector3 Do(int id, Vector3 position, Quaternion rotation, float size, Vector3 snap, Handles.DrawCapFunction capFunc) - #pragma warning restore 618 - { - Vector3 worldPosition = Handles.matrix.MultiplyPoint(position); - Matrix4x4 origMatrix = Handles.matrix; - - VertexSnapping.HandleKeyAndMouseMove(id); - - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - // We only want the position to be affected by the Handles.matrix. - Handles.matrix = Matrix4x4.identity; - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(worldPosition, size * 1.2f)); - Handles.matrix = origMatrix; - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0) - { - GUIUtility.hotControl = id; // Grab mouse focus - s_CurrentMousePosition = s_StartMousePosition = evt.mousePosition; - s_StartPosition = position; - HandleUtility.ignoreRaySnapObjects = null; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - bool rayDrag = EditorGUI.actionKey && evt.shift; - - if (rayDrag) - { - if (HandleUtility.ignoreRaySnapObjects == null) - Handles.SetupIgnoreRaySnapObjects(); - - object hit = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(evt.mousePosition)); - if (hit != null) - { - RaycastHit rh = (RaycastHit)hit; - float offset = 0; - if (Tools.pivotMode == PivotMode.Center) - { - float geomOffset = HandleUtility.CalcRayPlaceOffset(HandleUtility.ignoreRaySnapObjects, rh.normal); - if (geomOffset != Mathf.Infinity) - { - offset = Vector3.Dot(position, rh.normal) - geomOffset; - } - } - position = Handles.inverseMatrix.MultiplyPoint(rh.point + (rh.normal * offset)); - } - else - { - rayDrag = false; - } - } - - if (!rayDrag) - { - // normal drag - s_CurrentMousePosition += new Vector2(evt.delta.x, -evt.delta.y) * EditorGUIUtility.pixelsPerPoint; - Vector3 screenPos = Camera.current.WorldToScreenPoint(Handles.matrix.MultiplyPoint(s_StartPosition)); - screenPos += (Vector3)(s_CurrentMousePosition - s_StartMousePosition); - position = Handles.inverseMatrix.MultiplyPoint(Camera.current.ScreenToWorldPoint(screenPos)); - - // Due to floating point inaccuracies, the back-and-forth transformations used may sometimes introduce - // tiny unintended movement in wrong directions. People notice when using a straight top/left/right ortho camera. - // In that case, just restrain the movement to the plane. - if (Camera.current.transform.forward == Vector3.forward || Camera.current.transform.forward == -Vector3.forward) - position.z = s_StartPosition.z; - if (Camera.current.transform.forward == Vector3.up || Camera.current.transform.forward == -Vector3.up) - position.y = s_StartPosition.y; - if (Camera.current.transform.forward == Vector3.right || Camera.current.transform.forward == -Vector3.right) - position.x = s_StartPosition.x; - - if (Tools.vertexDragging) - { - if (HandleUtility.ignoreRaySnapObjects == null) - Handles.SetupIgnoreRaySnapObjects(); - Vector3 near; - if (HandleUtility.FindNearestVertex(evt.mousePosition, null, out near)) - { - position = Handles.inverseMatrix.MultiplyPoint(near); - } - } - - if (EditorGUI.actionKey && !evt.shift) - { - Vector3 delta = position - s_StartPosition; - delta.x = Handles.SnapValue(delta.x, snap.x); - delta.y = Handles.SnapValue(delta.y, snap.y); - delta.z = Handles.SnapValue(delta.z, snap.z); - position = s_StartPosition + delta; - } - } - GUI.changed = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - HandleUtility.ignoreRaySnapObjects = null; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.Repaint: - Color temp = Color.white; - - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - // We only want the position to be affected by the Handles.matrix. - Handles.matrix = Matrix4x4.identity; - capFunc(id, worldPosition, Camera.current.transform.rotation, size); - Handles.matrix = origMatrix; - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - break; - } - return position; - } - - public static Vector3 Do(int id, Vector3 position, Quaternion rotation, float size, Vector3 snap, Handles.CapFunction handleFunction) - { - Vector3 worldPosition = Handles.matrix.MultiplyPoint(position); - Matrix4x4 origMatrix = Handles.matrix; - - VertexSnapping.HandleKeyAndMouseMove(id); - - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - // We only want the position to be affected by the Handles.matrix. - Handles.matrix = Matrix4x4.identity; - handleFunction(id, worldPosition, Camera.current.transform.rotation, size, EventType.Layout); - Handles.matrix = origMatrix; - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0) - { - GUIUtility.hotControl = id; // Grab mouse focus - s_CurrentMousePosition = s_StartMousePosition = evt.mousePosition; - s_StartPosition = position; - HandleUtility.ignoreRaySnapObjects = null; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - bool rayDrag = EditorGUI.actionKey && evt.shift; - - if (rayDrag) - { - if (HandleUtility.ignoreRaySnapObjects == null) - Handles.SetupIgnoreRaySnapObjects(); - - object hit = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(evt.mousePosition)); - if (hit != null) - { - RaycastHit rh = (RaycastHit)hit; - float offset = 0; - if (Tools.pivotMode == PivotMode.Center) - { - float geomOffset = HandleUtility.CalcRayPlaceOffset(HandleUtility.ignoreRaySnapObjects, rh.normal); - if (geomOffset != Mathf.Infinity) - { - offset = Vector3.Dot(position, rh.normal) - geomOffset; - } - } - position = Handles.inverseMatrix.MultiplyPoint(rh.point + (rh.normal * offset)); - } - else - { - rayDrag = false; - } - } - - if (!rayDrag) - { - // normal drag - s_CurrentMousePosition += new Vector2(evt.delta.x, -evt.delta.y) * EditorGUIUtility.pixelsPerPoint; - Vector3 screenPos = Camera.current.WorldToScreenPoint(Handles.matrix.MultiplyPoint(s_StartPosition)); - screenPos += (Vector3)(s_CurrentMousePosition - s_StartMousePosition); - position = Handles.inverseMatrix.MultiplyPoint(Camera.current.ScreenToWorldPoint(screenPos)); - - // Due to floating point inaccuracies, the back-and-forth transformations used may sometimes introduce - // tiny unintended movement in wrong directions. People notice when using a straight top/left/right ortho camera. - // In that case, just restrain the movement to the plane. - if (Camera.current.transform.forward == Vector3.forward || Camera.current.transform.forward == -Vector3.forward) - position.z = s_StartPosition.z; - if (Camera.current.transform.forward == Vector3.up || Camera.current.transform.forward == -Vector3.up) - position.y = s_StartPosition.y; - if (Camera.current.transform.forward == Vector3.right || Camera.current.transform.forward == -Vector3.right) - position.x = s_StartPosition.x; - - if (Tools.vertexDragging) - { - if (HandleUtility.ignoreRaySnapObjects == null) - Handles.SetupIgnoreRaySnapObjects(); - Vector3 near; - if (HandleUtility.FindNearestVertex(evt.mousePosition, null, out near)) - { - position = Handles.inverseMatrix.MultiplyPoint(near); - } - } - - if (EditorGUI.actionKey && !evt.shift) - { - Vector3 delta = position - s_StartPosition; - delta.x = Handles.SnapValue(delta.x, snap.x); - delta.y = Handles.SnapValue(delta.y, snap.y); - delta.z = Handles.SnapValue(delta.z, snap.z); - position = s_StartPosition + delta; - } - } - GUI.changed = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - HandleUtility.ignoreRaySnapObjects = null; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.Repaint: - Color temp = Color.white; - - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - // We only want the position to be affected by the Handles.matrix. - Handles.matrix = Matrix4x4.identity; - handleFunction(id, worldPosition, Camera.current.transform.rotation, size, EventType.Repaint); - Handles.matrix = origMatrix; - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - break; - } - return position; - } - } -} diff --git a/Editor/Mono/EditorHandles/FreeRotate.cs b/Editor/Mono/EditorHandles/FreeRotate.cs deleted file mode 100644 index 0a08ab0298..0000000000 --- a/Editor/Mono/EditorHandles/FreeRotate.cs +++ /dev/null @@ -1,138 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditorInternal -{ - internal class FreeRotate - { - static readonly Color s_DimmingColor = new Color(0f, 0f, 0f, 0.078f); - private static Vector2 s_CurrentMousePosition; - - public static Quaternion Do(int id, Quaternion rotation, Vector3 position, float size) - { - return Do(id, rotation, position, size, true); - } - - internal static Quaternion Do(int id, Quaternion rotation, Vector3 position, float size, bool drawCircle) - { - Vector3 worldPosition = Handles.matrix.MultiplyPoint(position); - Matrix4x4 origMatrix = Handles.matrix; - - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - // We only want the position to be affected by the Handles.matrix. - Handles.matrix = Matrix4x4.identity; - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(worldPosition, size) + HandleUtility.kPickDistance); - Handles.matrix = origMatrix; - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0) - { - GUIUtility.hotControl = id; // Grab mouse focus - Tools.LockHandlePosition(); - s_CurrentMousePosition = evt.mousePosition; - HandleUtility.ignoreRaySnapObjects = null; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - // rayDrag rotates object to look at ray hit - bool rayDrag = EditorGUI.actionKey && evt.shift; - if (rayDrag) - { - if (HandleUtility.ignoreRaySnapObjects == null) - Handles.SetupIgnoreRaySnapObjects(); - - object hit = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(evt.mousePosition)); - if (hit != null) - { - RaycastHit rh = (RaycastHit)hit; - Quaternion newRotation = Quaternion.LookRotation(rh.point - position); - if (Tools.pivotRotation == PivotRotation.Global) - { - Transform t = Selection.activeTransform; - if (t) - { - Quaternion delta = Quaternion.Inverse(t.rotation) * rotation; - newRotation = newRotation * delta; - } - } - rotation = newRotation; - } - } - else - { - s_CurrentMousePosition += evt.delta; - Vector3 rotDir = Camera.current.transform.TransformDirection(new Vector3(-evt.delta.y, -evt.delta.x, 0)); - rotation = Quaternion.AngleAxis(evt.delta.magnitude, rotDir.normalized) * rotation; - } - GUI.changed = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - Tools.UnlockHandlePosition(); - GUIUtility.hotControl = 0; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.KeyDown: - if (evt.keyCode == KeyCode.Escape && GUIUtility.hotControl == id) - { - // We do not use the event nor clear hotcontrol to ensure auto revert value kicks in from native side - Tools.UnlockHandlePosition(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.Repaint: - Color temp = Color.white; - var isHot = id == GUIUtility.hotControl; - var isPreselected = id == HandleUtility.nearestControl && GUIUtility.hotControl == 0; - - if (isHot) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (isPreselected) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - // We only want the position to be affected by the Handles.matrix. - Handles.matrix = Matrix4x4.identity; - if (drawCircle) - Handles.DrawWireDisc(worldPosition, Camera.current.transform.forward, size); - if (isPreselected || isHot) - { - Handles.color = s_DimmingColor; - Handles.DrawSolidDisc(worldPosition, Camera.current.transform.forward, size); - } - Handles.matrix = origMatrix; - - if (isHot || isPreselected) - Handles.color = temp; - break; - } - return rotation; - } - } -} diff --git a/Editor/Mono/EditorHandles/JointAngularLimitHandle.cs b/Editor/Mono/EditorHandles/JointAngularLimitHandle.cs index 10c838a157..9bbe0c21c8 100644 --- a/Editor/Mono/EditorHandles/JointAngularLimitHandle.cs +++ b/Editor/Mono/EditorHandles/JointAngularLimitHandle.cs @@ -26,10 +26,12 @@ private static float GetSortingDistance(ArcHandle handle) Vector3 worldPosition = Handles.matrix.MultiplyPoint3x4( Quaternion.AngleAxis(handle.angle, Vector3.up) * Vector3.forward * handle.radius ); - Vector3 toHandle = worldPosition - Camera.current.transform.position; - if (Camera.current.orthographic) + Vector3 toHandle = Camera.current == null + ? worldPosition + : worldPosition - Camera.current.transform.position; + if (Camera.current == null || Camera.current.orthographic) { - Vector3 lookVector = Camera.current.transform.forward; + Vector3 lookVector = Camera.current == null ? Vector3.forward : Camera.current.transform.forward; toHandle = lookVector * Vector3.Dot(lookVector, toHandle); } return toHandle.sqrMagnitude; diff --git a/Editor/Mono/EditorHandles/Slider1D.cs b/Editor/Mono/EditorHandles/Slider1D.cs deleted file mode 100644 index 2876e8ca10..0000000000 --- a/Editor/Mono/EditorHandles/Slider1D.cs +++ /dev/null @@ -1,185 +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; - -namespace UnityEditorInternal -{ - internal class Slider1D - { - private static Vector2 s_StartMousePosition, s_CurrentMousePosition; - private static Vector3 s_StartPosition; - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - internal static Vector3 Do(int id, Vector3 position, Vector3 direction, float size, Handles.DrawCapFunction drawFunc, float snap) - #pragma warning restore 618 - { - return Do(id, position, direction, direction, size, drawFunc, snap); - } - - internal static Vector3 Do(int id, Vector3 position, Vector3 direction, float size, Handles.CapFunction capFunction, float snap) - { - return Do(id, position, Vector3.zero, direction, direction, size, capFunction, snap); - } - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - internal static Vector3 Do(int id, Vector3 position, Vector3 handleDirection, Vector3 slideDirection, float size, Handles.DrawCapFunction drawFunc, float snap) - #pragma warning disable 618 - { - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - // This is an ugly hack. It would be better if the drawFunc can handle it's own layout. - if (drawFunc == Handles.ArrowCap) - { - HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + slideDirection * size)); - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + slideDirection * size, size * .2f)); - } - else - { - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position, size * .2f)); - } - break; - case EventType.MouseDown: - // am I closest to the thingy? - if ((HandleUtility.nearestControl == id && evt.button == 0) && GUIUtility.hotControl == 0) - { - GUIUtility.hotControl = id; // Grab mouse focus - s_CurrentMousePosition = s_StartMousePosition = evt.mousePosition; - s_StartPosition = position; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - s_CurrentMousePosition += evt.delta; - float dist = HandleUtility.CalcLineTranslation(s_StartMousePosition, s_CurrentMousePosition, s_StartPosition, slideDirection); - - dist = Handles.SnapValue(dist, snap); - - Vector3 worldDirection = Handles.matrix.MultiplyVector(slideDirection); - Vector3 worldPosition = Handles.matrix.MultiplyPoint(s_StartPosition) + worldDirection * dist; - position = Handles.inverseMatrix.MultiplyPoint(worldPosition); - GUI.changed = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.Repaint: - Color temp = Color.white; - - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - drawFunc(id, position, Quaternion.LookRotation(handleDirection), size); - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - break; - } - return position; - } - - internal static Vector3 Do(int id, Vector3 position, Vector3 offset, Vector3 handleDirection, Vector3 slideDirection, float size, Handles.CapFunction capFunction, float snap) - { - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - if (capFunction != null) - capFunction(id, position + offset, Quaternion.LookRotation(handleDirection), size, EventType.Layout); - else - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + offset, size * .2f)); - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0 && GUIUtility.hotControl == 0) - { - GUIUtility.hotControl = id; // Grab mouse focus - s_CurrentMousePosition = s_StartMousePosition = evt.mousePosition; - s_StartPosition = position; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - s_CurrentMousePosition += evt.delta; - float dist = HandleUtility.CalcLineTranslation(s_StartMousePosition, s_CurrentMousePosition, s_StartPosition, slideDirection); - - dist = Handles.SnapValue(dist, snap); - - Vector3 worldDirection = Handles.matrix.MultiplyVector(slideDirection); - Vector3 worldPosition = Handles.matrix.MultiplyPoint(s_StartPosition) + worldDirection * dist; - position = Handles.inverseMatrix.MultiplyPoint(worldPosition); - GUI.changed = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.Repaint: - Color temp = Color.white; - - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - capFunction(id, position + offset, Quaternion.LookRotation(handleDirection), size, EventType.Repaint); - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - break; - } - return position; - } - } -} diff --git a/Editor/Mono/EditorHandles/Slider2D.cs b/Editor/Mono/EditorHandles/Slider2D.cs deleted file mode 100644 index d3f5f0adb0..0000000000 --- a/Editor/Mono/EditorHandles/Slider2D.cs +++ /dev/null @@ -1,433 +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; - -namespace UnityEditorInternal -{ - internal class Slider2D - { - private static Vector2 s_CurrentMousePosition; - private static Vector3 s_StartPosition; - private static Vector2 s_StartPlaneOffset; - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - public static Vector3 Do( - int id, - Vector3 handlePos, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.DrawCapFunction drawFunc, - float snap, - bool drawHelper) - #pragma warning restore 618 - { - return Do(id, handlePos, new Vector3(0, 0, 0), handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); - } - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - public static Vector3 Do( - int id, - Vector3 handlePos, - Vector3 offset, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.DrawCapFunction drawFunc, - float snap, - bool drawHelper) - #pragma warning restore 618 - { - return Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, new Vector2(snap, snap), drawHelper); - } - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - public static Vector3 Do( - int id, - Vector3 handlePos, - Vector3 offset, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.DrawCapFunction drawFunc, - Vector2 snap, - bool drawHelper) - #pragma warning restore 618 - { - bool orgGuiChanged = GUI.changed; - GUI.changed = false; - - Vector2 delta = CalcDeltaAlongDirections(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, drawFunc, snap, drawHelper); - if (GUI.changed) - handlePos = s_StartPosition + slideDir1 * delta.x + slideDir2 * delta.y; - - GUI.changed |= orgGuiChanged; - return handlePos; - } - - // Returns the new handlePos - public static Vector3 Do( - int id, - Vector3 handlePos, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.CapFunction capFunction, - float snap, - bool drawHelper) - { - return Do(id, handlePos, new Vector3(0, 0, 0), handleDir, slideDir1, slideDir2, handleSize, capFunction, new Vector2(snap, snap), drawHelper); - } - - // Returns the new handlePos - public static Vector3 Do( - int id, - Vector3 handlePos, - Vector3 offset, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.CapFunction capFunction, - float snap, - bool drawHelper) - { - return Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, capFunction, new Vector2(snap, snap), drawHelper); - } - - // Returns the new handlePos - public static Vector3 Do( - int id, - Vector3 handlePos, - Vector3 offset, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.CapFunction capFunction, - Vector2 snap, - bool drawHelper) - { - bool orgGuiChanged = GUI.changed; - GUI.changed = false; - - Vector2 delta = CalcDeltaAlongDirections(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, drawHelper); - if (GUI.changed) - handlePos = s_StartPosition + slideDir1 * delta.x + slideDir2 * delta.y; - - GUI.changed |= orgGuiChanged; - return handlePos; - } - - // DrawCapFunction was marked plannned obsolete by @juha on 2016-03-16, marked obsolete warning by @adamm on 2016-12-21 - [Obsolete("DrawCapFunction is obsolete. Use the version with CapFunction instead. Example: Change SphereCap to SphereHandleCap.")] - #pragma warning disable 618 - private static Vector2 CalcDeltaAlongDirections( - int id, - Vector3 handlePos, - Vector3 offset, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.DrawCapFunction drawFunc, - Vector2 snap, - bool drawHelper) - #pragma warning restore 618 - { - Vector2 deltaDistanceAlongDirections = new Vector2(0, 0); - - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - // This is an ugly hack. It would be better if the drawFunc can handle it's own layout. - if (drawFunc == Handles.ArrowCap) - { - HandleUtility.AddControl(id, HandleUtility.DistanceToLine(handlePos + offset, handlePos + handleDir * handleSize)); - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle((handlePos + offset) + handleDir * handleSize, handleSize * .2f)); - } - else if (drawFunc == Handles.RectangleCap) - { - HandleUtility.AddControl(id, HandleUtility.DistanceToRectangle(handlePos + offset, Quaternion.LookRotation(handleDir, slideDir1), handleSize)); - } - else - { - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(handlePos + offset, handleSize * .5f)); - } - break; - - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0 && GUIUtility.hotControl == 0) - { - Plane plane = new Plane(Handles.matrix.MultiplyVector(handleDir), Handles.matrix.MultiplyPoint(handlePos)); - Ray mouseRay = HandleUtility.GUIPointToWorldRay(evt.mousePosition); - float dist = 0.0f; - plane.Raycast(mouseRay, out dist); - - GUIUtility.hotControl = id; // Grab mouse focus - s_CurrentMousePosition = evt.mousePosition; - s_StartPosition = handlePos; - - Vector3 localMousePoint = Handles.inverseMatrix.MultiplyPoint(mouseRay.GetPoint(dist)); - Vector3 clickOffset = localMousePoint - handlePos; - s_StartPlaneOffset.x = Vector3.Dot(clickOffset, slideDir1); - s_StartPlaneOffset.y = Vector3.Dot(clickOffset, slideDir2); - - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - break; - - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - s_CurrentMousePosition += evt.delta; - Vector3 worldPosition = Handles.matrix.MultiplyPoint(handlePos); - Vector3 worldSlideDir1 = Handles.matrix.MultiplyVector(slideDir1).normalized; - Vector3 worldSlideDir2 = Handles.matrix.MultiplyVector(slideDir2).normalized; - - // Detect hit with plane (ray from campos to cursor) - Ray mouseRay = HandleUtility.GUIPointToWorldRay(s_CurrentMousePosition); - Plane plane = new Plane(worldPosition, worldPosition + worldSlideDir1, worldPosition + worldSlideDir2); - float dist = 0.0f; - if (plane.Raycast(mouseRay, out dist)) - { - Vector3 hitpos = Handles.inverseMatrix.MultiplyPoint(mouseRay.GetPoint(dist)); - - // Determine hitpos projection onto slideDirs - deltaDistanceAlongDirections.x = HandleUtility.PointOnLineParameter(hitpos, s_StartPosition, slideDir1); - deltaDistanceAlongDirections.y = HandleUtility.PointOnLineParameter(hitpos, s_StartPosition, slideDir2); - deltaDistanceAlongDirections -= s_StartPlaneOffset; - if (snap.x > 0 || snap.y > 0) - { - deltaDistanceAlongDirections.x = Handles.SnapValue(deltaDistanceAlongDirections.x, snap.x); - deltaDistanceAlongDirections.y = Handles.SnapValue(deltaDistanceAlongDirections.y, snap.y); - } - - GUI.changed = true; - } - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.Repaint: - { - if (drawFunc == null) - break; - - Vector3 position = handlePos + offset; - Quaternion rotation = Quaternion.LookRotation(handleDir, slideDir1); - - Color temp = Color.white; - - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - drawFunc(id, position, rotation, handleSize); - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - - // Draw a helper rectangle to show what plane we are dragging in - if (drawHelper && GUIUtility.hotControl == id) - { - Vector3[] verts = new Vector3[4]; - float helperSize = handleSize * 10.0f; - verts[0] = position + (slideDir1 * helperSize + slideDir2 * helperSize); - verts[1] = verts[0] - slideDir1 * helperSize * 2.0f; - verts[2] = verts[1] - slideDir2 * helperSize * 2.0f; - verts[3] = verts[2] + slideDir1 * helperSize * 2.0f; - Color prevColor = Handles.color; - Handles.color = Color.white; - float outline = 0.6f; - Handles.DrawSolidRectangleWithOutline(verts, new Color(1, 1, 1, 0.05f), new Color(outline, outline, outline, 0.4f)); - Handles.color = prevColor; - } - } - - break; - } - - return deltaDistanceAlongDirections; - } - - // Returns the distance the new position has moved along slideDir1 and slideDir2 - private static Vector2 CalcDeltaAlongDirections( - int id, - Vector3 handlePos, - Vector3 offset, - Vector3 handleDir, - Vector3 slideDir1, - Vector3 slideDir2, - float handleSize, - Handles.CapFunction capFunction, - Vector2 snap, - bool drawHelper) - { - Vector3 position = handlePos + offset; - Quaternion rotation = Quaternion.LookRotation(handleDir, slideDir1); - Vector2 deltaDistanceAlongDirections = new Vector2(0, 0); - - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - if (capFunction != null) - capFunction(id, position, rotation, handleSize, EventType.Layout); - else - HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(handlePos + offset, handleSize * .5f)); - break; - case EventType.MouseDown: - // am I closest to the thingy? - if (HandleUtility.nearestControl == id && evt.button == 0 && GUIUtility.hotControl == 0) - { - s_CurrentMousePosition = evt.mousePosition; - bool success = true; - Vector3 localMousePoint = Handles.inverseMatrix.MultiplyPoint(GetMousePosition(handleDir, handlePos, ref success)); - if (success) - { - GUIUtility.hotControl = id; // Grab mouse focus - s_StartPosition = handlePos; - - Vector3 clickOffset = localMousePoint - handlePos; - s_StartPlaneOffset.x = Vector3.Dot(clickOffset, slideDir1); - s_StartPlaneOffset.y = Vector3.Dot(clickOffset, slideDir2); - - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(1); - } - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - s_CurrentMousePosition += evt.delta; - bool success = true; - Vector3 localMousePoint = Handles.inverseMatrix.MultiplyPoint(GetMousePosition(handleDir, handlePos, ref success)); - if (success) - { - // Determine hitpos projection onto slideDirs - deltaDistanceAlongDirections.x = HandleUtility.PointOnLineParameter(localMousePoint, s_StartPosition, slideDir1); - deltaDistanceAlongDirections.y = HandleUtility.PointOnLineParameter(localMousePoint, s_StartPosition, slideDir2); - deltaDistanceAlongDirections -= s_StartPlaneOffset; - if (snap.x > 0 || snap.y > 0) - { - deltaDistanceAlongDirections.x = Handles.SnapValue(deltaDistanceAlongDirections.x, snap.x); - deltaDistanceAlongDirections.y = Handles.SnapValue(deltaDistanceAlongDirections.y, snap.y); - } - - GUI.changed = true; - } - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) - { - GUIUtility.hotControl = 0; - evt.Use(); - EditorGUIUtility.SetWantsMouseJumping(0); - } - break; - case EventType.MouseMove: - if (id == HandleUtility.nearestControl) - HandleUtility.Repaint(); - break; - case EventType.Repaint: - { - if (capFunction == null) - break; - - Color temp = Color.white; - if (id == GUIUtility.hotControl) - { - temp = Handles.color; - Handles.color = Handles.selectedColor; - } - else if (id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - { - temp = Handles.color; - Handles.color = Handles.preselectionColor; - } - - capFunction(id, position, rotation, handleSize, EventType.Repaint); - - if (id == GUIUtility.hotControl || id == HandleUtility.nearestControl && GUIUtility.hotControl == 0) - Handles.color = temp; - - // Draw a helper rectangle to show what plane we are dragging in - if (drawHelper && GUIUtility.hotControl == id) - { - Vector3[] verts = new Vector3[4]; - float helperSize = handleSize * 10.0f; - verts[0] = position + (slideDir1 * helperSize + slideDir2 * helperSize); - verts[1] = verts[0] - slideDir1 * helperSize * 2.0f; - verts[2] = verts[1] - slideDir2 * helperSize * 2.0f; - verts[3] = verts[2] + slideDir1 * helperSize * 2.0f; - Color prevColor = Handles.color; - Handles.color = Color.white; - float outline = 0.6f; - Handles.DrawSolidRectangleWithOutline(verts, new Color(1, 1, 1, 0.05f), new Color(outline, outline, outline, 0.4f)); - Handles.color = prevColor; - } - } - - break; - } - - return deltaDistanceAlongDirections; - } - - private static Vector3 GetMousePosition(Vector3 handleDirection, Vector3 handlePosition, ref bool success) - { - if (Camera.current != null) - { - Plane plane = new Plane(Handles.matrix.MultiplyVector(handleDirection), Handles.matrix.MultiplyPoint(handlePosition)); - Ray mouseRay = HandleUtility.GUIPointToWorldRay(s_CurrentMousePosition); - float dist = 0.0f; - success = plane.Raycast(mouseRay, out dist); - return mouseRay.GetPoint(dist); - } - else - { - success = true; - return s_CurrentMousePosition; - } - } - } -} diff --git a/Editor/Mono/EditorHeaderItemAttribute.cs b/Editor/Mono/EditorHeaderItemAttribute.cs deleted file mode 100644 index 8a6fafc42b..0000000000 --- a/Editor/Mono/EditorHeaderItemAttribute.cs +++ /dev/null @@ -1,26 +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 UnityEditor; -using UnityEngine.Scripting; - -namespace UnityEditor -{ - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] - internal sealed partial class EditorHeaderItemAttribute : CallbackOrderAttribute - { - public EditorHeaderItemAttribute(Type targetType, int priority = 1) - { - TargetType = targetType; - m_CallbackOrder = priority; - } - - public Type TargetType; - - [RequiredSignature] - static extern bool SignatureBool(Rect rectangle, UnityEngine.Object[] targetObjets); - } -} diff --git a/Editor/Mono/EditorUserBuildSettings.bindings.cs b/Editor/Mono/EditorUserBuildSettings.bindings.cs index 04b6e3a25a..f7bddf49a9 100644 --- a/Editor/Mono/EditorUserBuildSettings.bindings.cs +++ b/Editor/Mono/EditorUserBuildSettings.bindings.cs @@ -626,6 +626,15 @@ public static extern bool switchNVNShaderDebugging set; } + // Enable debug validation of NVN drawcalls + public static extern bool switchNVNDrawValidation + { + [NativeMethod("GetNVNDrawValidation")] + get; + [NativeMethod("SetNVNDrawValidation")] + set; + } + // Enable linkage of the Heap inspector tool for Nintendo Switch. public static extern bool switchEnableHeapInspector { diff --git a/Editor/Mono/EditorUserBuildSettings.deprecated.cs b/Editor/Mono/EditorUserBuildSettings.deprecated.cs deleted file mode 100644 index faff5e9f4c..0000000000 --- a/Editor/Mono/EditorUserBuildSettings.deprecated.cs +++ /dev/null @@ -1,35 +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 -{ - public partial class EditorUserBuildSettings - { - // Select a new build target to be active. - [Obsolete("Please use SwitchActiveBuildTarget(BuildTargetGroup targetGroup, BuildTarget target)")] - public static bool SwitchActiveBuildTarget(BuildTarget target) - { - return SwitchActiveBuildTarget(BuildPipeline.GetBuildTargetGroup(target), target); - } - - // Triggered in response to SwitchActiveBuildTarget. - [Obsolete("UnityEditor.activeBuildTargetChanged has been deprecated.Use UnityEditor.Build.IActiveBuildTargetChanged instead.")] - public static Action activeBuildTargetChanged; - -#pragma warning disable 0618 - internal static void Internal_ActiveBuildTargetChanged() - { - if (activeBuildTargetChanged != null) - activeBuildTargetChanged(); - } - -#pragma warning restore 0618 - - // Force full optimisations for script complilation in Development builds (OBSOLETE, replaced by "IL2CPP optimization level" Player Setting) - [Obsolete("forceOptimizeScriptCompilation is obsolete - will always return false. Control script optimization using the 'IL2CPP optimization level' configuration in Player Settings / Other.")] - public static bool forceOptimizeScriptCompilation { get { return false; } } - } -} diff --git a/Editor/Mono/EditorUserBuildSettingsUtils.cs b/Editor/Mono/EditorUserBuildSettingsUtils.cs deleted file mode 100644 index 5226c39902..0000000000 --- a/Editor/Mono/EditorUserBuildSettingsUtils.cs +++ /dev/null @@ -1,30 +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 UnityEditor.Build; - -namespace UnityEditor -{ - internal static class EditorUserBuildSettingsUtils - { - public static BuildTarget CalculateSelectedBuildTarget() - { - BuildTargetGroup targetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; - switch (targetGroup) - { - case BuildTargetGroup.Standalone: - return DesktopStandaloneBuildWindowExtension.GetBestStandaloneTarget(EditorUserBuildSettings.selectedStandaloneTarget); - case BuildTargetGroup.Facebook: - return EditorUserBuildSettings.selectedFacebookTarget; - default: - if (BuildPlatforms.instance == null) - throw new System.Exception("Build platforms are not initialized."); - BuildPlatform platform = BuildPlatforms.instance.BuildPlatformFromTargetGroup(targetGroup); - if (platform == null) - throw new System.Exception("Could not find build platform for target group " + targetGroup); - return platform.defaultTarget; - } - } - } -} diff --git a/Editor/Mono/EditorUtility.cs b/Editor/Mono/EditorUtility.cs index b197a5a8c8..5ebdd84813 100644 --- a/Editor/Mono/EditorUtility.cs +++ b/Editor/Mono/EditorUtility.cs @@ -198,25 +198,25 @@ public static Object InstantiatePrefab(Object target) return PrefabUtility.InstantiatePrefab(target); } - [Obsolete("Use PrefabUtility.ReplacePrefab", false)] + [Obsolete("Use PrefabUtility.SaveAsPrefabAsset with a path instead.", false)] public static GameObject ReplacePrefab(GameObject go, Object targetPrefab, ReplacePrefabOptions options) { return PrefabUtility.ReplacePrefab(go, targetPrefab, options); } - [Obsolete("Use PrefabUtility.ReplacePrefab", false)] + [Obsolete("Use PrefabUtility.SaveAsPrefabAsset or PrefabUtility.SaveAsPrefabAssetAndConnect with a path instead.", false)] public static GameObject ReplacePrefab(GameObject go, Object targetPrefab) { return PrefabUtility.ReplacePrefab(go, targetPrefab, ReplacePrefabOptions.Default); } - [Obsolete("Use PrefabUtility.CreateEmptyPrefab", false)] + [Obsolete("The concept of creating a completely empty Prefab has been discontinued. You can however use PrefabUtility.SaveAsPrefabAsset with an empty GameObject.", false)] public static Object CreateEmptyPrefab(string path) { return PrefabUtility.CreateEmptyPrefab(path); } - [Obsolete("Use PrefabUtility.RevertPrefabInstance", false)] + [Obsolete("Use PrefabUtility.RevertPrefabInstance.", false)] public static bool ReconnectToLastPrefab(GameObject go) { return PrefabUtility.ReconnectToLastPrefab(go); @@ -240,7 +240,7 @@ public static GameObject FindPrefabRoot(GameObject source) return PrefabUtility.FindPrefabRoot(source); } - [Obsolete("Use PrefabUtility.ResetToPrefabState", false)] + [Obsolete("Use PrefabUtility.RevertObjectOverride.", false)] public static bool ResetToPrefabState(Object source) { return PrefabUtility.ResetToPrefabState(source); diff --git a/Editor/Mono/EditorWindow.cs b/Editor/Mono/EditorWindow.cs index 1b17962e0f..ba8446b436 100644 --- a/Editor/Mono/EditorWindow.cs +++ b/Editor/Mono/EditorWindow.cs @@ -478,8 +478,18 @@ public void ShowUtility() ShowWithMode(ShowMode.Utility); } - // Used for popup style windows. + internal void ShowTooltip() + { + ShowPopupWithMode(ShowMode.Tooltip); + } + public void ShowPopup() + { + ShowPopupWithMode(ShowMode.PopupMenu); + } + + // Used for popup style windows. + internal void ShowPopupWithMode(ShowMode mode) { if (m_Parent == null) { @@ -494,7 +504,7 @@ public void ShowPopup() cw.position = r; cw.rootView = host; MakeParentsSettingsMatchMe(); - cw.ShowPopup(); + cw.ShowPopupWithMode(mode); } } @@ -515,7 +525,7 @@ internal void ShowWithMode(ShowMode mode) cw.position = r; cw.rootView = host; MakeParentsSettingsMatchMe(); - cw.Show(mode, true, false); + cw.Show(mode, loadPosition: true, displayImmediately: false, setFocus: true); // set min/max size now that native window is not null so that it will e.g., use proper styleMask on macOS cw.SetMinMaxSizes(minSize, maxSize); @@ -531,7 +541,7 @@ public void ShowAsDropDown(Rect buttonRect, Vector2 windowSize) internal void ShowAsDropDown(Rect buttonRect, Vector2 windowSize, PopupLocation[] locationPriorityOrder) { - ShowAsDropDown(buttonRect, windowSize, locationPriorityOrder, ShowMode.PopupMenuWithKeyboardFocus); + ShowAsDropDown(buttonRect, windowSize, locationPriorityOrder, ShowMode.PopupMenu); } internal void ShowAsDropDown(Rect buttonRect, Vector2 windowSize, PopupLocation[] locationPriorityOrder, ShowMode mode) @@ -550,9 +560,9 @@ internal void ShowAsDropDown(Rect buttonRect, Vector2 windowSize, PopupLocation[ position = ShowAsDropDownFitToScreen(buttonRect, windowSize, locationPriorityOrder); // ShowWithMode() always grabs window focus so we use ShowPopup() for popup windows so PopupWindowWithoutFocus - // will work correctly (no focus when opened) - if (ContainerWindow.IsPopup(mode) && mode != ShowMode.PopupMenuWithKeyboardFocus) - ShowPopup(); + // will work correctly (no focus when opened). + if (ContainerWindow.IsPopup(mode)) + ShowPopupWithMode(mode); else ShowWithMode(mode); @@ -1058,24 +1068,19 @@ private void OnDisableINTERNAL() // Internal stuff: // Helper to show this EditorWindow - internal static void CreateNewWindowForEditorWindow(EditorWindow window, bool loadPosition, bool showImmediately) - { - CreateNewWindowForEditorWindow(window, new Vector2(window.position.x, window.position.y), loadPosition, showImmediately); - } - - internal static void CreateNewWindowForEditorWindow(EditorWindow window, Vector2 screenPosition, bool loadPosition, bool showImmediately) + internal static void CreateNewWindowForEditorWindow(EditorWindow window, bool loadPosition, bool showImmediately, bool setFocus = true) { ContainerWindow cw = ScriptableObject.CreateInstance(); SplitView sw = ScriptableObject.CreateInstance(); cw.rootView = sw; DockArea da = ScriptableObject.CreateInstance(); - da.AddTab(window); + da.AddTab(window, setFocus); sw.AddChild(da); - Rect r = window.m_Parent.borderSize.Add(new Rect(screenPosition.x, screenPosition.y, window.position.width, window.position.height)); + Rect r = window.m_Parent.borderSize.Add(window.position); cw.position = r; sw.position = new Rect(0, 0, r.width, r.height); window.MakeParentsSettingsMatchMe(); - cw.Show(ShowMode.NormalWindow, loadPosition, showImmediately); + cw.Show(ShowMode.NormalWindow, loadPosition, showImmediately, setFocus: true); //Need this, as show my change the size of the window, due to screen constraints cw.OnResize(); } diff --git a/Editor/Mono/ExportPackageOptions.cs b/Editor/Mono/ExportPackageOptions.cs deleted file mode 100644 index fcb14d2b7d..0000000000 --- a/Editor/Mono/ExportPackageOptions.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; -namespace UnityEditor -{ - // Export package option. Multiple options can be combined together using the | operator. - [Flags] - public enum ExportPackageOptions - { - // Default mode. Will not include dependencies or subdirectories nor include Library assets unless specifically included in the asset list. - Default = 0, - - // The export operation will be run asynchronously and reveal the exported package file in a file browser window after the export is finished. - Interactive = 1, - - // Will recurse through any subdirectories listed and include all assets inside them. - Recurse = 2, - - // In addition to the assets paths listed, all dependent assets will be included as well. - IncludeDependencies = 4, - - // The exported package will include all library assets, ie. the project settings located in the Library folder of the project. - IncludeLibraryAssets = 8 - } -} diff --git a/Editor/Mono/FileUtil.cs b/Editor/Mono/FileUtil.cs deleted file mode 100644 index 5222e33d7a..0000000000 --- a/Editor/Mono/FileUtil.cs +++ /dev/null @@ -1,318 +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.IO; -using System.Text.RegularExpressions; -using UnityEngine; - -namespace UnityEditor -{ - public partial class FileUtil - { - internal static void ReplaceText(string path, params string[] input) - { - path = NiceWinPath(path); - string[] data = File.ReadAllLines(path); - - for (int i = 0; i < input.Length; i += 2) - { - for (int q = 0; q < data.Length; ++q) - { - data[q] = data[q].Replace(input[i], input[i + 1]); - } - } - - File.WriteAllLines(path, data); - } - - internal static bool ReplaceTextRegex(string path, params string[] input) - { - bool res = false; - path = NiceWinPath(path); - string[] data = File.ReadAllLines(path); - - for (int i = 0; i < input.Length; i += 2) - { - for (int q = 0; q < data.Length; ++q) - { - string s = data[q]; - data[q] = Regex.Replace(s, input[i], input[i + 1]); - - if (s != (string)data[q]) - res = true; - } - } - - File.WriteAllLines(path, data); - return res; - } - - internal static bool AppendTextAfter(string path, string find, string append) - { - bool res = false; - path = NiceWinPath(path); - var data = new List(File.ReadAllLines(path)); - - for (int q = 0; q < data.Count; ++q) - { - if (data[q].Contains(find)) - { - data.Insert(q + 1, append); - res = true; - break; - } - } - - File.WriteAllLines(path, data.ToArray()); - return res; - } - - internal static void CopyDirectoryRecursive(string source, string target) - { - CopyDirectoryRecursive(source, target, false, false); - } - - internal static void CopyDirectoryRecursiveIgnoreMeta(string source, string target) - { - CopyDirectoryRecursive(source, target, false, true); - } - - internal static void CopyDirectoryRecursive(string source, string target, bool overwrite) - { - CopyDirectoryRecursive(source, target, overwrite, false); - } - - internal static void CopyDirectory(string source, string target, bool overwrite) - { - CopyDirectoryFiltered(source, target, overwrite, f => true, false); - } - - internal static void CopyDirectoryRecursive(string source, string target, bool overwrite, bool ignoreMeta) - { - CopyDirectoryRecursiveFiltered(source, target, overwrite, ignoreMeta ? @"\.meta$" : null); - } - - internal static void CopyDirectoryRecursiveForPostprocess(string source, string target, bool overwrite) - { - CopyDirectoryRecursiveFiltered(source, target, overwrite, @".*/\.+|\.meta$"); - } - - internal static void CopyDirectoryRecursiveFiltered(string source, string target, bool overwrite, string regExExcludeFilter) - { - CopyDirectoryFiltered(source, target, overwrite, regExExcludeFilter, true); - } - - internal static void CopyDirectoryFiltered(string source, string target, bool overwrite, string regExExcludeFilter, bool recursive) - { - Regex exclude = null; - try - { - if (regExExcludeFilter != null) - exclude = new Regex(regExExcludeFilter); - } - catch (ArgumentException) - { - Debug.Log("CopyDirectoryRecursive: Pattern '" + regExExcludeFilter + "' is not a correct Regular Expression. Not excluding any files."); - return; - } - - Func includeCallback = file => (exclude == null || !exclude.IsMatch(file)); - - CopyDirectoryFiltered(source, target, overwrite, includeCallback, recursive); - } - - internal static void CopyDirectoryFiltered(string source, string target, bool overwrite, Func includeCallback, bool recursive) - { - // Check if the target directory exists, but dont create it yet until we know there are files to copy. - bool createDirectory = !Directory.Exists(target); - - // Copy each file into the new directory. - foreach (string fi in Directory.GetFiles(source)) - { - if (!includeCallback(fi)) - continue; - - if (createDirectory) - { - Directory.CreateDirectory(target); - overwrite = false; // no reason to perform this on subdirs - createDirectory = false; - } - - string fname = Path.GetFileName(fi); - string targetfname = Path.Combine(target, fname); - - UnityFileCopy(fi, targetfname, overwrite); - } - - if (!recursive) - return; - - // Copy each subdirectory recursively. - foreach (string di in Directory.GetDirectories(source)) - { - if (!includeCallback(di)) - continue; - - string fname = Path.GetFileName(di); - - CopyDirectoryFiltered(Path.Combine(source, fname), Path.Combine(target, fname), overwrite, includeCallback, recursive); - } - } - - internal static void UnityDirectoryDelete(string path) - { - UnityDirectoryDelete(path, false); - } - - internal static void UnityDirectoryDelete(string path, bool recursive) - { - Directory.Delete(NiceWinPath(path), recursive); - } - - // set the System.IO.FileAttributes.Normal recursively on all files in target_dir - internal static void UnityDirectoryRemoveReadonlyAttribute(string target_dir) - { - string[] files = Directory.GetFiles(target_dir); - string[] dirs = Directory.GetDirectories(target_dir); - - foreach (string file in files) - { - File.SetAttributes(file, System.IO.FileAttributes.Normal); - } - - foreach (string dir in dirs) - { - UnityDirectoryRemoveReadonlyAttribute(dir); - } - } - - internal static void MoveFileIfExists(string src, string dst) - { - if (File.Exists(src)) - { - DeleteFileOrDirectory(dst); - MoveFileOrDirectory(src, dst); - File.SetLastWriteTime(dst, DateTime.Now); - } - } - - internal static void CopyFileIfExists(string src, string dst, bool overwrite) - { - if (File.Exists(src)) - { - UnityFileCopy(src, dst, overwrite); - } - } - - internal static void UnityFileCopy(string from, string to, bool overwrite) - { - File.Copy(NiceWinPath(from), NiceWinPath(to), overwrite); - } - - internal static string NiceWinPath(string unityPath) - { - // IO functions do not like mixing of \ and / slashes, esp. for windows network paths (\\path) - return Application.platform == RuntimePlatform.WindowsEditor ? unityPath.Replace("/", @"\") : unityPath; - } - - internal static string UnityGetFileNameWithoutExtension(string path) - { - // this is because on Windows \\ means network path, in unity all \ are converted to / - // network paths become // and Path class functions think it's the same as / - return Path.GetFileNameWithoutExtension(path.Replace("//", @"\\")).Replace(@"\\", "//"); - } - - internal static string UnityGetFileName(string path) - { - // this is because on Windows \\ means network path, in unity all \ are converted to / - // network paths become // and Path class functions think it's the same as / - return Path.GetFileName(path.Replace("//", @"\\")).Replace(@"\\", "//"); - } - - internal static string UnityGetDirectoryName(string path) - { - // this is because on Windows \\ means network path, in unity all \ are converted to / - // network paths become // and Path class functions think it's the same as / - return Path.GetDirectoryName(path.Replace("//", @"\\")).Replace(@"\\", "//"); - } - - internal static void UnityFileCopy(string from, string to) - { - UnityFileCopy(from, to, false); - } - - internal static void CreateOrCleanDirectory(string dir) - { - if (Directory.Exists(dir)) - Directory.Delete(dir, true); - Directory.CreateDirectory(dir); - } - - internal static string RemovePathPrefix(string fullPath, string prefix) - { - var partsOfFull = fullPath.Split(Path.DirectorySeparatorChar); - var partsOfPrefix = prefix.Split(Path.DirectorySeparatorChar); - int index = 0; - - if (partsOfFull[0] == string.Empty) - index = 1; - - while (index < partsOfFull.Length - && index < partsOfPrefix.Length - && partsOfFull[index] == partsOfPrefix[index]) - ++index; - - if (index == partsOfFull.Length) - return ""; - - return string.Join(Path.DirectorySeparatorChar.ToString(), - partsOfFull, index, partsOfFull.Length - index); - } - - internal static string CombinePaths(params string[] paths) - { - if (null == paths) - return string.Empty; - return string.Join(Path.DirectorySeparatorChar.ToString(), paths); - } - - internal static List GetAllFilesRecursive(string path) - { - List files = new List(); - WalkFilesystemRecursively(path, - (p) => { files.Add(p); }, - (p) => { return true; }); - return files; - } - - internal static void WalkFilesystemRecursively(string path, - Action fileCallback, - Func directoryCallback) - { - foreach (string file in Directory.GetFiles(path)) - fileCallback(file); - foreach (string subdir in Directory.GetDirectories(path)) - { - if (directoryCallback(subdir)) - WalkFilesystemRecursively(subdir, fileCallback, directoryCallback); - } - } - - internal static long GetDirectorySize(string path) - { - var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); - long filesSize = 0; - foreach (var file in files) - { - var info = new FileInfo(file); - filesSize += info.Length; - } - return filesSize; - } - } -} diff --git a/Editor/Mono/FlagSet.cs b/Editor/Mono/FlagSet.cs deleted file mode 100644 index 94294ffb9c..0000000000 --- a/Editor/Mono/FlagSet.cs +++ /dev/null @@ -1,36 +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 -{ - // Holds a flag set. Can be used with enum flags. - // Has semantic value in separating a single value of an enum versus the flag set - [Serializable] - internal struct FlagSet where T : IConvertible - { - private ulong m_Flags; - - public bool HasFlags(T flags) - { - return (m_Flags & Convert.ToUInt64(flags)) != 0; - } - - public void SetFlags(T flags, bool value) - { - if (value) - m_Flags |= Convert.ToUInt64(flags); - else - m_Flags &= ~Convert.ToUInt64(flags); - } - - public FlagSet(T flags) - { - m_Flags = Convert.ToUInt64(flags); - } - - public static implicit operator FlagSet(T flags) {return new FlagSet(flags); } - } -} diff --git a/Editor/Mono/GI/LightmapEditorSettings.bindings.cs b/Editor/Mono/GI/LightmapEditorSettings.bindings.cs index 4f841a6632..2a28803785 100644 --- a/Editor/Mono/GI/LightmapEditorSettings.bindings.cs +++ b/Editor/Mono/GI/LightmapEditorSettings.bindings.cs @@ -29,8 +29,11 @@ public enum Lightmapper [Obsolete("Use Lightmapper.ProgressiveCPU instead. (UnityUpgradable) -> UnityEditor.LightmapEditorSettings/Lightmapper.ProgressiveCPU", true)] PathTracer = 1, - // Lightmaps are baked by the Progressive lightmapper (Wintermute + OpenRL based). - ProgressiveCPU = 1 + // Lightmaps are baked by the CPU Progressive lightmapper (Wintermute + OpenRL based). + ProgressiveCPU = 1, + + // Lightmaps are baked by the GPU Progressive lightmapper (RadeonRays + OpenCL based). + ProgressiveGPU = 2 } // Which path tracer sampling scheme is used. diff --git a/Editor/Mono/GI/LightmapSnapshot.deprecated.cs b/Editor/Mono/GI/LightmapSnapshot.deprecated.cs deleted file mode 100644 index 91990a6f73..0000000000 --- a/Editor/Mono/GI/LightmapSnapshot.deprecated.cs +++ /dev/null @@ -1,16 +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 -{ - //Originally class was defined in Lightmapping.bindings - [System.Obsolete("LightmapSnapshot has been deprecated. Use LightingDataAsset instead (UnityUpgradable) -> LightingDataAsset", true)] - [UnityEngine.NativeClass(null)] - public class LightmapSnapshot : UnityEngine.Object // No **partial** needed since it is a **type** rename - { - //Original class had no public members - } -} - diff --git a/Editor/Mono/GI/LightmapVisualization.bindings.cs b/Editor/Mono/GI/LightmapVisualization.bindings.cs index 95cdebbaf8..435a75b001 100644 --- a/Editor/Mono/GI/LightmapVisualization.bindings.cs +++ b/Editor/Mono/GI/LightmapVisualization.bindings.cs @@ -31,6 +31,9 @@ internal sealed partial class LightmapVisualizationUtility [StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)] internal extern static bool IsBakedTextureType(GITextureType textureType); + [StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)] + internal extern static bool IsAtlasTextureType(GITextureType textureType); + [StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)] public extern static VisualisationGITexture[] GetRealtimeGITextures(GITextureType textureType); diff --git a/Editor/Mono/GI/Lightmapping.deprecated.cs b/Editor/Mono/GI/Lightmapping.deprecated.cs deleted file mode 100644 index a68547da5b..0000000000 --- a/Editor/Mono/GI/Lightmapping.deprecated.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 UnityEngine; -using UnityEngineInternal; - -namespace UnityEditor -{ - public partial class Lightmapping - { - [System.Obsolete("lightmapSnapshot has been deprecated. Use lightingDataAsset instead (UnityUpgradable) -> lightingDataAsset", true)] - public static LightmapSnapshot lightmapSnapshot - { - get { return null; } - set {} - } - - [System.Obsolete("BakeSelectedAsync has been deprecated. Use BakeAsync instead (UnityUpgradable) -> BakeAsync()", true)] - public static bool BakeSelectedAsync() { return false; } - - [System.Obsolete("BakeSelected has been deprecated. Use Bake instead (UnityUpgradable) -> Bake()", true)] - public static bool BakeSelected() { return false; } - - [System.Obsolete("BakeLightProbesOnlyAsync has been deprecated. Use BakeAsync instead (UnityUpgradable) -> BakeAsync()", true)] - public static bool BakeLightProbesOnlyAsync() { return false; } - - [System.Obsolete("BakeLightProbesOnly has been deprecated. Use Bake instead (UnityUpgradable) -> Bake()", true)] - public static bool BakeLightProbesOnly() { return false; } - } -} - diff --git a/Editor/Mono/GUI/AnimatedValues.cs b/Editor/Mono/GUI/AnimatedValues.cs deleted file mode 100644 index 2fb0b2d990..0000000000 --- a/Editor/Mono/GUI/AnimatedValues.cs +++ /dev/null @@ -1,259 +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.Events; - -namespace UnityEditor.AnimatedValues -{ - public abstract class BaseAnimValue - { - private T m_Start; - - [SerializeField] - private T m_Target; - - private double m_LastTime; - private double m_LerpPosition = 1f; - - public float speed = 2f; - - [NonSerialized] - public UnityEvent valueChanged; - - private bool m_Animating; - - protected BaseAnimValue(T value) - { - m_Start = value; - m_Target = value; - valueChanged = new UnityEvent(); - } - - protected BaseAnimValue(T value, UnityAction callback) - { - m_Start = value; - m_Target = value; - valueChanged = new UnityEvent(); - valueChanged.AddListener(callback); - } - - private static T2 Clamp(T2 val, T2 min, T2 max) where T2 : IComparable - { - if (val.CompareTo(min) < 0) return min; - if (val.CompareTo(max) > 0) return max; - return val; - } - - protected void BeginAnimating(T newTarget, T newStart) - { - m_Start = newStart; - m_Target = newTarget; - - EditorApplication.update += Update; - m_Animating = true; - m_LastTime = EditorApplication.timeSinceStartup; - m_LerpPosition = 0; - } - - public bool isAnimating - { - get { return m_Animating; } - } - - private void Update() - { - if (!m_Animating) - return; - - // update the lerpPosition - UpdateLerpPosition(); - - if (valueChanged != null) - valueChanged.Invoke(); - - if (lerpPosition >= 1f) - { - m_Animating = false; - EditorApplication.update -= Update; - } - } - - protected float lerpPosition - { - get - { - var v = 1.0 - m_LerpPosition; - var result = 1.0 - v * v * v * v; - return (float)result; - } - } - - private void UpdateLerpPosition() - { - double nowTime = EditorApplication.timeSinceStartup; - double deltaTime = nowTime - m_LastTime; - - m_LerpPosition = Clamp(m_LerpPosition + (deltaTime * speed), 0.0, 1.0); - m_LastTime = nowTime; - } - - protected void StopAnim(T newValue) - { - // If the new value is different, or we might be in the middle of a fade, we need to refresh. - // Checking GetValue is not reliable on its own, since for e.g. bool it'll return the "closest" value, - // but that doesn't mean the fade is done. - bool invoke = false; - if ((!newValue.Equals(GetValue()) || m_LerpPosition < 1) && valueChanged != null) - invoke = true; - - m_Target = newValue; - m_Start = newValue; - m_LerpPosition = 1; - m_Animating = false; - // Only refresh *after* we set the correct new value. - if (invoke) - valueChanged.Invoke(); - } - - protected T start - { - get { return m_Start; } - } - - public T target - { - get { return m_Target; } - set - { - if (!m_Target.Equals(value)) - BeginAnimating(value, this.value); - } - } - - public T value - { - get { return GetValue(); } - set { StopAnim(value); } - } - - protected abstract T GetValue(); - } - - [Serializable] - public class AnimFloat : BaseAnimValue - { - [SerializeField] - private float m_Value; - - public AnimFloat(float value) - : base(value) - {} - - public AnimFloat(float value, UnityAction callback) : base(value, callback) - {} - - protected override float GetValue() - { - m_Value = Mathf.Lerp(start, target, lerpPosition); - return m_Value; - } - } - - [Serializable] - public class AnimVector3 : BaseAnimValue - { - [SerializeField] - private Vector3 m_Value; - - public AnimVector3() - : base(Vector3.zero) - {} - - public AnimVector3(Vector3 value) - : base(value) - {} - - public AnimVector3(Vector3 value, UnityAction callback) - : base(value, callback) - {} - - protected override Vector3 GetValue() - { - m_Value = Vector3.Lerp(start, target, lerpPosition); - return m_Value; - } - } - - [Serializable] - public class AnimBool : BaseAnimValue - { - [SerializeField] - private float m_Value; - - public AnimBool() - : base(false) - {} - - public AnimBool(bool value) - : base(value) - {} - - public AnimBool(UnityAction callback) - : base(false, callback) - {} - - public AnimBool(bool value, UnityAction callback) - : base(value, callback) - {} - - public float faded - { - get - { - GetValue(); - return m_Value; - } - } - - protected override bool GetValue() - { - float startVal = target ? 0f : 1f; - float end = 1f - startVal; - - m_Value = Mathf.Lerp(startVal, end, lerpPosition); - - return m_Value > .5f; - } - - public float Fade(float from, float to) - { - return Mathf.Lerp(from, to, faded); - } - } - - [Serializable] - public class AnimQuaternion : BaseAnimValue - { - [SerializeField] - private Quaternion m_Value; - - - public AnimQuaternion(Quaternion value) - : base(value) - {} - - public AnimQuaternion(Quaternion value, UnityAction callback) - : base(value, callback) - {} - - protected override Quaternion GetValue() - { - m_Value = Quaternion.Slerp(start, target, lerpPosition); - return m_Value; - } - } -} -//namespace diff --git a/Editor/Mono/GUI/BumpMapSettingsFixingWindow.cs b/Editor/Mono/GUI/BumpMapSettingsFixingWindow.cs deleted file mode 100644 index 12c9eb7f3c..0000000000 --- a/Editor/Mono/GUI/BumpMapSettingsFixingWindow.cs +++ /dev/null @@ -1,93 +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 UnityEditorInternal; - -namespace UnityEditor -{ - internal class BumpMapSettingsFixingWindow : EditorWindow - { - public static void ShowWindow(string[] paths) - { - BumpMapSettingsFixingWindow win = EditorWindow.GetWindow(true); - win.SetPaths(paths); - win.ShowUtility(); - } - - class Styles - { - public GUIStyle selected = "OL SelectedRow"; - public GUIStyle box = "OL Box"; - public GUIStyle button = "LargeButton"; - public GUIContent overviewText = EditorGUIUtility.TrTextContent("A Material is using the texture as a normal map.\nThe texture must be marked as a normal map in the import settings."); - } - - static Styles s_Styles = null; - - ListViewState m_LV = new ListViewState(); - string[] m_Paths; - - public BumpMapSettingsFixingWindow() - { - titleContent = EditorGUIUtility.TrTextContent("NormalMap settings"); - } - - public void SetPaths(string[] paths) - { - m_Paths = paths; - m_LV.totalRows = paths.Length; - } - - void OnGUI() - { - if (s_Styles == null) - { - s_Styles = new Styles(); - minSize = new Vector2(400, 300); - position = new Rect(position.x, position.y, minSize.x, minSize.y); - } - - GUILayout.Space(5); - GUILayout.Label(s_Styles.overviewText); - GUILayout.Space(10); - - GUILayout.BeginHorizontal(); - GUILayout.Space(10); - foreach (ListViewElement el in ListViewGUILayout.ListView(m_LV, s_Styles.box)) - { - if (el.row == m_LV.row && Event.current.type == EventType.Repaint) - s_Styles.selected.Draw(el.position, false, false, false, false); - - GUILayout.Label(m_Paths[el.row]); - } - GUILayout.Space(10); - GUILayout.EndHorizontal(); - GUILayout.Space(10); - - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - if (GUILayout.Button("Fix now", s_Styles.button)) - { - InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(1); - Close(); - } - - if (GUILayout.Button("Ignore", s_Styles.button)) - { - InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(0); - Close(); - } - GUILayout.Space(10); - GUILayout.EndHorizontal(); - - GUILayout.Space(10); - } - - void OnDestroy() - { - InternalEditorUtility.BumpMapSettingsFixingWindowReportResult(0); - } - } -} diff --git a/Editor/Mono/GUI/ButtonWithAnimatedIcon.cs b/Editor/Mono/GUI/ButtonWithAnimatedIcon.cs deleted file mode 100644 index 55fc989ac9..0000000000 --- a/Editor/Mono/GUI/ButtonWithAnimatedIcon.cs +++ /dev/null @@ -1,81 +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 -{ - public sealed partial class EditorGUI - { - internal static bool ButtonWithRotatedIcon(Rect rect, GUIContent guiContent, float iconAngle, bool mouseDownButton, GUIStyle style) - { - // Button with text and background (no icon - it's rendered separately below) - bool buttonPressed; - if (mouseDownButton) - buttonPressed = DropdownButton(rect, GUIContent.Temp(guiContent.text, guiContent.tooltip), FocusType.Passive, style); - else - buttonPressed = GUI.Button(rect, GUIContent.Temp(guiContent.text, guiContent.tooltip), style); - - // Icon (rendered left of text) - if (Event.current.type == EventType.Repaint && guiContent.image != null) - { - Vector2 iconSize = EditorGUIUtility.GetIconSize(); - if (iconSize == Vector2.zero) - { - iconSize.x = iconSize.y = rect.height - style.padding.vertical; - } - - const float spaceBetweenIconAndText = 3f; - const float spaceBetweenIconAndTop = 1f; - Rect iconRect = new Rect(rect.x + style.padding.left - spaceBetweenIconAndText - iconSize.x, rect.y + style.padding.top + spaceBetweenIconAndTop, iconSize.x, iconSize.y); - if (iconAngle == 0f) - { - GUI.DrawTexture(iconRect, guiContent.image); - } - else - { - Matrix4x4 prevMatrix = GUI.matrix; - GUIUtility.RotateAroundPivot(iconAngle, iconRect.center); - GUI.DrawTexture(iconRect, guiContent.image); - GUI.matrix = prevMatrix; - } - } - return buttonPressed; - } - } - - // Ensure to call Clear() before setting a instance to null to prevent mem leaking - // due to CallbackController using a delegate for update calls (if not de-registering this - // delegate, it will keep the instance from being gc'ed) - internal class ButtonWithAnimatedIconRotation - { - readonly CallbackController m_CallbackController; // used for continuous repaints - readonly Func m_AngleCallback; - readonly bool m_MouseDownButton; - - public ButtonWithAnimatedIconRotation(Func angleCallback, Action repaintCallback, float repaintsPerSecond, bool mouseDownButton) - { - m_CallbackController = new CallbackController(repaintCallback, repaintsPerSecond); - m_AngleCallback = angleCallback; - m_MouseDownButton = mouseDownButton; - } - - public bool OnGUI(Rect rect, GUIContent guiContent, bool animate, GUIStyle style) - { - if (animate && !m_CallbackController.active) - m_CallbackController.Start(); - if (!animate && m_CallbackController.active) - m_CallbackController.Stop(); - - float iconAngle = animate ? m_AngleCallback() : 0f; - return EditorGUI.ButtonWithRotatedIcon(rect, guiContent, iconAngle, m_MouseDownButton, style); - } - - public void Clear() - { - m_CallbackController.Stop(); - } - } -} diff --git a/Editor/Mono/GUI/CallbackController.cs b/Editor/Mono/GUI/CallbackController.cs deleted file mode 100644 index bfe7f78d49..0000000000 --- a/Editor/Mono/GUI/CallbackController.cs +++ /dev/null @@ -1,49 +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; - -namespace UnityEditor -{ - class CallbackController - { - readonly Action m_Callback; - readonly float m_CallbacksPerSecond; - double m_NextCallback; - - public CallbackController(Action callback, float callbacksPerSecond) - { - m_Callback = callback; - m_CallbacksPerSecond = Mathf.Max(callbacksPerSecond, 1f); - } - - public bool active { get; private set; } - - public void Start() - { - m_NextCallback = 0; - EditorApplication.update += Update; - active = true; - } - - public void Stop() - { - EditorApplication.update -= Update; - active = false; - } - - void Update() - { - double time = EditorApplication.timeSinceStartup; - if (time > m_NextCallback) - { - m_NextCallback = time + (1f / m_CallbacksPerSecond); - if (m_Callback != null) - m_Callback(); - } - } - } -} diff --git a/Editor/Mono/GUI/ColorClipboard.cs b/Editor/Mono/GUI/ColorClipboard.cs deleted file mode 100644 index 8381d0508c..0000000000 --- a/Editor/Mono/GUI/ColorClipboard.cs +++ /dev/null @@ -1,49 +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.Networking; - -namespace UnityEditor -{ - // ColorClipboard supports colors copied to the system copy buffer (as a hex string) and as a Color value to the Pasteboard (in c++) - static internal class ColorClipboard - { - public static void SetColor(Color color) - { - EditorGUIUtility.systemCopyBuffer = ""; - EditorGUIUtility.SetPasteboardColor(color); - } - - public static bool HasColor() - { - Color dummy; - return TryGetColor(false, out dummy); - } - - public static bool TryGetColor(bool allowHDR, out Color color) - { - bool validColor = false; - if (ColorUtility.TryParseHtmlString(EditorGUIUtility.systemCopyBuffer, out color)) - { - validColor = true; - } - else if (EditorGUIUtility.HasPasteboardColor()) - { - color = EditorGUIUtility.GetPasteboardColor(); - validColor = true; - } - - if (validColor) - { - // Ensure HDR colors are normalized for LDR color fields - if (!allowHDR && color.maxColorComponent > 1f) - color = color.RGBMultiplied(1f / color.maxColorComponent); - return true; - } - - return false; - } - } -} // namespace diff --git a/Editor/Mono/GUI/ColorPicker.cs b/Editor/Mono/GUI/ColorPicker.cs index 453514fc52..670789bce6 100644 --- a/Editor/Mono/GUI/ColorPicker.cs +++ b/Editor/Mono/GUI/ColorPicker.cs @@ -448,7 +448,7 @@ void DrawColorSpaceBox(Rect colorBoxRect, float constantValue) m_LastConstant = constantValue; m_TextureColorBoxMode = (int)m_ColorBoxMode; } - Graphics.DrawTexture(colorBoxRect, m_ColorBox, new Rect(.5f / m_ColorBox.width, .5f / m_ColorBox.height, 1 - 1f / m_ColorBox.width, 1 - 1f / m_ColorBox.height), 0, 0, 0, 0, Color.grey); + Graphics.DrawTexture(colorBoxRect, m_ColorBox, new Rect(.5f / m_ColorBox.width, .5f / m_ColorBox.height, 1 - 1f / m_ColorBox.width, 1 - 1f / m_ColorBox.height), 0, 0, 0, 0, new Color(.5f, .5f, .5f, .5f)); } static class Styles @@ -570,7 +570,7 @@ void DoColorSwatchAndEyedropper() if (GUILayout.Button(Styles.eyeDropper, GUIStyle.none, GUILayout.Width(40), GUILayout.ExpandWidth(false))) { GUIUtility.keyboardControl = 0; - EyeDropper.Start(m_Parent, false); + EyeDropper.Start(m_Parent); m_ColorBoxMode = ColorBoxMode.EyeDropper; GUIUtility.ExitGUI(); } @@ -958,6 +958,15 @@ void OnGUI() } } + // Cancel EyeDropper if we change focus. + if (m_ColorBoxMode == ColorBoxMode.EyeDropper && + Event.current.type == EventType.ExecuteCommand && + Event.current.commandName == EventCommandNames.NewKeyboardFocus) + { + EyeDropper.End(); + OnEyedropperCancelled(); + } + // Remove keyfocus when clicked outside any control if ((Event.current.type == EventType.MouseDown && Event.current.button != 1) || Event.current.type == EventType.ContextClick) { @@ -1229,17 +1238,17 @@ internal class EyeDropper : GUIView private bool m_Focused = false; private Action m_ColorPickedCallback; - public static void Start(GUIView viewToUpdate, bool stealFocus = true) + public static void Start(GUIView viewToUpdate) { - Start(viewToUpdate, null, stealFocus); + Start(viewToUpdate, null); } - public static void Start(Action colorPickedCallback, bool stealFocus = true) + public static void Start(Action colorPickedCallback) { - Start(null, colorPickedCallback, stealFocus); + Start(null, colorPickedCallback); } - static void Start(GUIView viewToUpdate, Action colorPickedCallback, bool stealFocus) + static void Start(GUIView viewToUpdate, Action colorPickedCallback) { instance.m_DelegateView = viewToUpdate; instance.m_ColorPickedCallback = colorPickedCallback; @@ -1248,15 +1257,13 @@ static void Start(GUIView viewToUpdate, Action colorPickedCallback, bool win.title = "EyeDropper"; win.hideFlags = HideFlags.DontSave; win.rootView = instance; - win.Show(ShowMode.PopupMenu, true, false); + win.Show(ShowMode.PopupMenu, loadPosition: true, displayImmediately: false, setFocus: true); instance.AddToAuxWindowList(); win.SetInvisible(); instance.SetMinMaxSizes(new Vector2(0, 0), new Vector2(kDummyWindowSize, kDummyWindowSize)); win.position = new Rect(-kDummyWindowSize / 2, -kDummyWindowSize / 2, kDummyWindowSize, kDummyWindowSize); instance.wantsMouseMove = true; instance.StealMouseCapture(); - if (stealFocus) - instance.Focus(); } public static void End() diff --git a/Editor/Mono/GUI/CreateAssetUtility.cs b/Editor/Mono/GUI/CreateAssetUtility.cs deleted file mode 100644 index c33f28754c..0000000000 --- a/Editor/Mono/GUI/CreateAssetUtility.cs +++ /dev/null @@ -1,125 +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.IO; -using UnityEditor.ProjectWindowCallback; -using UnityEngine; - - -namespace UnityEditor -{ - [System.Serializable] - internal class CreateAssetUtility - { - [SerializeField] - EndNameEditAction m_EndAction; - [SerializeField] - int m_InstanceID; - [SerializeField] - string m_Path = ""; - [SerializeField] - Texture2D m_Icon; - [SerializeField] - string m_ResourceFile; - - public void Clear() - { - m_EndAction = null; - m_InstanceID = 0; - m_Path = ""; - m_Icon = null; - m_ResourceFile = ""; - } - - public int instanceID - { - get { return m_InstanceID; } - } - - public Texture2D icon - { - get { return m_Icon; } - } - - public string folder - { - get { return Path.GetDirectoryName(m_Path); } - } - - public string extension - { - get { return Path.GetExtension(m_Path); } - } - - public string originalName - { - get { return Path.GetFileNameWithoutExtension(m_Path); } - } - - public EndNameEditAction endAction - { - get { return m_EndAction; } - } - - static bool IsPathDataValid(string filePath) - { - // Ensure some path - if (string.IsNullOrEmpty(filePath)) - return false; - - // Ensure valid folder to place the asset in - string folder = Path.GetDirectoryName(filePath); - int instanceID = AssetDatabase.GetMainAssetInstanceID(folder); - return instanceID != 0; - } - - // Selection changes when calling BeginNewAsset if it succeeds - public bool BeginNewAssetCreation(int instanceID, EndNameEditAction newAssetEndAction, string filePath, Texture2D icon, string newAssetResourceFile) - { - string uniquePath; - if (!filePath.StartsWith("assets/", System.StringComparison.CurrentCultureIgnoreCase)) - { - uniquePath = AssetDatabase.GetUniquePathNameAtSelectedPath(filePath); - } - else - { - uniquePath = AssetDatabase.GenerateUniqueAssetPath(filePath); - } - - if (!IsPathDataValid(uniquePath)) - { - Debug.LogErrorFormat("Invalid generated unique path '{0}' (input path '{1}')", uniquePath, filePath); - Clear(); - return false; - } - - m_InstanceID = instanceID; - m_Path = uniquePath; - m_Icon = icon; - m_EndAction = newAssetEndAction; - m_ResourceFile = newAssetResourceFile; - - // Change selection to none or instanceID - Selection.activeObject = EditorUtility.InstanceIDToObject(instanceID); - return true; - } - - // The asset is created here - public void EndNewAssetCreation(string name) - { - string path = folder + "/" + name + extension; - EndNameEditAction endAction = m_EndAction; - int instanceID = m_InstanceID; - string resourceFile = m_ResourceFile; - Clear(); // Ensure clear if anything goes bad in EndNameEditAction and gui is exited. - - ProjectWindowUtil.EndNameEditAction(endAction, instanceID, path, resourceFile); - } - - public bool IsCreatingNewAsset() - { - return !string.IsNullOrEmpty(m_Path); - } - } -} // end namespace UnityEditor diff --git a/Editor/Mono/GUI/DockArea.cs b/Editor/Mono/GUI/DockArea.cs index e64688792e..fad669b4b6 100644 --- a/Editor/Mono/GUI/DockArea.cs +++ b/Editor/Mono/GUI/DockArea.cs @@ -82,14 +82,16 @@ private static class Styles public int selected { get { return m_Selected; } - set - { - if (m_Selected != value) - m_LastSelected = m_Selected; - m_Selected = value; - if (m_Selected >= 0 && m_Selected < m_Panes.Count) - actualView = m_Panes[m_Selected]; - } + set { SetSelectedPrivate(value, sendEvents: true); } + } + + private void SetSelectedPrivate(int value, bool sendEvents) + { + if (m_Selected != value) + m_LastSelected = m_Selected; + m_Selected = value; + if (m_Selected >= 0 && m_Selected < m_Panes.Count) + SetActualViewInternal(m_Panes[m_Selected], sendEvents); } public DockArea() @@ -173,16 +175,16 @@ protected override void UpdateViewMargins(EditorWindow view) style.positionType = PositionType.Absolute; } - public void AddTab(EditorWindow pane) + public void AddTab(EditorWindow pane, bool sendPaneEvents = true) { - AddTab(m_Panes.Count, pane); + AddTab(m_Panes.Count, pane, sendPaneEvents); } - public void AddTab(int idx, EditorWindow pane) + public void AddTab(int idx, EditorWindow pane, bool sendPaneEvents = true) { - DeregisterSelectedPane(true); + DeregisterSelectedPane(clearActualView: true, sendEvents: true); m_Panes.Insert(idx, pane); - selected = idx; + SetSelectedPrivate(idx, sendPaneEvents); s_GUIContents.Clear(); var sp = parent as SplitView; @@ -192,11 +194,11 @@ public void AddTab(int idx, EditorWindow pane) Repaint(); } - public void RemoveTab(EditorWindow pane) { RemoveTab(pane, true); } - public void RemoveTab(EditorWindow pane, bool killIfEmpty) + public void RemoveTab(EditorWindow pane) { RemoveTab(pane, killIfEmpty: true); } + public void RemoveTab(EditorWindow pane, bool killIfEmpty, bool sendEvents = true) { if (actualView == pane) - DeregisterSelectedPane(true); + DeregisterSelectedPane(clearActualView: true, sendEvents: sendEvents); int idx = m_Panes.IndexOf(pane); if (idx == -1) return; // Pane is not in the window @@ -222,7 +224,7 @@ public void RemoveTab(EditorWindow pane, bool killIfEmpty) pane.m_Parent = null; if (killIfEmpty) KillIfEmpty(); - RegisterSelectedPane(); + RegisterSelectedPane(sendEvents: true); } private void KillIfEmpty() @@ -279,9 +281,10 @@ public DropInfo DragOver(EditorWindow window, Vector2 mouseScreenPosition) public bool PerformDrop(EditorWindow w, DropInfo info, Vector2 screenPos) { - s_OriginalDragSource.RemoveTab(w, s_OriginalDragSource != this); + // Don't send focus events to the tab being moved + s_OriginalDragSource.RemoveTab(w, killIfEmpty: s_OriginalDragSource != this, sendEvents: false); int tabInsertIndex = s_PlaceholderPos == -1 || s_PlaceholderPos > m_Panes.Count ? m_Panes.Count : s_PlaceholderPos; - AddTab(tabInsertIndex, w); + AddTab(tabInsertIndex, w, sendPaneEvents: false); selected = tabInsertIndex; return true; } @@ -891,7 +894,9 @@ private float DragTab(Rect tabAreaRect, float scrollOffset, GUIStyle tabStyle) ResetDragVars(); - RemoveTab(w); + // The active tab that we're moving to the new window stays focused at all times. + // Do not remove focus from the tab being detached. + RemoveTab(w, killIfEmpty: true, sendEvents: false); Rect wPos = w.position; wPos.x = screenMousePos.x - wPos.width * .5f; wPos.y = screenMousePos.y - wPos.height * .5f; @@ -900,7 +905,8 @@ private float DragTab(Rect tabAreaRect, float scrollOffset, GUIStyle tabStyle) if (Application.platform == RuntimePlatform.WindowsEditor) wPos.y = Mathf.Max(InternalEditorUtility.GetBoundsOfDesktopAtPoint(screenMousePos).y, wPos.y); - EditorWindow.CreateNewWindowForEditorWindow(w, false, false); + // Don't call OnFocus on the tab when it is moved to the new window + EditorWindow.CreateNewWindowForEditorWindow(w, loadPosition: false, showImmediately: false, setFocus: false); w.position = w.m_Parent.window.FitWindowRectToScreen(wPos, true, true); diff --git a/Editor/Mono/GUI/DragRect.cs b/Editor/Mono/GUI/DragRect.cs deleted file mode 100644 index 76c2387805..0000000000 --- a/Editor/Mono/GUI/DragRect.cs +++ /dev/null @@ -1,66 +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 UnityEditor; - -namespace UnityEditor -{ - class DragRectGUI - { - static int dragRectHash = "DragRect".GetHashCode(); - static int s_DragCandidateState = 0; - static float s_DragSensitivity = 1.0f; - - public static int DragRect(Rect position, int value, int minValue, int maxValue) - { - Event evt = Event.current; - - int id = GUIUtility.GetControlID(dragRectHash, FocusType.Passive, position); - - switch (evt.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (position.Contains(evt.mousePosition) && evt.button == 0) - { - GUIUtility.hotControl = id; - s_DragCandidateState = 1; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && s_DragCandidateState != 0) - { - GUIUtility.hotControl = 0; - s_DragCandidateState = 0; - evt.Use(); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - switch (s_DragCandidateState) - { - case 1: - value += (int)(HandleUtility.niceMouseDelta * s_DragSensitivity); - GUI.changed = true; - evt.Use(); - - if (value < minValue) - value = minValue; - else if (value > maxValue) - value = maxValue; - break; - } - } - break; - case EventType.Repaint: - EditorGUIUtility.AddCursorRect(position, MouseCursor.SlideArrow); - break; - } - - return value; - } - } -} diff --git a/Editor/Mono/GUI/EditorApplicationLayout.cs b/Editor/Mono/GUI/EditorApplicationLayout.cs deleted file mode 100644 index 4277a830c6..0000000000 --- a/Editor/Mono/GUI/EditorApplicationLayout.cs +++ /dev/null @@ -1,93 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.IO; -using UnityEditorInternal; - -// Description: -// EditorApplicationLayout handles the GUI when playmode changes (on a high level). - -// When entering playmode the flow is as follows (also see Application::SetIsPlaying() for actual loading): -// 1) Calling InitPlaymodeLayout prepares the main gameView WITHOUT rendering it. Sets it up, maximizes it if needed and intitializes its size. -// 2) The current scene is loaded from Application.cp and initialized (Awake(), OnEnable(), Start() and first Update() is called (this takes time for large projects)) -// 3) Calling FinalizePlaymodeLayout finalizes and renders maximized window (if set). - - -namespace UnityEditor -{ - internal class EditorApplicationLayout - { - static private GameView m_GameView = null; - static private bool m_MaximizePending = false; - - - static internal bool IsInitializingPlaymodeLayout() - { - return m_GameView != null; - } - - static internal void SetPlaymodeLayout() - { - InitPlaymodeLayout(); - FinalizePlaymodeLayout(); - } - - static internal void SetStopmodeLayout() - { - WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(false); - Toolbar.RepaintToolbar(); - } - - static internal void SetPausemodeLayout() - { - // We use the stopmode layout when pausing (maximized windows are unmaximized) - SetStopmodeLayout(); - } - - static internal void InitPlaymodeLayout() - { - m_GameView = WindowLayout.ShowAppropriateViewOnEnterExitPlaymode(true) as GameView; - if (m_GameView == null) - return; - - if (m_GameView.maximizeOnPlay) - { - DockArea da = m_GameView.m_Parent as DockArea; - - if (da != null) - m_MaximizePending = WindowLayout.MaximizePrepare(da.actualView); - } - - // Mark this game view as the start gameview so the backend - // can set size and mouseoffset properly for this game view - m_GameView.m_Parent.SetAsStartView(); - - Toolbar.RepaintToolbar(); - } - - static internal void FinalizePlaymodeLayout() - { - if (m_GameView != null) - { - if (m_MaximizePending) - WindowLayout.MaximizePresent(m_GameView); - - m_GameView.m_Parent.ClearStartView(); - } - - Clear(); - } - - static private void Clear() - { - m_MaximizePending = false; - m_GameView = null; - } - } -} // namespace diff --git a/Editor/Mono/GUI/EditorGUIContents.cs b/Editor/Mono/GUI/EditorGUIContents.cs deleted file mode 100644 index a38d282d45..0000000000 --- a/Editor/Mono/GUI/EditorGUIContents.cs +++ /dev/null @@ -1,58 +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 System.Reflection; - -namespace UnityEditor -{ - public sealed partial class EditorGUI - { - // Common GUIContents used for EditorGUI controls. - internal sealed class GUIContents - { - // The settings dropdown icon top right in a component - [IconName("_Popup")] - internal static GUIContent titleSettingsIcon { get; private set; } - - // The help icon in a component - [IconName("_Help")] - internal static GUIContent helpIcon { get; private set; } - - // We use a static constructor to lazily initialize all static properties. This is useful because changed image files can then - // be picked up on assembly reload. - static GUIContents() - { - // Run through each static property and initialize it using the - // filename provided in the IconName Attribute. - PropertyInfo[] propertyInfos = typeof(GUIContents).GetProperties(System.Reflection.BindingFlags.Static | BindingFlags.NonPublic); - foreach (PropertyInfo property in propertyInfos) - { - IconName[] iconNames = (IconName[])property.GetCustomAttributes(typeof(IconName), false); - if (iconNames.Length > 0) - { - string name = iconNames[0].name; - GUIContent content = EditorGUIUtility.IconContent(name); - property.SetValue(null, content, null); - } - } - } - - private class IconName : System.Attribute - { - private string m_Name; - - public IconName(string name) - { - this.m_Name = name; - } - - public virtual string name - { - get { return m_Name; } - } - } - } - } -} diff --git a/Editor/Mono/GUI/EditorUpdateWindow.cs b/Editor/Mono/GUI/EditorUpdateWindow.cs deleted file mode 100644 index 7ac2dcbe92..0000000000 --- a/Editor/Mono/GUI/EditorUpdateWindow.cs +++ /dev/null @@ -1,148 +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 System.Collections; -using UnityEditor; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class EditorUpdateWindow : EditorWindow - { - static void ShowEditorErrorWindow(string errorString) - { - LoadResources(); - - EditorUpdateWindow w = ShowWindow(); - - w.s_ErrorString = errorString; - w.s_HasConnectionError = true; - w.s_HasUpdate = false; - } - - static void ShowEditorUpdateWindow(string latestVersionString, string latestVersionMessage, string updateURL) - { - LoadResources(); - - EditorUpdateWindow w = ShowWindow(); - - w.s_LatestVersionString = latestVersionString; - w.s_LatestVersionMessage = latestVersionMessage; - w.s_UpdateURL = updateURL; - w.s_HasConnectionError = false; - w.s_HasUpdate = updateURL.Length > 0; - } - - private static EditorUpdateWindow ShowWindow() - { - return EditorWindow.GetWindowWithRect(typeof(EditorUpdateWindow), new Rect(100, 100, 570, 400), true, s_Title.text) as EditorUpdateWindow; - } - - private static GUIContent s_UnityLogo; - private static GUIContent s_Title; - private static GUIContent s_TextHasUpdate, s_TextUpToDate; - private static GUIContent s_CheckForNewUpdatesText; - - [SerializeField] - private string s_ErrorString; - - [SerializeField] - private string s_LatestVersionString; - - [SerializeField] - private string s_LatestVersionMessage; - - [SerializeField] - private string s_UpdateURL; - - [SerializeField] - private bool s_HasUpdate; - - [SerializeField] - private bool s_HasConnectionError; - - private static bool s_ShowAtStartup; - private Vector2 m_ScrollPos; - - private static void LoadResources() - { - if (s_UnityLogo != null) - return; - - s_ShowAtStartup = EditorPrefs.GetBool("EditorUpdateShowAtStartup", true); - - s_Title = EditorGUIUtility.TrTextContent("Unity Editor Update Check"); - - s_UnityLogo = EditorGUIUtility.IconContent("UnityLogo"); - s_TextHasUpdate = EditorGUIUtility.TrTextContent("There is a new version of the Unity Editor available for download.\n\nCurrently installed version is {0}\nNew version is {1}"); - s_TextUpToDate = EditorGUIUtility.TrTextContent("The Unity Editor is up to date. Currently installed version is {0}"); - - s_CheckForNewUpdatesText = EditorGUIUtility.TrTextContent("Check for Updates"); - } - - public void OnGUI() - { - LoadResources(); - - - GUILayout.BeginVertical(); - GUILayout.Space(10); - GUI.Box(new Rect(13, 8, s_UnityLogo.image.width, s_UnityLogo.image.height), s_UnityLogo, GUIStyle.none); - GUILayout.Space(5); - GUILayout.BeginHorizontal(); - GUILayout.Space(120); - GUILayout.BeginVertical(); - - if (s_HasConnectionError) - { - GUILayout.Label(s_ErrorString, "WordWrappedLabel", GUILayout.Width(405)); - } - else if (s_HasUpdate) - { - GUILayout.Label(string.Format(s_TextHasUpdate.text, InternalEditorUtility.GetFullUnityVersion(), s_LatestVersionString), "WordWrappedLabel", GUILayout.Width(300)); - - GUILayout.Space(20); - m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos, GUILayout.Width(405), GUILayout.Height(200)); - GUILayout.Label(s_LatestVersionMessage, "WordWrappedLabel"); - EditorGUILayout.EndScrollView(); - - GUILayout.Space(20); - GUILayout.BeginHorizontal(); - if (GUILayout.Button("Download new version", GUILayout.Width(200))) - Help.BrowseURL(s_UpdateURL); - - if (GUILayout.Button("Skip new version", GUILayout.Width(200))) - { - EditorPrefs.SetString("EditorUpdateSkipVersionString", s_LatestVersionString); - Close(); - } - GUILayout.EndHorizontal(); - } - else - { - GUILayout.Label(string.Format(s_TextUpToDate.text, Application.unityVersion), "WordWrappedLabel", GUILayout.Width(405)); - } - - - GUILayout.EndVertical(); - GUILayout.EndHorizontal(); - - GUILayout.Space(8); - - - GUILayout.FlexibleSpace(); - GUILayout.BeginHorizontal(GUILayout.Height(20)); - GUILayout.FlexibleSpace(); - GUI.changed = false; - s_ShowAtStartup = GUILayout.Toggle(s_ShowAtStartup, s_CheckForNewUpdatesText); - if (GUI.changed) - EditorPrefs.SetBool("EditorUpdateShowAtStartup", s_ShowAtStartup); - - GUILayout.Space(10); - GUILayout.EndHorizontal(); - GUILayout.EndVertical(); - } - } -} // namespace diff --git a/Editor/Mono/GUI/ExposablePopupMenu.cs b/Editor/Mono/GUI/ExposablePopupMenu.cs deleted file mode 100644 index 3a972a2511..0000000000 --- a/Editor/Mono/GUI/ExposablePopupMenu.cs +++ /dev/null @@ -1,165 +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.Collections.Generic; -using System.Linq; -using System.IO; - -using UnityEditorInternal; -using UnityEngine; - - -namespace UnityEditor -{ - internal class ExposablePopupMenu - { - public class ItemData - { - public ItemData(GUIContent content, GUIStyle style, bool on, bool enabled, object userData) - { - m_GUIContent = content; - m_Style = style; - m_On = on; - m_Enabled = enabled; - m_UserData = userData; - } - - public GUIContent m_GUIContent; - public GUIStyle m_Style; - public bool m_On; - public bool m_Enabled; - public object m_UserData; - public float m_Width; - } - - public class PopupButtonData - { - public PopupButtonData(GUIContent content, GUIStyle style) - { - m_GUIContent = content; - m_Style = style; - } - - public GUIContent m_GUIContent; - public GUIStyle m_Style; - } - - List m_Items; - float m_WidthOfButtons; - float m_ItemSpacing; - PopupButtonData m_PopupButtonData; - float m_WidthOfPopup; - float m_MinWidthOfPopup; - System.Action m_SelectionChangedCallback = null; // - - public void Init(List items, float itemSpacing, float minWidthOfPopup, PopupButtonData popupButtonData, System.Action selectionChangedCallback) - { - m_Items = items; - m_ItemSpacing = itemSpacing; - m_PopupButtonData = popupButtonData; - m_SelectionChangedCallback = selectionChangedCallback; - m_MinWidthOfPopup = minWidthOfPopup; - CalcWidths(); - } - - public float OnGUI(Rect rect) - { - if (rect.width >= m_WidthOfButtons && rect.width > m_MinWidthOfPopup) - { - Rect buttonRect = rect; - - // Show as buttons - foreach (var item in m_Items) - { - buttonRect.width = item.m_Width; - - EditorGUI.BeginChangeCheck(); - - using (new EditorGUI.DisabledScope(!item.m_Enabled)) - { - GUI.Toggle(buttonRect, item.m_On, item.m_GUIContent, item.m_Style); - } - - if (EditorGUI.EndChangeCheck()) - { - SelectionChanged(item); - GUIUtility.ExitGUI(); // To make sure we can survive if m_Buttons are reallocated in the callback we exit gui - } - - buttonRect.x += item.m_Width + m_ItemSpacing; - } - - return m_WidthOfButtons; - } - else - { - // Show as popup - if (m_WidthOfPopup < rect.width) - rect.width = m_WidthOfPopup; - - //if (GUI.Button (rect, m_PopupButtonData.m_GUIContent, m_PopupButtonData.m_Style)) - if (EditorGUI.DropdownButton(rect, m_PopupButtonData.m_GUIContent, FocusType.Passive, m_PopupButtonData.m_Style)) - PopUpMenu.Show(rect, m_Items, this); - - return m_WidthOfPopup; - } - } - - void CalcWidths() - { - // Buttons - m_WidthOfButtons = 0f; - foreach (var item in m_Items) - { - item.m_Width = item.m_Style.CalcSize(item.m_GUIContent).x; - m_WidthOfButtons += item.m_Width; - } - m_WidthOfButtons += (m_Items.Count - 1) * m_ItemSpacing; - - // Popup - Vector2 size = m_PopupButtonData.m_Style.CalcSize(m_PopupButtonData.m_GUIContent); - size.x += 3f; // more space between text and arrow - m_WidthOfPopup = size.x; - } - - void SelectionChanged(ItemData item) - { - if (m_SelectionChangedCallback != null) - m_SelectionChangedCallback(item); - else - Debug.LogError("Callback is null"); - } - - internal class PopUpMenu - { - static List m_Data; - static ExposablePopupMenu m_Caller; - - static internal void Show(Rect activatorRect, List buttonData, ExposablePopupMenu caller) - { - m_Data = buttonData; - m_Caller = caller; - - GenericMenu menu = new GenericMenu(); - foreach (ItemData item in m_Data) - if (item.m_Enabled) - menu.AddItem(item.m_GUIContent, item.m_On, SelectionCallback, item); - else - menu.AddDisabledItem(item.m_GUIContent); - - menu.DropDown(activatorRect); - } - - static void SelectionCallback(object userData) - { - ItemData item = (ItemData)userData; - m_Caller.SelectionChanged(item); - - // Cleanup - m_Caller = null; - m_Data = null; - } - } - } -} // end namespace UnityEditor diff --git a/Editor/Mono/GUI/FallbackEditorWindow.cs b/Editor/Mono/GUI/FallbackEditorWindow.cs deleted file mode 100644 index 67be923855..0000000000 --- a/Editor/Mono/GUI/FallbackEditorWindow.cs +++ /dev/null @@ -1,38 +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 UnityEditor; -using System.Collections; -using System.Reflection; - -namespace UnityEditor -{ - internal class FallbackEditorWindow : EditorWindow - { - FallbackEditorWindow() - { - } - - void OnEnable() - { - titleContent = EditorGUIUtility.TrTextContent("Failed to load"); - } - - void OnGUI() - { - GUILayout.BeginVertical(); - GUILayout.FlexibleSpace(); - - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - GUILayout.Label("EditorWindow could not be loaded because the script is not found in the project", "WordWrapLabel"); - GUILayout.FlexibleSpace(); - GUILayout.EndHorizontal(); - - GUILayout.FlexibleSpace(); - GUILayout.EndVertical(); - } - } -} // namespace diff --git a/Editor/Mono/GUI/FlexibleMenu/FlexibleMenu.cs b/Editor/Mono/GUI/FlexibleMenu/FlexibleMenu.cs index b060fcdea7..8cdfc53eb2 100644 --- a/Editor/Mono/GUI/FlexibleMenu/FlexibleMenu.cs +++ b/Editor/Mono/GUI/FlexibleMenu/FlexibleMenu.cs @@ -243,7 +243,7 @@ void CreateNewItemButton(Rect itemRect) SelectItem(newIndex); EditorApplication.RequestRepaintAllViews(); // We want to repaint the flexible menu (currently in modifyItemUI) }); - PopupWindow.Show(plusRect, m_ModifyItemUI, null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(plusRect, m_ModifyItemUI); } } @@ -261,7 +261,7 @@ void EditExistingItem(Rect itemRect, int index) m_ItemProvider.Replace(index, obj); EditorApplication.RequestRepaintAllViews(); // We want to repaint the flexible menu (currently in modifyItemUI) }); - PopupWindow.Show(itemRect, m_ModifyItemUI, null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(itemRect, m_ModifyItemUI); } void DeleteItem(int index) diff --git a/Editor/Mono/GUI/FlexibleMenu/FlexibleMenuModifyItemUI.cs b/Editor/Mono/GUI/FlexibleMenu/FlexibleMenuModifyItemUI.cs deleted file mode 100644 index 5f88d5e77f..0000000000 --- a/Editor/Mono/GUI/FlexibleMenu/FlexibleMenuModifyItemUI.cs +++ /dev/null @@ -1,47 +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 System; - -namespace UnityEditor -{ - abstract class FlexibleMenuModifyItemUI : PopupWindowContent - { - public enum MenuType { Add, Edit }; - protected MenuType m_MenuType; - public object m_Object; - protected Action m_AcceptedCallback; - private bool m_IsInitialized; - - public override void OnClose() - { - m_Object = null; - m_AcceptedCallback = null; - m_IsInitialized = false; - EditorApplication.RequestRepaintAllViews(); // When closed ensure FlexibileMenu gets repainted so hover can be removed - } - - public void Init(MenuType menuType, object obj, Action acceptedCallback) - { - m_MenuType = menuType; - m_Object = obj; - m_AcceptedCallback = acceptedCallback; - m_IsInitialized = true; - } - - public void Accepted() - { - if (m_AcceptedCallback != null) - m_AcceptedCallback(m_Object); - else - Debug.LogError("Missing callback. Did you remember to call Init ?"); - } - - public bool IsShowing() - { - return m_IsInitialized; - } - } -} // namespace diff --git a/Editor/Mono/GUI/FlexibleMenu/IFlexibleMenuItemProvider.cs b/Editor/Mono/GUI/FlexibleMenu/IFlexibleMenuItemProvider.cs deleted file mode 100644 index 056193f706..0000000000 --- a/Editor/Mono/GUI/FlexibleMenu/IFlexibleMenuItemProvider.cs +++ /dev/null @@ -1,20 +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 -{ - interface IFlexibleMenuItemProvider - { - int Count(); - object GetItem(int index); - int Add(object obj); - void Replace(int index, object newPresetObject); - void Remove(int index); - object Create(); - void Move(int index, int destIndex, bool insertAfterDestIndex); - string GetName(int index); - bool IsModificationAllowed(int index); - int[] GetSeperatorIndices(); - } -} diff --git a/Editor/Mono/GUI/FlowLayout.cs b/Editor/Mono/GUI/FlowLayout.cs deleted file mode 100644 index b63403b9bc..0000000000 --- a/Editor/Mono/GUI/FlowLayout.cs +++ /dev/null @@ -1,327 +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 UnityEditor; -using System.Collections.Generic; -using System.Collections; -using System.Reflection; -using UnityEditorInternal; - - -namespace UnityEditor -{ - class FlowLayout : GUILayoutGroup - { - struct LineInfo - { - public float minSize, maxSize; - public float start, size; - public int topBorder, bottomBorder; - } - - int m_Lines; - LineInfo[] m_LineInfo; - - public override void CalcWidth() - { - bool hasMinWidth = minWidth != 0; - - base.CalcWidth(); - - if (isVertical) - { - // DONT - } - else - { - // Margin handling is somewhat different from other controls. - // Since we don't know what will wrap where we'll just take the Min margin of all child elements - if (!hasMinWidth) - { - minWidth = 0; - foreach (GUILayoutEntry i in entries) - { - // Here we should probably include margins of the element, but that does seem kind of annoying - minWidth = Mathf.Max(m_ChildMinWidth, i.minWidth); - } - } - } - } - - public override void SetHorizontal(float x, float width) - { - // Apply the base. Now everything is in one line (or column), and all we need is to insert the linebreaks - base.SetHorizontal(x, width); - - if (resetCoords) - x = 0; - - if (isVertical) - { - Debug.LogError("Wordwrapped vertical group. Don't. Just Don't"); - } - else - { // we're horizontally laid out: - // apply margins/padding here - // If we have a style, adjust the sizing to take care of padding (if we don't the horizontal margins have been propagated fully up the hierarchy)... - - // Set the positions - m_Lines = 0; - float pulledOffset = 0; // How far we need to pull each item back. - foreach (GUILayoutEntry i in entries) - { - if (i.rect.xMax - pulledOffset > x + width) - { - // TODO: When we move a line back, we should re-expand - pulledOffset = i.rect.x - i.margin.left; - m_Lines++; - } - i.SetHorizontal(i.rect.x - pulledOffset, i.rect.width); - i.rect.y = m_Lines; - } - m_Lines++; - } - } - - public override void CalcHeight() - { - if (entries.Count == 0) - { - maxHeight = minHeight = 0; - return; - } - m_ChildMinHeight = m_ChildMaxHeight = 0; - int _topMarginMin = 0, _bottomMarginMin = 0; - m_StretchableCountY = 0; - if (isVertical) - { - } - else - { - m_LineInfo = new LineInfo[m_Lines]; - for (int i = 0; i < m_Lines; i++) - { - m_LineInfo[i].topBorder = 10000; - m_LineInfo[i].bottomBorder = 10000; - } - - // Figure out border values for each line - foreach (GUILayoutEntry i in entries) - { - i.CalcHeight(); - int j = (int)i.rect.y; - m_LineInfo[j].minSize = Mathf.Max(i.minHeight, m_LineInfo[j].minSize); - m_LineInfo[j].maxSize = Mathf.Max(i.maxHeight, m_LineInfo[j].maxSize); - m_LineInfo[j].topBorder = Mathf.Min(i.margin.top, m_LineInfo[j].topBorder); - m_LineInfo[j].bottomBorder = Mathf.Min(i.margin.bottom, m_LineInfo[j].bottomBorder); - } - - for (int i = 0; i < m_Lines; i++) - { - m_ChildMinHeight += m_LineInfo[i].minSize; - m_ChildMaxHeight += m_LineInfo[i].maxSize; - } - - // Add in the the extra lines - for (int i = 1; i < m_Lines; i++) - { - float space = Mathf.Max(m_LineInfo[i - 1].bottomBorder, m_LineInfo[i].topBorder); - m_ChildMinHeight += space; - m_ChildMaxHeight += space; - } - _topMarginMin = m_LineInfo[0].topBorder; - _bottomMarginMin = m_LineInfo[m_LineInfo.Length - 1].bottomBorder; - } - - // Do the dance between children & parent for haggling over how many empty pixels to have - float firstPadding, lastPadding; - - margin.top = _topMarginMin; - margin.bottom = _bottomMarginMin; - firstPadding = lastPadding = 0; - - minHeight = Mathf.Max(minHeight, m_ChildMinHeight + firstPadding + lastPadding); - if (maxHeight == 0) - { - stretchHeight += m_StretchableCountY + (style.stretchHeight ? 1 : 0); - maxHeight = m_ChildMaxHeight + firstPadding + lastPadding; - } - else - { - stretchHeight = 0; - } - maxHeight = Mathf.Max(maxHeight, minHeight); - } - - public override void SetVertical(float y, float height) - { - if (entries.Count == 0) - { - base.SetVertical(y, height); - return; - } - - if (isVertical) - { - base.SetVertical(y, height); - } - else - { - if (resetCoords) - y = 0; - - float clientY, clientHeight; - clientY = y - margin.top; - clientHeight = y + margin.vertical; - - // Figure out how to distribute the elements between the different lines - float heightToDistribute = clientHeight - spacing * (m_Lines - 1); - float minMaxScale = 0; - if (m_ChildMinHeight != m_ChildMaxHeight) - minMaxScale = Mathf.Clamp((heightToDistribute - m_ChildMinHeight) / (m_ChildMaxHeight - m_ChildMinHeight), 0, 1); - - float lineY = clientY; - for (int i = 0; i < m_Lines; i++) - { - if (i > 0) - lineY += Mathf.Max(m_LineInfo[i].topBorder, m_LineInfo[i - 1].bottomBorder); - m_LineInfo[i].start = lineY; - m_LineInfo[i].size = Mathf.Lerp(m_LineInfo[i].minSize, m_LineInfo[i].maxSize, minMaxScale); - lineY += m_LineInfo[i].size + spacing; - } - - - foreach (GUILayoutEntry i in entries) - { - LineInfo li = m_LineInfo[(int)i.rect.y]; - if (i.stretchHeight != 0) - i.SetVertical(li.start + i.margin.top, li.size - i.margin.vertical); - else - i.SetVertical(li.start + i.margin.top, Mathf.Clamp(li.size - i.margin.vertical, i.minHeight, i.maxHeight)); - } - } - } - } - - - // @TODO Make this serialize - // @TODO Handle animate-from nothing (with fade?) - // @TODO Figure out how to implement fade-away of contents - // @TODO Switch a bunch of others to use this - internal class GUISlideGroup - { - internal static GUISlideGroup current = null; - Dictionary animIDs = new Dictionary(); - const float kLerp = .1f; - const float kSnap = .5f; - - public void Begin() - { - if (current != null) - { - Debug.LogError("You cannot nest animGroups"); - return; - } - - current = this; - } - - public void End() - { - current = null; - } - - public void Reset() - { - current = null; - animIDs.Clear(); - } - - public Rect BeginHorizontal(int id, params GUILayoutOption[] options) - { - SlideGroupInternal g = (SlideGroupInternal)GUILayoutUtility.BeginLayoutGroup(GUIStyle.none, options, typeof(SlideGroupInternal)); - g.SetID(this, id); - g.isVertical = false; - return g.m_FinalRect; - } - - public void EndHorizontal() - { - GUILayoutUtility.EndLayoutGroup(); - } - - public Rect GetRect(int id, Rect r) - { - bool dummy; - if (Event.current.type != EventType.Repaint) - return r; - return GetRect(id, r, out dummy); - } - - Rect GetRect(int id, Rect r, out bool changed) - { - if (!animIDs.ContainsKey(id)) - { - animIDs.Add(id, r); - changed = false; - return r; - } - - Rect current = animIDs[id]; - if (current.y != r.y || current.height != r.height || current.x != r.x || current.width != r.width) - { - float lerp = kLerp; - if (Mathf.Abs(current.y - r.y) > kSnap) - r.y = Mathf.Lerp(current.y, r.y, lerp); - if (Mathf.Abs(current.height - r.height) > kSnap) - r.height = Mathf.Lerp(current.height, r.height, lerp); - if (Mathf.Abs(current.x - r.x) > kSnap) - r.x = Mathf.Lerp(current.x, r.x, lerp); - if (Mathf.Abs(current.width - r.width) > kSnap) - r.width = Mathf.Lerp(current.width, r.width, lerp); - animIDs[id] = r; - changed = true; - HandleUtility.Repaint(); - } - else - changed = false; - return r; - } - - class SlideGroupInternal : GUILayoutGroup - { - int m_ID; - GUISlideGroup m_Owner; -#pragma warning disable 649 - internal Rect m_FinalRect; - public void SetID(GUISlideGroup owner, int id) - { - m_ID = id; - m_Owner = owner; - } - - public override void SetHorizontal(float x, float width) - { - m_FinalRect.x = x; - m_FinalRect.width = width; - base.SetHorizontal(x, width); - } - - public override void SetVertical(float y, float height) - { - m_FinalRect.y = y; - m_FinalRect.height = height; - - Rect r = new Rect(rect.x, y, rect.width, height); - bool changed; - r = m_Owner.GetRect(m_ID, r, out changed); - - if (changed) - base.SetHorizontal(r.x, r.width); - base.SetVertical(r.y, r.height); - } - } - } -} // namespace diff --git a/Editor/Mono/GUI/GradientEditor.cs b/Editor/Mono/GUI/GradientEditor.cs deleted file mode 100644 index a72ac8f42d..0000000000 --- a/Editor/Mono/GUI/GradientEditor.cs +++ /dev/null @@ -1,605 +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 System.Collections.Generic; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class GradientEditor - { - class Styles - { - public GUIStyle upSwatch = "Grad Up Swatch"; - public GUIStyle upSwatchOverlay = "Grad Up Swatch Overlay"; - public GUIStyle downSwatch = "Grad Down Swatch"; - public GUIStyle downSwatchOverlay = "Grad Down Swatch Overlay"; - - public GUIContent modeText = EditorGUIUtility.TrTextContent("Mode"); - public GUIContent alphaText = EditorGUIUtility.TrTextContent("Alpha"); - public GUIContent colorText = EditorGUIUtility.TrTextContent("Color"); - public GUIContent locationText = EditorGUIUtility.TrTextContent("Location"); - public GUIContent percentText = new GUIContent("%"); - - static GUIStyle GetStyle(string name) - { - GUISkin s = (GUISkin)EditorGUIUtility.LoadRequired("GradientEditor.GUISkin"); - return s.GetStyle(name); - } - } - static Styles s_Styles; - static Texture2D s_BackgroundTexture; - - public class Swatch - { - public float m_Time; - public Color m_Value; - public bool m_IsAlpha; - - public Swatch(float time, Color value, bool isAlpha) - { - m_Time = time; - m_Value = value; - m_IsAlpha = isAlpha; - } - } - - const int k_MaxNumKeys = 8; - List m_RGBSwatches; - List m_AlphaSwatches; - GradientMode m_GradientMode; - [System.NonSerialized] - Swatch m_SelectedSwatch; - Gradient m_Gradient; - int m_NumSteps; - bool m_HDR; - - // Fixed steps are only used if numSteps > 1 - public void Init(Gradient gradient, int numSteps, bool hdr) - { - m_Gradient = gradient; - m_NumSteps = numSteps; - m_HDR = hdr; - - BuildArrays(); - - if (m_RGBSwatches.Count > 0) - m_SelectedSwatch = m_RGBSwatches[0]; - } - - public Gradient target - { - get { return m_Gradient; } - } - - float GetTime(float actualTime) - { - actualTime = Mathf.Clamp01(actualTime); - - if (m_NumSteps > 1) - { - float stepSize = 1.0f / (m_NumSteps - 1); - int step = Mathf.RoundToInt(actualTime / stepSize); - return step / (float)(m_NumSteps - 1); - } - - return actualTime; - } - - void BuildArrays() - { - if (m_Gradient == null) - return; - GradientColorKey[] colorKeys = m_Gradient.colorKeys; - m_RGBSwatches = new List(colorKeys.Length); - for (int i = 0; i < colorKeys.Length; i++) - { - Color color = colorKeys[i].color; - color.a = 1f; - m_RGBSwatches.Add(new Swatch(colorKeys[i].time, color, false)); - } - - GradientAlphaKey[] alphaKeys = m_Gradient.alphaKeys; - m_AlphaSwatches = new List(alphaKeys.Length); - for (int i = 0; i < alphaKeys.Length; i++) - { - float a = alphaKeys[i].alpha; - m_AlphaSwatches.Add(new Swatch(alphaKeys[i].time, new Color(a, a, a, 1), true)); - } - m_GradientMode = m_Gradient.mode; - } - - public static void DrawGradientWithBackground(Rect position, Gradient gradient) - { - Texture2D gradientTexture = UnityEditorInternal.GradientPreviewCache.GetGradientPreview(gradient); - Rect r2 = new Rect(position.x + 1, position.y + 1, position.width - 2, position.height - 2); - - // Background checkers - Texture2D backgroundTexture = GetBackgroundTexture(); - Rect texCoordsRect = new Rect(0, 0, r2.width / backgroundTexture.width, r2.height / backgroundTexture.height); - GUI.DrawTextureWithTexCoords(r2, backgroundTexture, texCoordsRect, false); - - // Gradient texture - if (gradientTexture != null) - GUI.DrawTexture(r2, gradientTexture, ScaleMode.StretchToFill, true); - - // Frame over texture - GUI.Label(position, GUIContent.none, EditorStyles.colorPickerBox); - - // HDR label - float maxColorComponent = GetMaxColorComponent(gradient); - if (maxColorComponent > 1.0f) - { - GUI.Label(new Rect(position.x, position.y, position.width - 3, position.height), "HDR", EditorStyles.centeredGreyMiniLabel); - } - } - - public void OnGUI(Rect position) - { - if (s_Styles == null) - s_Styles = new Styles(); - - float modeHeight = 24f; - float swatchHeight = 16f; - float editSectionHeight = 26f; - float gradientTextureHeight = position.height - 2 * swatchHeight - editSectionHeight - modeHeight; - - position.height = modeHeight; - m_GradientMode = (GradientMode)EditorGUI.EnumPopup(position, s_Styles.modeText, m_GradientMode); - if (m_GradientMode != m_Gradient.mode) - AssignBack(); - - position.y += modeHeight; - position.height = swatchHeight; - - // Alpha swatches (no idea why they're top, but that's what Adobe & Apple seem to agree on) - ShowSwatchArray(position, m_AlphaSwatches, true); - - // Gradient texture - position.y += swatchHeight; - if (Event.current.type == EventType.Repaint) - { - position.height = gradientTextureHeight; - DrawGradientWithBackground(position, m_Gradient); - } - position.y += gradientTextureHeight; - position.height = swatchHeight; - - // Color swatches (bottom) - ShowSwatchArray(position, m_RGBSwatches, false); - - if (m_SelectedSwatch != null) - { - position.y += swatchHeight; - position.height = editSectionHeight; - position.y += 10; - - float locationWidth = 45; - float locationTextWidth = 60; - float space = 20; - float alphaOrColorTextWidth = 50; - float totalLocationWidth = locationTextWidth + space + locationTextWidth + locationWidth; - - // Alpha or Color field - Rect rect = position; - rect.height = 18; - rect.x += 17; - rect.width -= totalLocationWidth; - EditorGUIUtility.labelWidth = alphaOrColorTextWidth; - if (m_SelectedSwatch.m_IsAlpha) - { - EditorGUIUtility.fieldWidth = 30; - EditorGUI.BeginChangeCheck(); - float sliderValue = EditorGUI.IntSlider(rect, s_Styles.alphaText, (int)(m_SelectedSwatch.m_Value.r * 255), 0, 255) / 255f; - if (EditorGUI.EndChangeCheck()) - { - sliderValue = Mathf.Clamp01(sliderValue); - m_SelectedSwatch.m_Value.r = m_SelectedSwatch.m_Value.g = m_SelectedSwatch.m_Value.b = sliderValue; - AssignBack(); - HandleUtility.Repaint(); - } - } - else - { - EditorGUI.BeginChangeCheck(); - m_SelectedSwatch.m_Value = EditorGUI.ColorField(rect, s_Styles.colorText, m_SelectedSwatch.m_Value, true, false, m_HDR); - if (EditorGUI.EndChangeCheck()) - { - AssignBack(); - HandleUtility.Repaint(); - } - } - - // Location of key - rect.x += rect.width + space; - rect.width = locationWidth + locationTextWidth; - - EditorGUIUtility.labelWidth = locationTextWidth; - string orgFormatString = EditorGUI.kFloatFieldFormatString; - EditorGUI.kFloatFieldFormatString = "f1"; - - EditorGUI.BeginChangeCheck(); - float newLocation = EditorGUI.FloatField(rect, s_Styles.locationText, m_SelectedSwatch.m_Time * 100.0f) / 100.0f; - if (EditorGUI.EndChangeCheck()) - { - m_SelectedSwatch.m_Time = Mathf.Clamp(newLocation, 0f, 1f); - AssignBack(); - } - - EditorGUI.kFloatFieldFormatString = orgFormatString; - - rect.x += rect.width; - rect.width = 20; - GUI.Label(rect, s_Styles.percentText); - } - } - - void ShowSwatchArray(Rect position, List swatches, bool isAlpha) - { - int id = GUIUtility.GetControlID(652347689, FocusType.Passive); - Event evt = Event.current; - - float mouseSwatchTime = GetTime((Event.current.mousePosition.x - position.x) / position.width); - Vector2 fixedStepMousePosition = new Vector3(position.x + mouseSwatchTime * position.width, Event.current.mousePosition.y); - - switch (evt.GetTypeForControl(id)) - { - case EventType.Repaint: - { - bool hasSelection = false; - foreach (Swatch s in swatches) - { - if (m_SelectedSwatch == s) - { - hasSelection = true; - continue; - } - DrawSwatch(position, s, !isAlpha); - } - // selected swatch drawn last - if (hasSelection && m_SelectedSwatch != null) - DrawSwatch(position, m_SelectedSwatch, !isAlpha); - break; - } - case EventType.MouseDown: - { - Rect clickRect = position; - - // Swatches have some thickness thus we enlarge the clickable area - clickRect.xMin -= 10; - clickRect.xMax += 10; - if (clickRect.Contains(evt.mousePosition)) - { - GUIUtility.hotControl = id; - evt.Use(); - - // Make sure selected is topmost for the click - if (swatches.Contains(m_SelectedSwatch) && !m_SelectedSwatch.m_IsAlpha && CalcSwatchRect(position, m_SelectedSwatch).Contains(evt.mousePosition)) - { - if (evt.clickCount == 2) - { - GUIUtility.keyboardControl = id; - ColorPicker.Show(GUIView.current, m_SelectedSwatch.m_Value, false, m_HDR); - GUIUtility.ExitGUI(); - } - break; - } - - bool found = false; - foreach (Swatch s in swatches) - { - if (CalcSwatchRect(position, s).Contains(fixedStepMousePosition)) - { - found = true; - m_SelectedSwatch = s; - break; - } - } - - if (!found) - { - if (swatches.Count < k_MaxNumKeys) - { - Color currentColor = m_Gradient.Evaluate(mouseSwatchTime); - if (isAlpha) - currentColor = new Color(currentColor.a, currentColor.a, currentColor.a, 1f); - else - currentColor.a = 1f; - m_SelectedSwatch = new Swatch(mouseSwatchTime, currentColor, isAlpha); - swatches.Add(m_SelectedSwatch); - AssignBack(); - } - else - { - Debug.LogWarning("Max " + k_MaxNumKeys + " color keys and " + k_MaxNumKeys + " alpha keys are allowed in a gradient."); - } - } - } - break; - } - case EventType.MouseDrag: - - if (GUIUtility.hotControl == id && m_SelectedSwatch != null) - { - evt.Use(); - - // If user drags swatch outside in vertical direction, we'll remove the swatch - if ((evt.mousePosition.y + 5 < position.y || evt.mousePosition.y - 5 > position.yMax)) - { - if (swatches.Count > 1) - { - swatches.Remove(m_SelectedSwatch); - AssignBack(); - break; - } - } - else if (!swatches.Contains(m_SelectedSwatch)) - swatches.Add(m_SelectedSwatch); - - m_SelectedSwatch.m_Time = mouseSwatchTime; - AssignBack(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id) - { - GUIUtility.hotControl = 0; - evt.Use(); - - // If the dragged swatch is NOT in the timeline, it means it was dragged outside. - // We just forget about it and let GC get it later. - if (!swatches.Contains(m_SelectedSwatch)) - m_SelectedSwatch = null; - - // Remove duplicate keys on mouse up so that we do not kill any keys during the drag - RemoveDuplicateOverlappingSwatches(); - } - break; - - case EventType.KeyDown: - if (evt.keyCode == KeyCode.Delete) - { - if (m_SelectedSwatch != null) - { - List listToDeleteFrom; - if (m_SelectedSwatch.m_IsAlpha) - listToDeleteFrom = m_AlphaSwatches; - else - listToDeleteFrom = m_RGBSwatches; - - if (listToDeleteFrom.Count > 1) - { - listToDeleteFrom.Remove(m_SelectedSwatch); - AssignBack(); - HandleUtility.Repaint(); - } - } - evt.Use(); - } - break; - - case EventType.ValidateCommand: - if (evt.commandName == EventCommandNames.Delete) - Event.current.Use(); - break; - - case EventType.ExecuteCommand: - if (evt.commandName == EventCommandNames.ColorPickerChanged) - { - GUI.changed = true; - m_SelectedSwatch.m_Value = ColorPicker.color; - AssignBack(); - HandleUtility.Repaint(); - } - else if (evt.commandName == EventCommandNames.Delete) - { - if (swatches.Count > 1) - { - swatches.Remove(m_SelectedSwatch); - AssignBack(); - HandleUtility.Repaint(); - } - } - break; - } - } - - void DrawSwatch(Rect totalPos, Swatch s, bool upwards) - { - Color temp = GUI.backgroundColor; - Rect r = CalcSwatchRect(totalPos, s); - GUI.backgroundColor = s.m_Value; - GUIStyle back = upwards ? s_Styles.upSwatch : s_Styles.downSwatch; - GUIStyle overlay = upwards ? s_Styles.upSwatchOverlay : s_Styles.downSwatchOverlay; - back.Draw(r, false, false, m_SelectedSwatch == s, false); - GUI.backgroundColor = temp; - overlay.Draw(r, false, false, m_SelectedSwatch == s, false); - } - - Rect CalcSwatchRect(Rect totalRect, Swatch s) - { - float time = s.m_Time; - return new Rect(totalRect.x + Mathf.Round(totalRect.width * time) - 5, totalRect.y, 10, totalRect.height); - } - - int SwatchSort(Swatch lhs, Swatch rhs) - { - if (lhs.m_Time == rhs.m_Time && lhs == m_SelectedSwatch) - return -1; - if (lhs.m_Time == rhs.m_Time && rhs == m_SelectedSwatch) - return 1; - - return lhs.m_Time.CompareTo(rhs.m_Time); - } - - // Assign back all swatches, to target gradient. - void AssignBack() - { - m_RGBSwatches.Sort((a, b) => SwatchSort(a, b)); - GradientColorKey[] colorKeys = new GradientColorKey[m_RGBSwatches.Count]; - for (int i = 0; i < m_RGBSwatches.Count; i++) - { - colorKeys[i].color = m_RGBSwatches[i].m_Value; - colorKeys[i].time = m_RGBSwatches[i].m_Time; - } - - m_AlphaSwatches.Sort((a, b) => SwatchSort(a, b)); - GradientAlphaKey[] alphaKeys = new GradientAlphaKey[m_AlphaSwatches.Count]; - for (int i = 0; i < m_AlphaSwatches.Count; i++) - { - alphaKeys[i].alpha = m_AlphaSwatches[i].m_Value.r; // we use the red channel (see BuildArrays) - alphaKeys[i].time = m_AlphaSwatches[i].m_Time; - } - - m_Gradient.colorKeys = colorKeys; - m_Gradient.alphaKeys = alphaKeys; - m_Gradient.mode = m_GradientMode; - - GUI.changed = true; - } - - // Kill any swatches that are at the same time (For example as the result of dragging a swatch on top of another) - void RemoveDuplicateOverlappingSwatches() - { - bool didRemoveAny = false; - for (int i = 1; i < m_RGBSwatches.Count; i++) - { - if (Mathf.Approximately(m_RGBSwatches[i - 1].m_Time, m_RGBSwatches[i].m_Time)) - { - m_RGBSwatches.RemoveAt(i); - i--; - didRemoveAny = true; - } - } - - for (int i = 1; i < m_AlphaSwatches.Count; i++) - { - if (Mathf.Approximately(m_AlphaSwatches[i - 1].m_Time, m_AlphaSwatches[i].m_Time)) - { - m_AlphaSwatches.RemoveAt(i); - i--; - didRemoveAny = true; - } - } - - if (didRemoveAny) - AssignBack(); - } - - public static Texture2D GetBackgroundTexture() - { - if (s_BackgroundTexture == null) - s_BackgroundTexture = GradientEditor.CreateCheckerTexture(32, 4, 4, Color.white, new Color(0.7f, 0.7f, 0.7f)); - return s_BackgroundTexture; - } - - public static Texture2D CreateCheckerTexture(int numCols, int numRows, int cellPixelWidth, Color col1, Color col2) - { - int height = numRows * cellPixelWidth; - int width = numCols * cellPixelWidth; - - Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false); - texture.hideFlags = HideFlags.HideAndDontSave; - Color[] pixels = new Color[width * height]; - - for (int i = 0; i < numRows; i++) - for (int j = 0; j < numCols; j++) - for (int ci = 0; ci < cellPixelWidth; ci++) - for (int cj = 0; cj < cellPixelWidth; cj++) - pixels[(i * cellPixelWidth + ci) * width + j * cellPixelWidth + cj] = ((i + j) % 2 == 0) ? col1 : col2; - - texture.SetPixels(pixels); - texture.Apply(); - return texture; - } - - // GUI Helpers - public static void DrawGradientSwatch(Rect position, Gradient gradient, Color bgColor) - { - DrawGradientSwatchInternal(position, gradient, null, bgColor); - } - - public static void DrawGradientSwatch(Rect position, SerializedProperty property, Color bgColor) - { - DrawGradientSwatchInternal(position, null, property, bgColor); - } - - private static void DrawGradientSwatchInternal(Rect position, Gradient gradient, SerializedProperty property, Color bgColor) - { - if (Event.current.type != EventType.Repaint) - return; - - if (EditorGUI.showMixedValue) - { - Color oldColor = GUI.color; - float a = GUI.enabled ? 1 : 2; - - GUI.color = new Color(0.82f, 0.82f, 0.82f, a) * bgColor; - GUIStyle mgs = EditorGUIUtility.whiteTextureStyle; - mgs.Draw(position, false, false, false, false); - - EditorGUI.BeginHandleMixedValueContentColor(); - mgs.Draw(position, EditorGUI.mixedValueContent, false, false, false, false); - EditorGUI.EndHandleMixedValueContentColor(); - - GUI.color = oldColor; - return; - } - - // Draw Background - Texture2D backgroundTexture = GradientEditor.GetBackgroundTexture(); - if (backgroundTexture != null) - { - Color oldColor = GUI.color; - GUI.color = bgColor; - - GUIStyle backgroundStyle = EditorGUIUtility.GetBasicTextureStyle(backgroundTexture); - backgroundStyle.Draw(position, false, false, false, false); - - GUI.color = oldColor; - } - - // DrawTexture - Texture2D preview = null; - float maxColorComponent; - if (property != null) - { - preview = GradientPreviewCache.GetPropertyPreview(property); - maxColorComponent = GetMaxColorComponent(property.gradientValue); - } - else - { - preview = GradientPreviewCache.GetGradientPreview(gradient); - maxColorComponent = GetMaxColorComponent(gradient); - } - - if (preview == null) - { - Debug.Log("Warning: Could not create preview for gradient"); - return; - } - - GUIStyle gs = EditorGUIUtility.GetBasicTextureStyle(preview); - gs.Draw(position, false, false, false, false); - - // HDR label - if (maxColorComponent > 1.0f) - { - GUI.Label(new Rect(position.x, position.y - 1, position.width - 3, position.height + 2), "HDR", EditorStyles.centeredGreyMiniLabel); - } - } - - private static float GetMaxColorComponent(Gradient gradient) - { - float maxColorComponent = 0.0f; - GradientColorKey[] colorKeys = gradient.colorKeys; - for (int i = 0; i < colorKeys.Length; i++) - { - maxColorComponent = Mathf.Max(maxColorComponent, colorKeys[i].color.maxColorComponent); - } - return maxColorComponent; - } - } -} // namespace diff --git a/Editor/Mono/GUI/GradientPicker.cs b/Editor/Mono/GUI/GradientPicker.cs deleted file mode 100644 index 8fc662443a..0000000000 --- a/Editor/Mono/GUI/GradientPicker.cs +++ /dev/null @@ -1,260 +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 UnityEditor; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class GradientPicker : EditorWindow - { - private static GradientPicker s_GradientPicker; - public static string presetsEditorPrefID { get { return "Gradient"; } } - - private GradientEditor m_GradientEditor; - private PresetLibraryEditor m_GradientLibraryEditor; - [SerializeField] - private PresetLibraryEditorState m_GradientLibraryEditorState; - private Gradient m_Gradient; - private const int k_DefaultNumSteps = 0; - private GUIView m_DelegateView; - private System.Action m_Delegate; - private bool m_HDR; - private bool gradientChanged { get; set; } - - // Static methods - public static void Show(Gradient newGradient, bool hdr) - { - GUIView currentView = GUIView.current; - PrepareShow(hdr); - s_GradientPicker.m_DelegateView = currentView; - s_GradientPicker.m_Delegate = null; - s_GradientPicker.Init(newGradient, hdr); - - GradientPreviewCache.ClearCache(); - } - - public static void Show(Gradient newGradient, bool hdr, System.Action onGradientChanged) - { - PrepareShow(hdr); - s_GradientPicker.m_DelegateView = null; - s_GradientPicker.m_Delegate = onGradientChanged; - s_GradientPicker.Init(newGradient, hdr); - - GradientPreviewCache.ClearCache(); - } - - static void PrepareShow(bool hdr) - { - if (s_GradientPicker == null) - { - string title = hdr ? "HDR Gradient Editor" : "Gradient Editor"; - s_GradientPicker = (GradientPicker)GetWindow(typeof(GradientPicker), true, title, false); - Vector2 minSize = new Vector2(360, 224); - Vector2 maxSize = new Vector2(1900, 3000); - s_GradientPicker.minSize = minSize; - s_GradientPicker.maxSize = maxSize; - s_GradientPicker.wantsMouseMove = true; - s_GradientPicker.ShowAuxWindow(); // Use this if auto close on lost focus is wanted. - } - else - { - s_GradientPicker.Repaint(); // Ensure we get a OnGUI so we refresh if new gradient - } - } - - public static GradientPicker instance - { - get - { - if (!s_GradientPicker) - Debug.LogError("Gradient Picker not initalized, did you call Show first?"); - return s_GradientPicker; - } - } - - public string currentPresetLibrary - { - get - { - InitIfNeeded(); - return m_GradientLibraryEditor.currentLibraryWithoutExtension; - } - set - { - InitIfNeeded(); - m_GradientLibraryEditor.currentLibraryWithoutExtension = value; - } - } - - private void Init(Gradient newGradient, bool hdr) - { - m_Gradient = newGradient; - m_HDR = hdr; - if (m_GradientEditor != null) - m_GradientEditor.Init(newGradient, k_DefaultNumSteps, m_HDR); - Repaint(); - } - - private void SetGradientData(Gradient gradient) - { - m_Gradient.colorKeys = gradient.colorKeys; - m_Gradient.alphaKeys = gradient.alphaKeys; - m_Gradient.mode = gradient.mode; - Init(m_Gradient, m_HDR); - } - - public static bool visible - { - get { return s_GradientPicker != null; } - } - - public static Gradient gradient - { - get - { - if (s_GradientPicker != null) - return s_GradientPicker.m_Gradient; - return null; - } - } - - public void OnEnable() - { - hideFlags = HideFlags.DontSave; - // Use these if window is not an aux window for auto closing on play/stop - //EditorApplication.playmodeStateChanged += OnPlayModeStateChanged; - } - - public void OnDisable() - { - //EditorApplication.playmodeStateChanged -= OnPlayModeStateChanged; - if (m_GradientLibraryEditorState != null) - m_GradientLibraryEditorState.TransferEditorPrefsState(false); - - s_GradientPicker = null; - } - - public void OnDestroy() - { - m_GradientLibraryEditor.UnloadUsedLibraries(); - } - - void OnPlayModeStateChanged() - { - Close(); - } - - void InitIfNeeded() - { - // Init editor when needed - if (m_GradientEditor == null) - { - m_GradientEditor = new GradientEditor(); - m_GradientEditor.Init(m_Gradient, k_DefaultNumSteps, m_HDR); - } - - if (m_GradientLibraryEditorState == null) - { - m_GradientLibraryEditorState = new PresetLibraryEditorState(presetsEditorPrefID); - m_GradientLibraryEditorState.TransferEditorPrefsState(true); - } - - if (m_GradientLibraryEditor == null) - { - var saveLoadHelper = new ScriptableObjectSaveLoadHelper("gradients", SaveType.Text); - m_GradientLibraryEditor = new PresetLibraryEditor(saveLoadHelper, m_GradientLibraryEditorState, PresetClickedCallback); - m_GradientLibraryEditor.showHeader = true; - m_GradientLibraryEditor.minMaxPreviewHeight = new Vector2(14f, 14f); - } - } - - void PresetClickedCallback(int clickCount, object presetObject) - { - Gradient gradient = presetObject as Gradient; - if (gradient == null) - Debug.LogError("Incorrect object passed " + presetObject); - - SetCurrentGradient(gradient); - UnityEditorInternal.GradientPreviewCache.ClearCache(); - gradientChanged = true; - } - - public void OnGUI() - { - // When we start play (using shortcut keys) we get two OnGui calls and m_Gradient is null: so early out. - if (m_Gradient == null) - return; - - InitIfNeeded(); - - float gradientEditorHeight = Mathf.Min(position.height, 146); - float distBetween = 10f; - float presetLibraryHeight = position.height - gradientEditorHeight - distBetween; - - Rect gradientEditorRect = new Rect(10, 10, position.width - 20, gradientEditorHeight - 20); - Rect gradientLibraryRect = new Rect(0, gradientEditorHeight + distBetween, position.width, presetLibraryHeight); - - // Separator - EditorGUI.DrawRect(new Rect(gradientLibraryRect.x, gradientLibraryRect.y - 1, gradientLibraryRect.width, 1), new Color(0, 0, 0, 0.3f)); - EditorGUI.DrawRect(new Rect(gradientLibraryRect.x, gradientLibraryRect.y, gradientLibraryRect.width, 1), new Color(1, 1, 1, 0.1f)); - - // The meat - EditorGUI.BeginChangeCheck(); - m_GradientEditor.OnGUI(gradientEditorRect); - if (EditorGUI.EndChangeCheck()) - gradientChanged = true; - m_GradientLibraryEditor.OnGUI(gradientLibraryRect, m_Gradient); - if (gradientChanged) - { - gradientChanged = false; - SendEvent(true); - } - } - - public const string GradientPickerChangedCommand = "GradientPickerChanged"; - - void SendEvent(bool exitGUI) - { - if (m_DelegateView) - { - Event e = EditorGUIUtility.CommandEvent(GradientPickerChangedCommand); - Repaint(); - m_DelegateView.SendEvent(e); - if (exitGUI) - GUIUtility.ExitGUI(); - } - if (m_Delegate != null) - { - m_Delegate(gradient); - } - } - - public static void SetCurrentGradient(Gradient gradient) - { - if (s_GradientPicker == null) - return; - - s_GradientPicker.SetGradientData(gradient); - GUI.changed = true; - } - - public static void CloseWindow() - { - if (s_GradientPicker == null) - return; - - s_GradientPicker.Close(); - GUIUtility.ExitGUI(); - } - - public static void RepaintWindow() - { - if (s_GradientPicker == null) - return; - s_GradientPicker.Repaint(); - } - } -} // namespace diff --git a/Editor/Mono/GUI/HexColorTextField.cs b/Editor/Mono/GUI/HexColorTextField.cs deleted file mode 100644 index a1dec0afb0..0000000000 --- a/Editor/Mono/GUI/HexColorTextField.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; - -namespace UnityEditor -{ - public sealed partial class EditorGUILayout - { - internal static Color32 HexColorTextField(GUIContent label, Color32 color, bool showAlpha, params GUILayoutOption[] options) - { - return HexColorTextField(label, color, showAlpha, EditorStyles.textField, options); - } - - internal static Color32 HexColorTextField(GUIContent label, Color32 color, bool showAlpha, GUIStyle style, params GUILayoutOption[] options) - { - Rect r = s_LastRect = GetControlRect(true, EditorGUI.kSingleLineHeight, EditorStyles.numberField, options); - return EditorGUI.HexColorTextField(r, label, color, showAlpha, style); - } - } - - public sealed partial class EditorGUI - { - internal static Color32 HexColorTextField(Rect rect, GUIContent label, Color32 color, bool showAlpha) - { - return HexColorTextField(rect, label, color, showAlpha, EditorStyles.textField); - } - - internal static Color32 HexColorTextField(Rect rect, GUIContent label, Color32 color, bool showAlpha, GUIStyle style) - { - var id = GUIUtility.GetControlID(s_TextFieldHash, FocusType.Keyboard, rect); - return DoHexColorTextField(id, PrefixLabel(rect, id, label), color, showAlpha, style); - } - - internal static Color32 DoHexColorTextField(int id, Rect rect, Color32 color, bool showAlpha, GUIStyle style) - { - const string kValidHexChars = "0123456789ABCDEFabcdef"; - - // Hex field - string hex = showAlpha ? ColorUtility.ToHtmlStringRGBA(color) : ColorUtility.ToHtmlStringRGB(color); - BeginChangeCheck(); - - bool dummy; - string newHex = DoTextField(s_RecycledEditor, id, rect, hex, style, kValidHexChars, out dummy, false, false, false); - - if (EndChangeCheck()) - { - s_RecycledEditor.text = s_RecycledEditor.text.ToUpper(); - - Color newColor; - if (ColorUtility.TryParseHtmlString("#" + newHex, out newColor)) - color = new Color(newColor.r, newColor.g, newColor.b, showAlpha ? newColor.a : color.a); - } - - return color; - } - } -} // namespace diff --git a/Editor/Mono/GUI/InternalEditorGUI.cs b/Editor/Mono/GUI/InternalEditorGUI.cs deleted file mode 100644 index de99b3b1eb..0000000000 --- a/Editor/Mono/GUI/InternalEditorGUI.cs +++ /dev/null @@ -1,322 +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 System.Collections.Generic; - -// NOTE: -// This file should only contain internal functions of the EditorGUI class -// - -namespace UnityEditor -{ - public sealed partial class EditorGUI - { - static int s_DropdownButtonHash = "DropdownButton".GetHashCode(); - static int s_MouseDeltaReaderHash = "MouseDeltaReader".GetHashCode(); - - internal static bool Button(Rect position, GUIContent content) - { - return Button(position, content, EditorStyles.miniButton); - } - - // We need an EditorGUI.Button that only reacts to left mouse button (GUI.Button reacts to all mouse buttons), so we - // can handle context click events for button areas etc. - internal static bool Button(Rect position, GUIContent content, GUIStyle style) - { - Event evt = Event.current; - switch (evt.type) - { - case EventType.MouseDown: - case EventType.MouseUp: - if (evt.button != 0) - return false; // ignore all input from other buttons than the left mouse button - break; - } - - return GUI.Button(position, content, style); - } - - // Button used for the icon selector where an icon can be selected by pressing and dragging the - // mouse cursor around to select different icons - internal static bool IconButton(int id, Rect position, GUIContent content, GUIStyle style) - { - GUIUtility.CheckOnGUI(); - switch (Event.current.GetTypeForControl(id)) - { - case EventType.MouseDown: - // If the mouse is inside the button, we say that we're the hot control - if (position.Contains(Event.current.mousePosition)) - { - GUIUtility.hotControl = id; - Event.current.Use(); - return true; - } - return false; - case EventType.MouseUp: - if (GUIUtility.hotControl == id) - { - GUIUtility.hotControl = 0; - - // If we got the mousedown, the mouseup is ours as well - // (no matter if the click was in the button or not) - Event.current.Use(); - - // But we only return true if the button was actually clicked - return position.Contains(Event.current.mousePosition); - } - return false; - case EventType.MouseDrag: - if (position.Contains(Event.current.mousePosition)) - { - GUIUtility.hotControl = id; - Event.current.Use(); - return true; - } - break; - case EventType.Repaint: - style.Draw(position, content, id); - break; - } - return false; - } - - internal static float WidthResizer(Rect position, float width, float minWidth, float maxWidth) - { - bool hasControl; - return Resizer.Resize(position, width, minWidth, maxWidth, true, out hasControl); - } - - internal static float WidthResizer(Rect position, float width, float minWidth, float maxWidth, out bool hasControl) - { - return Resizer.Resize(position, width, minWidth, maxWidth, true, out hasControl); - } - - internal static float HeightResizer(Rect position, float height, float minHeight, float maxHeight) - { - bool hasControl; - return Resizer.Resize(position, height, minHeight, maxHeight, false, out hasControl); - } - - internal static float HeightResizer(Rect position, float height, float minHeight, float maxHeight, out bool hasControl) - { - return Resizer.Resize(position, height, minHeight, maxHeight, false, out hasControl); - } - - static class Resizer - { - static float s_StartSize; - static Vector2 s_MouseDeltaReaderStartPos; - internal static float Resize(Rect position, float size, float minSize, float maxSize, bool horizontal, out bool hasControl) - { - int id = EditorGUIUtility.GetControlID(s_MouseDeltaReaderHash, FocusType.Passive, position); - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (GUIUtility.hotControl == 0 && position.Contains(evt.mousePosition) && evt.button == 0) - { - GUIUtility.hotControl = id; - GUIUtility.keyboardControl = 0; - s_MouseDeltaReaderStartPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews - s_StartSize = size; - evt.Use(); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - evt.Use(); - Vector2 screenPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews - float delta = horizontal ? (screenPos - s_MouseDeltaReaderStartPos).x : (screenPos - s_MouseDeltaReaderStartPos).y; - float newSize = s_StartSize + delta; - if (newSize >= minSize && newSize <= maxSize) - size = newSize; - else - size = Mathf.Clamp(newSize, minSize, maxSize); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && evt.button == 0) - { - GUIUtility.hotControl = 0; - evt.Use(); - } - break; - case EventType.Repaint: - var cursor = horizontal ? MouseCursor.SplitResizeLeftRight : MouseCursor.SplitResizeUpDown; - EditorGUIUtility.AddCursorRect(position, cursor, id); - break; - } - - hasControl = GUIUtility.hotControl == id; - return size; - } - } - - - // Get mouse delta values in different situations when click-dragging - static Vector2 s_MouseDeltaReaderLastPos; - internal static Vector2 MouseDeltaReader(Rect position, bool activated) - { - int id = EditorGUIUtility.GetControlID(s_MouseDeltaReaderHash, FocusType.Passive, position); - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (activated && GUIUtility.hotControl == 0 && position.Contains(evt.mousePosition) && evt.button == 0) - { - GUIUtility.hotControl = id; - GUIUtility.keyboardControl = 0; - s_MouseDeltaReaderLastPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews - evt.Use(); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - Vector2 screenPos = GUIClip.Unclip(evt.mousePosition); // We unclip to screenspace to prevent being affected by scrollviews - Vector2 delta = (screenPos - s_MouseDeltaReaderLastPos); - s_MouseDeltaReaderLastPos = screenPos; - evt.Use(); - return delta; - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id && evt.button == 0) - { - GUIUtility.hotControl = 0; - evt.Use(); - } - break; - } - return Vector2.zero; - } - - // Shows an active button and a triangle button on the right, which expands the dropdown list - // Returns true if button was activated, returns false if the the dropdown button was activated or the button was not clicked. - internal static bool ButtonWithDropdownList(string buttonName, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options) - { - var content = EditorGUIUtility.TempContent(buttonName); - return ButtonWithDropdownList(content, buttonNames, callback, options); - } - - // Shows an active button and a triangle button on the right, which expands the dropdown list - // Returns true if button was activated, returns false if the the dropdown button was activated or the button was not clicked. - internal static bool ButtonWithDropdownList(GUIContent content, string[] buttonNames, GenericMenu.MenuFunction2 callback, params GUILayoutOption[] options) - { - var rect = GUILayoutUtility.GetRect(content, EditorStyles.dropDownList, options); - - var dropDownRect = rect; - const float kDropDownButtonWidth = 20f; - dropDownRect.xMin = dropDownRect.xMax - kDropDownButtonWidth; - - if (Event.current.type == EventType.MouseDown && dropDownRect.Contains(Event.current.mousePosition)) - { - var menu = new GenericMenu(); - for (int i = 0; i != buttonNames.Length; i++) - menu.AddItem(new GUIContent(buttonNames[i]), false, callback, i); - - menu.DropDown(rect); - Event.current.Use(); - - return false; - } - - return GUI.Button(rect, content, EditorStyles.dropDownList); - } - - internal static void GameViewSizePopup(Rect buttonRect, GameViewSizeGroupType groupType, int selectedIndex, IGameViewSizeMenuUser gameView, GUIStyle guiStyle) - { - var group = GameViewSizes.instance.GetGroup(groupType); - var text = ""; - if (selectedIndex >= 0 && selectedIndex < group.GetTotalCount()) - text = group.GetGameViewSize(selectedIndex).displayText; - - if (EditorGUI.DropdownButton(buttonRect, GUIContent.Temp(text), FocusType.Passive, guiStyle)) - { - var menuData = new GameViewSizesMenuItemProvider(groupType); - var flexibleMenu = new GameViewSizeMenu(menuData, selectedIndex, new GameViewSizesMenuModifyItemUI(), gameView); - PopupWindow.Show(buttonRect, flexibleMenu); - } - } - - public static void DrawRect(Rect rect, Color color) - { - if (Event.current.type != EventType.Repaint) - return; - - Color orgColor = GUI.color; - GUI.color = GUI.color * color; - GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture); - GUI.color = orgColor; - } - - internal static void DrawDelimiterLine(Rect rect) - { - DrawRect(rect, kSplitLineSkinnedColor.color); - } - - internal static void DrawOutline(Rect rect, float size, Color color) - { - if (Event.current.type != EventType.Repaint) - return; - - Color orgColor = GUI.color; - GUI.color = GUI.color * color; - GUI.DrawTexture(new Rect(rect.x, rect.y, rect.width, size), EditorGUIUtility.whiteTexture); - GUI.DrawTexture(new Rect(rect.x, rect.yMax - size, rect.width, size), EditorGUIUtility.whiteTexture); - GUI.DrawTexture(new Rect(rect.x, rect.y + 1, size, rect.height - 2 * size), EditorGUIUtility.whiteTexture); - GUI.DrawTexture(new Rect(rect.xMax - size, rect.y + 1, size, rect.height - 2 * size), EditorGUIUtility.whiteTexture); - - GUI.color = orgColor; - } - } - - internal struct PropertyGUIData - { - public SerializedProperty property; - public Rect totalPosition; - public bool wasBoldDefaultFont; - public bool wasEnabled; - public Color color; - public PropertyGUIData(SerializedProperty property, Rect totalPosition, bool wasBoldDefaultFont, bool wasEnabled, Color color) - { - this.property = property; - this.totalPosition = totalPosition; - this.wasBoldDefaultFont = wasBoldDefaultFont; - this.wasEnabled = wasEnabled; - this.color = color; - } - } - - internal class DebugUtils - { - internal static string ListToString(IEnumerable list) - { - if (list == null) - return "[null list]"; - - string r = "["; - int count = 0; - foreach (T item in list) - { - if (count != 0) - r += ", "; - if (item != null) - r += item.ToString(); - else - r += "'null'"; - count++; - } - r += "]"; - - if (count == 0) - return "[empty list]"; - - return "(" + count + ") " + r; - } - } -} diff --git a/Editor/Mono/GUI/InternalEditorGUILayout.cs b/Editor/Mono/GUI/InternalEditorGUILayout.cs deleted file mode 100644 index dba74acbd3..0000000000 --- a/Editor/Mono/GUI/InternalEditorGUILayout.cs +++ /dev/null @@ -1,34 +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 UnityEditor; -using System.Collections; - -// NOTE: -// This file should only contain internal functions of the EditorGUILayout class - -namespace UnityEditor -{ - public sealed partial class EditorGUILayout - { - internal static bool IconButton(int id, GUIContent content, GUIStyle style, params GUILayoutOption[] options) - { - s_LastRect = GUILayoutUtility.GetRect(content, style, options); - return EditorGUI.IconButton(id, s_LastRect, content, style); - } - - internal static void GameViewSizePopup(GameViewSizeGroupType groupType, int selectedIndex, IGameViewSizeMenuUser gameView, GUIStyle style, params GUILayoutOption[] options) - { - s_LastRect = GetControlRect(false, EditorGUI.kSingleLineHeight, style, options); - EditorGUI.GameViewSizePopup(s_LastRect, groupType, selectedIndex, gameView, style); - } - - internal static void SortingLayerField(GUIContent label, SerializedProperty layerID, GUIStyle style, GUIStyle labelStyle) - { - s_LastRect = EditorGUILayout.GetControlRect(false, EditorGUI.kSingleLineHeight, style); - EditorGUI.SortingLayerField(s_LastRect, label, layerID, style, labelStyle); - } - } -} diff --git a/Editor/Mono/GUI/ListViewElement.cs b/Editor/Mono/GUI/ListViewElement.cs deleted file mode 100644 index 5c13c9ccdf..0000000000 --- a/Editor/Mono/GUI/ListViewElement.cs +++ /dev/null @@ -1,15 +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; - -namespace UnityEditor -{ - internal struct ListViewElement - { - public int row; - public int column; - public Rect position; - } -} diff --git a/Editor/Mono/GUI/ListViewGUI.cs b/Editor/Mono/GUI/ListViewGUI.cs deleted file mode 100644 index 9e1d4eb3eb..0000000000 --- a/Editor/Mono/GUI/ListViewGUI.cs +++ /dev/null @@ -1,124 +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; - -namespace UnityEditor -{ - /// *undocumented* - internal class ListViewGUI - { - static int[] dummyWidths = new int[1]; - - static internal ListViewShared.InternalListViewState ilvState = new ListViewShared.InternalListViewState(); - static int listViewHash = "ListView".GetHashCode(); - - static public ListViewShared.ListViewElementsEnumerator ListView(Rect pos, ListViewState state) - { - return DoListView(pos, state, null, string.Empty); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, 0, null, string.Empty, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, int[] colWidths, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, 0, colWidths, string.Empty, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, lvOptions, null, string.Empty, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, string dragTitle, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, lvOptions, null, dragTitle, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, int[] colWidths, string dragTitle, GUIStyle style, params GUILayoutOption[] options) - { - GUILayout.BeginHorizontal(style); - state.scrollPos = EditorGUILayout.BeginScrollView(state.scrollPos, options); - ilvState.beganHorizontal = true; - - state.draggedFrom = -1; - state.draggedTo = -1; - state.fileNames = null; - - if ((lvOptions & ListViewOptions.wantsReordering) != 0) ilvState.wantsReordering = true; - if ((lvOptions & ListViewOptions.wantsExternalFiles) != 0) ilvState.wantsExternalFiles = true; - if ((lvOptions & ListViewOptions.wantsToStartCustomDrag) != 0) ilvState.wantsToStartCustomDrag = true; - if ((lvOptions & ListViewOptions.wantsToAcceptCustomDrag) != 0) ilvState.wantsToAcceptCustomDrag = true; - - return DoListView(GUILayoutUtility.GetRect(1, state.totalRows * state.rowHeight + 3), state, colWidths, string.Empty); - } - - static public ListViewShared.ListViewElementsEnumerator DoListView(Rect pos, ListViewState state, int[] colWidths, string dragTitle) - { - int id = GUIUtility.GetControlID(listViewHash, FocusType.Passive); - state.ID = id; - - state.selectionChanged = false; - - Rect vRect; - - if ((GUIClip.visibleRect.x < 0) || (GUIClip.visibleRect.y < 0)) // TODO: this is needed for simple LVs to work. we are not in a clip at all. - { - vRect = pos; - } - else - vRect = (pos.y < 0) ? new Rect(0, 0, GUIClip.visibleRect.width, GUIClip.visibleRect.height) : new Rect(0, state.scrollPos.y, GUIClip.visibleRect.width, GUIClip.visibleRect.height); // check if this is custom scroll - - if (vRect.width <= 0) vRect.width = 1; - if (vRect.height <= 0) vRect.height = 1; - - ilvState.rect = vRect; - - int invisibleRows = (int)((-pos.y + vRect.yMin) / state.rowHeight); - int endRow = invisibleRows + (int)System.Math.Ceiling((((vRect.yMin - pos.y) % state.rowHeight) + vRect.height) / state.rowHeight) - 1; - - if (colWidths == null) - { - dummyWidths[0] = (int)vRect.width; - colWidths = dummyWidths; - } - - ilvState.invisibleRows = invisibleRows; - ilvState.endRow = endRow; - ilvState.rectHeight = (int)vRect.height; - ilvState.state = state; - - if (invisibleRows < 0) - invisibleRows = 0; - - if (endRow >= state.totalRows) - endRow = state.totalRows - 1; - - return new ListViewShared.ListViewElementsEnumerator(ilvState, colWidths, invisibleRows, endRow, dragTitle, new Rect(0, invisibleRows * state.rowHeight, pos.width, state.rowHeight)); - } - - static public bool MultiSelection(int prevSelected, int currSelected, ref int initialSelected, ref bool[] selectedItems) - { - return ListViewShared.MultiSelection(ilvState, prevSelected, currSelected, ref initialSelected, ref selectedItems); - } - - static public bool HasMouseUp(Rect r) - { - return ListViewShared.HasMouseUp(ilvState, r, 0); - } - - static public bool HasMouseDown(Rect r) - { - return ListViewShared.HasMouseDown(ilvState, r, 0); - } - - static public bool HasMouseDown(Rect r, int button) - { - return ListViewShared.HasMouseDown(ilvState, r, button); - } - } -} diff --git a/Editor/Mono/GUI/ListViewGUILayout.cs b/Editor/Mono/GUI/ListViewGUILayout.cs deleted file mode 100644 index 60b1e549c3..0000000000 --- a/Editor/Mono/GUI/ListViewGUILayout.cs +++ /dev/null @@ -1,215 +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; - -namespace UnityEditor -{ - /// *undocumented* - internal class ListViewGUILayout - { - static int layoutedListViewHash = "layoutedListView".GetHashCode(); - - static ListViewState lvState = null; - - static int listViewHash = "ListView".GetHashCode(); - static int[] dummyWidths = new int[1]; - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, 0, string.Empty, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, string dragTitle, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, 0, dragTitle, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, GUIStyle style, params GUILayoutOption[] options) - { - return ListView(state, lvOptions, string.Empty, style, options); - } - - static public ListViewShared.ListViewElementsEnumerator ListView(ListViewState state, ListViewOptions lvOptions, string dragTitle, GUIStyle style, params GUILayoutOption[] options) - { - lvState = state; - - GUILayout.BeginHorizontal(style, options); // no good reason for this here, except drawing LVs background - - state.scrollPos = EditorGUILayout.BeginScrollView(state.scrollPos, options); - BeginLayoutedListview(state, GUIStyle.none); - - state.draggedFrom = -1; - state.draggedTo = -1; - state.fileNames = null; - - if ((lvOptions & ListViewOptions.wantsReordering) != 0) state.ilvState.wantsReordering = true; - if ((lvOptions & ListViewOptions.wantsExternalFiles) != 0) state.ilvState.wantsExternalFiles = true; - if ((lvOptions & ListViewOptions.wantsToStartCustomDrag) != 0) state.ilvState.wantsToStartCustomDrag = true; - if ((lvOptions & ListViewOptions.wantsToAcceptCustomDrag) != 0) state.ilvState.wantsToAcceptCustomDrag = true; - - return DoListView(state, null, dragTitle); - } - - static Rect dummyRect = new Rect(0, 0, 1, 1); - - static private ListViewShared.ListViewElementsEnumerator DoListView(ListViewState state, int[] colWidths, string dragTitle) - { - Rect vRect = dummyRect; - int invisibleRows = 0; - int endRow = 0; - - ListViewShared.InternalLayoutedListViewState ilvState = state.ilvState; - - //GUIUtility.CheckOnGUI (); - int id = GUIUtility.GetControlID(listViewHash, FocusType.Passive); - - state.ID = id; - state.selectionChanged = false; - ilvState.state = state; - - if (Event.current.type != EventType.Layout) - { - vRect = new Rect(0, state.scrollPos.y, GUIClip.visibleRect.width, GUIClip.visibleRect.height); - - if (vRect.width <= 0) vRect.width = 1; - if (vRect.height <= 0) vRect.height = 1; - - state.ilvState.rect = vRect; - - invisibleRows = (int)(vRect.yMin) / state.rowHeight; - endRow = invisibleRows + (int)System.Math.Ceiling(((vRect.yMin % state.rowHeight) + vRect.height) / state.rowHeight) - 1; - - //if (id == GUIUtility.hotControl) - //{ - // s = invisibleRows.ToString() + "::" + endRow.ToString(); - //} - - ilvState.invisibleRows = invisibleRows; - ilvState.endRow = endRow; - ilvState.rectHeight = (int)vRect.height; - - if (invisibleRows < 0) - invisibleRows = 0; - - if (endRow >= state.totalRows) - endRow = state.totalRows - 1; - } - - if (colWidths == null) - { - dummyWidths[0] = (int)vRect.width; - colWidths = dummyWidths; - } - - return new ListViewShared.ListViewElementsEnumerator(ilvState, colWidths, invisibleRows, endRow, dragTitle, new Rect(0, invisibleRows * state.rowHeight, vRect.width, state.rowHeight)); - } - - private static void BeginLayoutedListview(ListViewState state, GUIStyle style, params GUILayoutOption[] options) - { - GUILayoutedListViewGroup g = (GUILayoutedListViewGroup)GUILayoutUtility.BeginLayoutGroup(style, null, typeof(GUILayoutedListViewGroup)); - - g.state = state; - state.ilvState.group = g; - - GUIUtility.GetControlID(layoutedListViewHash, FocusType.Passive); - - switch (Event.current.type) - { - case EventType.Layout: - { - g.resetCoords = false; - g.isVertical = true; - g.ApplyOptions(options); - break; - } - } - } - - /// *undocumented* - internal class GUILayoutedListViewGroup : GUILayoutGroup - { - internal ListViewState state; - - public override void CalcWidth() - { - // Make LVs width independent of widths of elements inside it - base.CalcWidth(); - minWidth = 0; - maxWidth = 0; - stretchWidth = 10000; - } - - public override void CalcHeight() - { - minHeight = 0; - maxHeight = 0; - - base.CalcHeight(); - - margin.top = 0; - margin.bottom = 0; - - if (minHeight == 0) // empty lv? - { - minHeight = 1; - maxHeight = 1; - state.rowHeight = 1; - } - else - { - state.rowHeight = (int)minHeight; - minHeight *= state.totalRows; - maxHeight *= state.totalRows; - } - } - - private void AddYRecursive(GUILayoutEntry e, float y) - { - // this looks kind of bad, but in 99% of cases it would only be one level depth (e.g. few labels inside BeginHorizontal) - e.rect.y += y; - - GUILayoutGroup g = e as GUILayoutGroup; - - if (g != null) - { - for (int i = 0; i < g.entries.Count; i++) - AddYRecursive((GUILayoutEntry)g.entries[i], y); - } - } - - public void AddY() - { - if (entries.Count > 0) - AddYRecursive((GUILayoutEntry)entries[0], ((GUILayoutEntry)entries[0]).minHeight); - } - - public void AddY(float val) - { - if (entries.Count > 0) - AddYRecursive((GUILayoutEntry)entries[0], val); - } - } - - static public bool MultiSelection(int prevSelected, int currSelected, ref int initialSelected, ref bool[] selectedItems) - { - return ListViewShared.MultiSelection(lvState.ilvState, prevSelected, currSelected, ref initialSelected, ref selectedItems); - } - - static public bool HasMouseUp(Rect r) - { - return ListViewShared.HasMouseUp(lvState.ilvState, r, 0); - } - - static public bool HasMouseDown(Rect r) - { - return ListViewShared.HasMouseDown(lvState.ilvState, r, 0); - } - - static public bool HasMouseDown(Rect r, int button) - { - return ListViewShared.HasMouseDown(lvState.ilvState, r, button); - } - } -} diff --git a/Editor/Mono/GUI/ListViewOptions.cs b/Editor/Mono/GUI/ListViewOptions.cs deleted file mode 100644 index f488faf3aa..0000000000 --- a/Editor/Mono/GUI/ListViewOptions.cs +++ /dev/null @@ -1,8 +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 -{ - internal enum ListViewOptions { wantsReordering = 1, wantsExternalFiles = 2, wantsToStartCustomDrag = 4, wantsToAcceptCustomDrag = 8 }; -} diff --git a/Editor/Mono/GUI/ListViewState.cs b/Editor/Mono/GUI/ListViewState.cs deleted file mode 100644 index 5126afd108..0000000000 --- a/Editor/Mono/GUI/ListViewState.cs +++ /dev/null @@ -1,47 +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; - -namespace UnityEditor -{ - /// *undocumented* - [System.Serializable] - internal class ListViewState - { - const int c_rowHeight = 16; //TODO: - public int row; - public int column; - public Vector2 scrollPos; - public int totalRows; - public int rowHeight; - - public int ID; - public bool selectionChanged; - public int draggedFrom; - public int draggedTo; - public bool drawDropHere = false; - public Rect dropHereRect = new Rect(0, 0, 0, 0); - public string[] fileNames = null; - public int customDraggedFromID = 0; - - public ListViewState() { Init(0, c_rowHeight); } - public ListViewState(int totalRows) { Init(totalRows, c_rowHeight); } - public ListViewState(int totalRows, int rowHeight) { Init(totalRows, rowHeight); } - - /// *undocumented* - internal ListViewShared.InternalLayoutedListViewState ilvState = new ListViewShared.InternalLayoutedListViewState(); - - private void Init(int totalRows, int rowHeight) - { - this.row = -1; - this.column = 0; - this.scrollPos = Vector2.zero; - this.totalRows = totalRows; - this.rowHeight = rowHeight; - - selectionChanged = false; - } - } -} diff --git a/Editor/Mono/GUI/MainView.cs b/Editor/Mono/GUI/MainView.cs index 24f90a0854..1f41368a2a 100644 --- a/Editor/Mono/GUI/MainView.cs +++ b/Editor/Mono/GUI/MainView.cs @@ -56,7 +56,7 @@ public static void MakeMain() int height = Mathf.Clamp(res.height * 3 / 4, 600, 950); cw.position = new Rect(60, 20, width, height); - cw.Show(ShowMode.MainWindow, true, true); + cw.Show(ShowMode.MainWindow, loadPosition: true, displayImmediately: true, setFocus: true); cw.DisplayAllViews(); } diff --git a/Editor/Mono/GUI/MaskFieldGUI.cs b/Editor/Mono/GUI/MaskFieldGUI.cs deleted file mode 100644 index 59137ba93d..0000000000 --- a/Editor/Mono/GUI/MaskFieldGUI.cs +++ /dev/null @@ -1,246 +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; - -namespace UnityEditor -{ - // Class for storing state for mask menus so we can get the info back to OnGUI from the user selection - internal static class MaskFieldGUI - { - // Class for storing state for mask menus so we can get the info back to OnGUI from the user selection - private class MaskCallbackInfo - { - // The global shared popup state - public static MaskCallbackInfo m_Instance; - - // Name of the command event sent from the popup menu to OnGUI when user has changed selection - private const string kMaskMenuChangedMessage = "MaskMenuChanged"; - - // The control ID of the popup menu that is currently displayed. - // Used to pass selection changes back again - private readonly int m_ControlID; - - // New mask value - private int m_NewMask; - - // Which view should we send it to. - private readonly GUIView m_SourceView; - - public MaskCallbackInfo(int controlID) - { - m_ControlID = controlID; - m_SourceView = GUIView.current; - } - - public static int GetSelectedValueForControl(int controlID, int mask, out int changedFlags, out bool changedToValue) - { - var evt = Event.current; - - // No flags are changed by default - changedFlags = 0; - changedToValue = false; - - if (evt.type == EventType.ExecuteCommand && evt.commandName == kMaskMenuChangedMessage) - { - if (m_Instance == null) - { - Debug.LogError("Mask menu has no instance"); - return mask; - } - if (m_Instance.m_ControlID == controlID) - { - changedFlags = mask ^ m_Instance.m_NewMask; - changedToValue = (m_Instance.m_NewMask & changedFlags) != 0; - - if (changedFlags != 0) - { - mask = m_Instance.m_NewMask; - GUI.changed = true; - } - - m_Instance = null; - evt.Use(); - } - } - return mask; - } - - internal void SetMaskValueDelegate(object userData, string[] options, int selected) - { - int[] optionMaskValues = (int[])userData; - m_NewMask = optionMaskValues[selected]; - - if (m_SourceView) - m_SourceView.SendEvent(EditorGUIUtility.CommandEvent(kMaskMenuChangedMessage)); - } - } - - /// Make a field for a generic mask. - internal static int DoMaskField(Rect position, int controlID, int mask, string[] flagNames, GUIStyle style) - { - int dummyInt; - bool dummyBool; - return DoMaskField(position, controlID, mask, flagNames, style, out dummyInt, out dummyBool); - } - - internal static int DoMaskField(Rect position, int controlID, int mask, string[] flagNames, int[] flagValues, GUIStyle style) - { - int dummyInt; - bool dummyBool; - return DoMaskField(position, controlID, mask, flagNames, flagValues, style, out dummyInt, out dummyBool); - } - - internal static int DoMaskField(Rect position, int controlID, int mask, string[] flagNames, GUIStyle style, out int changedFlags, out bool changedToValue) - { - var flagValues = new int[flagNames.Length]; - for (int i = 0; i < flagValues.Length; ++i) - flagValues[i] = (1 << i); - - return DoMaskField(position, controlID, mask, flagNames, flagValues, style, out changedFlags, out changedToValue); - } - - /// Make a field for a generic mask. - /// This version also gives you back which flags were changed and what they were changed to. - /// This is useful if you want to make the same change to multiple objects. - internal static int DoMaskField(Rect position, int controlID, int mask, string[] flagNames, int[] flagValues, GUIStyle style, out int changedFlags, out bool changedToValue) - { - mask = MaskCallbackInfo.GetSelectedValueForControl(controlID, mask, out changedFlags, out changedToValue); - - string buttonText; - string[] optionNames; - int[] optionMaskValues; - int[] selectedOptions; - GetMenuOptions(mask, flagNames, flagValues, out buttonText, out optionNames, out optionMaskValues, out selectedOptions); - - Event evt = Event.current; - if (evt.type == EventType.Repaint) - { - GUIContent buttonContent = EditorGUI.showMixedValue ? EditorGUI.mixedValueContent : EditorGUIUtility.TempContent(buttonText); - style.Draw(position, buttonContent, controlID, false); - } - else if ((evt.type == EventType.MouseDown && position.Contains(evt.mousePosition)) || evt.MainActionKeyForControl(controlID)) - { - MaskCallbackInfo.m_Instance = new MaskCallbackInfo(controlID); - evt.Use(); - EditorUtility.DisplayCustomMenu(position, optionNames, - // Only show selections if we are not multi-editing - EditorGUI.showMixedValue ? new int[] {} : selectedOptions, - // optionMaskValues is from the pool so use a clone of the values for the current control - MaskCallbackInfo.m_Instance.SetMaskValueDelegate, optionMaskValues.Clone()); - EditorGUIUtility.keyboardControl = controlID; - } - - return mask; - } - - private static readonly List s_OptionNames = new List(); - private static readonly List s_OptionValues = new List(); - private static readonly List s_SelectedOptions = new List(); - private static readonly HashSet s_SelectedOptionsSet = new HashSet(); - - private static T[] GetBuffer(List pool, int bufferLength) - { - for (int i = pool.Count; i <= bufferLength; ++i) - pool.Add(null); - if (pool[bufferLength] == null) - pool[bufferLength] = new T[bufferLength]; - var buffer = pool[bufferLength]; - for (int i = 0, length = buffer.Length; i < length; ++i) - buffer[i] = default(T); - return buffer; - } - - internal static void GetMenuOptions(int mask, string[] flagNames, int[] flagValues, - out string buttonText, out string[] optionNames, out int[] optionMaskValues, out int[] selectedOptions) - { - bool hasNothingName = (flagValues[0] == 0); - bool hasEverythingName = (flagValues[flagValues.Length - 1] == ~0); - - var nothingName = (hasNothingName ? flagNames[0] : "Nothing"); - var everythingName = (hasEverythingName ? flagNames[flagValues.Length - 1] : "Everything"); - - var optionCount = flagNames.Length + (hasNothingName ? 0 : 1) + (hasEverythingName ? 0 : 1); - var flagCount = flagNames.Length - (hasNothingName ? 1 : 0) - (hasEverythingName ? 1 : 0); - - // These indices refer to flags that are not 0 and ~0 - var flagStartIndex = (hasNothingName ? 1 : 0); - var flagEndIndex = flagStartIndex + flagCount; - - // Button text - buttonText = "Mixed ..."; - if (mask == 0) - buttonText = nothingName; - else if (mask == ~0) - buttonText = everythingName; - else - { - for (var flagIndex = flagStartIndex; flagIndex < flagEndIndex; flagIndex++) - { - if (mask == flagValues[flagIndex]) - buttonText = flagNames[flagIndex]; - } - } - - // Options names - optionNames = GetBuffer(s_OptionNames, optionCount); - optionNames[0] = nothingName; - optionNames[1] = everythingName; - for (var flagIndex = flagStartIndex; flagIndex < flagEndIndex; flagIndex++) - { - var optionIndex = flagIndex - flagStartIndex + 2; - optionNames[optionIndex] = flagNames[flagIndex]; - } - - var flagMask = 0; // Disjunction of all flags (except 0 and ~0) - var intermediateMask = 0; // Mask used to compute new mask value for each option - - // Selected options - s_SelectedOptionsSet.Clear(); - if (mask == 0) - s_SelectedOptionsSet.Add(0); - if (mask == ~0) - s_SelectedOptionsSet.Add(1); - for (var flagIndex = flagStartIndex; flagIndex < flagEndIndex; flagIndex++) - { - var flagValue = flagValues[flagIndex]; - flagMask |= flagValue; - if ((mask & flagValue) == flagValue) - { - var optionIndex = flagIndex - flagStartIndex + 2; - s_SelectedOptionsSet.Add(optionIndex); - intermediateMask |= flagValue; - } - } - selectedOptions = GetBuffer(s_SelectedOptions, s_SelectedOptionsSet.Count); - var x = 0; - foreach (var selected in s_SelectedOptionsSet) - { - selectedOptions[x] = selected; - ++x; - } - - // Option mask values - optionMaskValues = GetBuffer(s_OptionValues, optionCount); - optionMaskValues[0] = 0; - optionMaskValues[1] = ~0; - for (var flagIndex = flagStartIndex; flagIndex < flagEndIndex; flagIndex++) - { - var optionIndex = flagIndex - flagStartIndex + 2; - var flagValue = flagValues[flagIndex]; - var flagSet = ((intermediateMask & flagValue) == flagValue); - var newMask = (flagSet ? intermediateMask & ~flagValue : intermediateMask | flagValue); - - // If all flag options are selected the mask becomes ~0 to be consistent with the "Everything" option - if (newMask == flagMask) - newMask = ~0; - - optionMaskValues[optionIndex] = newMask; - } - } - } -} diff --git a/Editor/Mono/GUI/PaneDragTab.cs b/Editor/Mono/GUI/PaneDragTab.cs index 935cdd2932..ce5ca74804 100644 --- a/Editor/Mono/GUI/PaneDragTab.cs +++ b/Editor/Mono/GUI/PaneDragTab.cs @@ -131,7 +131,9 @@ public void Show(Rect pixelPos, GUIContent content, Vector2 viewSize, Vector2 mo { SetWindowPos(pixelPos); } - m_Window.Show(ShowMode.NoShadow, true, false); + + // Do not steal focus from the pane + m_Window.Show(ShowMode.NoShadow, loadPosition: true, displayImmediately: false, setFocus: false); m_TargetRect = pixelPos; } diff --git a/Editor/Mono/GUI/PingData.cs b/Editor/Mono/GUI/PingData.cs deleted file mode 100644 index fbbcdfdf79..0000000000 --- a/Editor/Mono/GUI/PingData.cs +++ /dev/null @@ -1,83 +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; - -namespace UnityEditor -{ - // Handles a "ping" in project/hierarchy windows. Zoom, wait and fadeoff. - // Init by setting: - // - m_PingStyle: Background style - // - m_ContentDraw: Content render callback function (is rendered on top of background ping style) - // - m_ContentRect: Size and position of content that is rendered in m_ContentDraw (is used for calculating the ping background and is passed to m_ContentDraw) - class PingData - { - public float m_TimeStart = -1f; - - public float m_ZoomTime = 0.2f; - public float m_WaitTime = 2.5f; - public float m_FadeOutTime = 1.5f; - public float m_PeakScale = 1.75f; - - public System.Action m_ContentDraw; - public Rect m_ContentRect; // Rect passed to m_ContentDraw - - // How wide is the view where we are pinging. Needed for the pivot point trick where pinged content is only partly visible. - public float m_AvailableWidth = 100f; - public GUIStyle m_PingStyle; - - public bool isPinging - { - get { return m_TimeStart > -1f; } - } - - public void HandlePing() - { - if (isPinging) - { - float totalTime = m_ZoomTime + m_WaitTime + m_FadeOutTime; - float t = (Time.realtimeSinceStartup - m_TimeStart); - - if (t > 0.0f && t < totalTime) - { - Color c = GUI.color; - Matrix4x4 m = GUI.matrix; - if (t < m_ZoomTime) - { - float peakTime = m_ZoomTime / 2f; - float scale = (m_PeakScale - 1f) * (((m_ZoomTime - Mathf.Abs(peakTime - t)) / peakTime) - 1f) + 1f; - Matrix4x4 mat = GUI.matrix; - - // If the content is only partly visible, the zoom pivot point is moved to right border. This avoids the nasty artefacts. - Vector2 pivotPoint = m_ContentRect.xMax < m_AvailableWidth ? m_ContentRect.center : new Vector2(m_AvailableWidth, m_ContentRect.center.y); - Vector2 point = GUIClip.Unclip(pivotPoint); - Matrix4x4 newMat = Matrix4x4.TRS(point, Quaternion.identity, new Vector3(scale, scale, 1)) * Matrix4x4.TRS(-point, Quaternion.identity, Vector3.one); - GUI.matrix = newMat * mat; - } - else if (t > m_ZoomTime + m_WaitTime) - { - float alpha = (totalTime - t) / m_FadeOutTime; - GUI.color = new Color(c.r, c.g, c.b, c.a * alpha); - } - - if (m_ContentDraw != null && Event.current.type == EventType.Repaint) - { - Rect backRect = m_ContentRect; - backRect.x -= m_PingStyle.padding.left; - backRect.y -= m_PingStyle.padding.top; - m_PingStyle.Draw(backRect, GUIContent.none, false, false, false, false); - m_ContentDraw(m_ContentRect); - } - - GUI.matrix = m; - GUI.color = c; - } - else - { - m_TimeStart = -1f; - } - } - } - } -} diff --git a/Editor/Mono/GUI/PragmaFixingWindow.cs b/Editor/Mono/GUI/PragmaFixingWindow.cs deleted file mode 100644 index 796ec721bb..0000000000 --- a/Editor/Mono/GUI/PragmaFixingWindow.cs +++ /dev/null @@ -1,98 +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 UnityEditorInternal; -using UnityEditor.Scripting; - -namespace UnityEditor -{ - internal class PragmaFixingWindow : EditorWindow - { - public static void ShowWindow(string[] paths) - { - PragmaFixingWindow win = EditorWindow.GetWindow(true); - win.SetPaths(paths); - win.ShowModal(); - } - - class Styles - { - public GUIStyle selected = "OL SelectedRow"; - public GUIStyle box = "OL Box"; - public GUIStyle button = "LargeButton"; - } - - static Styles s_Styles = null; - - ListViewState m_LV = new ListViewState(); - string[] m_Paths; - - public PragmaFixingWindow() - { - titleContent = EditorGUIUtility.TrTextContent("Unity - #pragma fixing"); - } - - public void SetPaths(string[] paths) - { - m_Paths = paths; - m_LV.totalRows = paths.Length; - } - - void OnGUI() - { - if (s_Styles == null) - { - s_Styles = new Styles(); - minSize = new Vector2(450, 300); - position = new Rect(position.x, position.y, minSize.x, minSize.y); - } - - GUILayout.Space(10); - GUILayout.Label("#pragma implicit and #pragma downcast need to be added to following files\nfor backwards compatibility"); - GUILayout.Space(10); - - GUILayout.BeginHorizontal(); - GUILayout.Space(10); - foreach (ListViewElement el in ListViewGUILayout.ListView(m_LV, s_Styles.box)) - { - if (el.row == m_LV.row && Event.current.type == EventType.Repaint) - s_Styles.selected.Draw(el.position, false, false, false, false); - - GUILayout.Label(m_Paths[el.row]); - } - GUILayout.Space(10); - GUILayout.EndHorizontal(); - GUILayout.Space(10); - - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - if (GUILayout.Button("Fix now", s_Styles.button)) - { - Close(); - PragmaFixing30.FixFiles(m_Paths); - // bugfix (377429): do not call AssetDatabase.Refresh here as that screws up project upgrading. - // When this script is invoked from Application::InitializeProject, the assets will be refreshed anyway. - GUIUtility.ExitGUI(); - } - - if (GUILayout.Button("Ignore", s_Styles.button)) - { - Close(); - GUIUtility.ExitGUI(); - } - - if (GUILayout.Button("Quit", s_Styles.button)) - { - EditorApplication.Exit(0); - GUIUtility.ExitGUI(); - } - - GUILayout.Space(10); - GUILayout.EndHorizontal(); - - GUILayout.Space(10); - } - } -} diff --git a/Editor/Mono/GUI/PreviewResizer.cs b/Editor/Mono/GUI/PreviewResizer.cs deleted file mode 100644 index c6f91814f1..0000000000 --- a/Editor/Mono/GUI/PreviewResizer.cs +++ /dev/null @@ -1,205 +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; - -namespace UnityEditor -{ - [System.Serializable] - internal class PreviewResizer - { - // The raw preview size while dragging (not snapped to allowed values) (shared) - static float s_DraggedPreviewSize = 0; - // The returned preview size while dragging (shared) - static float s_CachedPreviewSizeWhileDragging = 0; - static float s_MouseDownLocation, s_MouseDownValue; - static bool s_MouseDragged; - - // The last saved preview size - only saved when not dragging - // The saved value is the size when expanded - when collapsed the value is negative, - // so it can be restored when expanded again. - [SerializeField] - private float m_CachedPref; - [SerializeField] - private int m_ControlHash; - [SerializeField] - private string m_PrefName; - - private int m_Id = 0; - - private int id - { - get - { - if (m_Id == 0) - m_Id = EditorGUIUtility.GetControlID(m_ControlHash, FocusType.Passive, new Rect()); - return m_Id; - } - } - - // Instances of this class should be serialized. - // The Init function will only have effect if the serialized values are not already set. - public void Init(string prefName) - { - if (m_ControlHash != 0 && !string.IsNullOrEmpty(m_PrefName)) - return; - - // The controlHash is set by the calling code - // There's one for the Inspector, one for LightmapEditor, etc. - m_ControlHash = prefName.GetHashCode(); - - // We'll have one pref name per controlHash - m_PrefName = "Preview_" + prefName; - - // This is the only place the pref is read. This means we can have e.g. multiple - // Inspectors that can be controlled individually as long as they're open. - m_CachedPref = EditorPrefs.GetFloat(m_PrefName, 1); - } - - public float ResizeHandle(Rect windowPosition, float minSize, float minRemainingSize, float resizerHeight) - { - return ResizeHandle(windowPosition, minSize, minRemainingSize, resizerHeight, new Rect()); - } - - public float ResizeHandle(Rect windowPosition, float minSize, float minRemainingSize, float resizerHeight, Rect dragRect) - { - // Sanity check the cached value. It can be positive or negative, but never smaller than the minSize - if (Mathf.Abs(m_CachedPref) < minSize) - m_CachedPref = minSize * Mathf.Sign(m_CachedPref); - - float maxPreviewSize = windowPosition.height - minRemainingSize; - bool dragging = (GUIUtility.hotControl == id); - - float previewSize = (dragging ? s_DraggedPreviewSize : Mathf.Max(0, m_CachedPref)); - bool expanded = (m_CachedPref > 0); - float lastSize = Mathf.Abs(m_CachedPref); - - Rect resizerRect = new Rect(0, windowPosition.height - previewSize - resizerHeight, windowPosition.width, resizerHeight); - if (dragRect.width != 0) - { - resizerRect.x = dragRect.x; - resizerRect.width = dragRect.width; - } - - bool expandedBefore = expanded; - previewSize = -PixelPreciseCollapsibleSlider(id, resizerRect, -previewSize, -maxPreviewSize, -0, ref expanded); - previewSize = Mathf.Min(previewSize, maxPreviewSize); - dragging = (GUIUtility.hotControl == id); - - if (dragging) - s_DraggedPreviewSize = previewSize; - - // First snap size between 0 and minimum size - if (previewSize < minSize) - previewSize = (previewSize < minSize * 0.5f ? 0 : minSize); - - // If user clicked area, adjust size - if (expanded != expandedBefore) - previewSize = (expanded ? lastSize : 0); - - // Determine new expanded state - expanded = (previewSize >= minSize / 2); - - // Keep track of last preview size while not dragging or collapsed - // Note we don't want to save when dragging preview OR window size, - // so just don't save while dragging anything at all - if (GUIUtility.hotControl == 0) - { - if (previewSize > 0) - lastSize = previewSize; - float newPref = lastSize * (expanded ? 1 : -1); - if (newPref != m_CachedPref) - { - // Save the value to prefs - m_CachedPref = newPref; - EditorPrefs.SetFloat(m_PrefName, m_CachedPref); - } - } - - s_CachedPreviewSizeWhileDragging = previewSize; - return previewSize; - } - - // This value will change in realtime while dragging - public bool GetExpanded() - { - if (GUIUtility.hotControl == id) - return (s_CachedPreviewSizeWhileDragging > 0); - else - return (m_CachedPref > 0); - } - - public float GetPreviewSize() - { - if (GUIUtility.hotControl == id) - return Mathf.Max(0, s_CachedPreviewSizeWhileDragging); - else - return Mathf.Max(0, m_CachedPref); - } - - // This value won't change until we have stopped dragging again - public bool GetExpandedBeforeDragging() - { - return (m_CachedPref > 0); - } - - public void SetExpanded(bool expanded) - { - // Set the sign based on whether it's collapsed or not, then save to prefs - m_CachedPref = Mathf.Abs(m_CachedPref) * (expanded ? 1 : -1); - EditorPrefs.SetFloat(m_PrefName, m_CachedPref); - } - - public void ToggleExpanded() - { - // Reverse the sign, then save to prefs - m_CachedPref = -m_CachedPref; - EditorPrefs.SetFloat(m_PrefName, m_CachedPref); - } - - // This is the slider behavior for resizing the preview area - public static float PixelPreciseCollapsibleSlider(int id, Rect position, float value, float min, float max, ref bool expanded) - { - Event evt = Event.current; - switch (evt.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (GUIUtility.hotControl == 0 && evt.button == 0 && position.Contains(evt.mousePosition)) - { - GUIUtility.hotControl = id; - s_MouseDownLocation = evt.mousePosition.y; - s_MouseDownValue = value; - s_MouseDragged = false; - evt.Use(); - } - break; - case EventType.MouseDrag: - if (GUIUtility.hotControl == id) - { - value = Mathf.Clamp(evt.mousePosition.y - s_MouseDownLocation + s_MouseDownValue, min, max - 1); - GUI.changed = true; - s_MouseDragged = true; - evt.Use(); - } - break; - case EventType.MouseUp: - if (GUIUtility.hotControl == id) - { - GUIUtility.hotControl = 0; - if (!s_MouseDragged) - expanded = !expanded; - evt.Use(); - } - break; - case EventType.Repaint: - if (GUIUtility.hotControl == 0) - EditorGUIUtility.AddCursorRect(position, MouseCursor.SplitResizeUpDown); - if (GUIUtility.hotControl == id) - EditorGUIUtility.AddCursorRect(new Rect(position.x, position.y - 100, position.width, position.height + 200), MouseCursor.SplitResizeUpDown); - break; - } - return value; - } - } -} diff --git a/Editor/Mono/GUI/SearchField.cs b/Editor/Mono/GUI/SearchField.cs deleted file mode 100644 index 483ba8f0c6..0000000000 --- a/Editor/Mono/GUI/SearchField.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.Runtime.Remoting.Messaging; -using UnityEngine; - -namespace UnityEditor.IMGUI.Controls -{ - public class SearchField - { - int m_ControlID; - bool m_WantsFocus; - bool m_AutoSetFocusOnFindCommand = true; - const float kMinWidth = 36f; - const float kMaxWidth = 10000000f; - const float kMinToolbarWidth = 29f; - const float kMaxToolbarWidth = 200f; - - public delegate void SearchFieldCallback(); - public event SearchFieldCallback downOrUpArrowKeyPressed; - - public SearchField() - { - m_ControlID = GUIUtility.GetPermanentControlID(); - } - - public int searchFieldControlID - { - get { return m_ControlID; } - set { m_ControlID = value; } - } - - public bool autoSetFocusOnFindCommand - { - get { return m_AutoSetFocusOnFindCommand; } - set { m_AutoSetFocusOnFindCommand = value; } - } - - public void SetFocus() - { - m_WantsFocus = true; - } - - public bool HasFocus() - { - return GUIUtility.keyboardControl == m_ControlID; - } - - public string OnGUI(Rect rect, string text, GUIStyle style, GUIStyle cancelButtonStyle, GUIStyle emptyCancelButtonStyle) - { - CommandEventHandling(); - - FocusAndKeyHandling(); - - float cancelButtonWidth = cancelButtonStyle.fixedWidth; - - // Search field - Rect textRect = rect; - textRect.width -= cancelButtonWidth; - text = EditorGUI.TextFieldInternal(m_ControlID, textRect, text, style); - - // Cancel button - Rect buttonRect = rect; - buttonRect.x += rect.width - cancelButtonWidth; - buttonRect.width = cancelButtonWidth; - if (GUI.Button(buttonRect, GUIContent.none, text != "" ? cancelButtonStyle : emptyCancelButtonStyle) && text != "") - { - text = ""; - GUIUtility.keyboardControl = 0; - } - return text; - } - - public string OnGUI(Rect rect, string text) - { - return OnGUI(rect, text, EditorStyles.searchField, EditorStyles.searchFieldCancelButton, EditorStyles.searchFieldCancelButtonEmpty); - } - - public string OnGUI(string text, params GUILayoutOption[] options) - { - Rect rect = GUILayoutUtility.GetRect(kMinWidth, kMaxWidth, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.searchField, options); - return OnGUI(rect, text); - } - - public string OnToolbarGUI(Rect rect, string text) - { - return OnGUI(rect, text, EditorStyles.toolbarSearchField, EditorStyles.toolbarSearchFieldCancelButton, EditorStyles.toolbarSearchFieldCancelButtonEmpty); - } - - public string OnToolbarGUI(string text, params GUILayoutOption[] options) - { - Rect rect = GUILayoutUtility.GetRect(kMinToolbarWidth, kMaxToolbarWidth, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.toolbarSearchField, options); - return OnToolbarGUI(rect, text); - } - - void FocusAndKeyHandling() - { - Event evt = Event.current; - if (m_WantsFocus && evt.type == EventType.Repaint) - { - GUIUtility.keyboardControl = m_ControlID; - EditorGUIUtility.editingTextField = true; - m_WantsFocus = false; - } - - if (evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.DownArrow || evt.keyCode == KeyCode.UpArrow) && - GUIUtility.keyboardControl == m_ControlID && GUIUtility.hotControl == 0) - { - if (downOrUpArrowKeyPressed != null) - { - downOrUpArrowKeyPressed(); - evt.Use(); - } - } - } - - void CommandEventHandling() - { - Event evt = Event.current; - - if (evt.type != EventType.ExecuteCommand && evt.type != EventType.ValidateCommand) - return; - - if (m_AutoSetFocusOnFindCommand && evt.commandName == EventCommandNames.Find) - { - if (evt.type == EventType.ExecuteCommand) - SetFocus(); - evt.Use(); - } - } - } -} // namespace diff --git a/Editor/Mono/GUI/SplitView.cs b/Editor/Mono/GUI/SplitView.cs index 2c3682beb7..f0fc43a7ff 100644 --- a/Editor/Mono/GUI/SplitView.cs +++ b/Editor/Mono/GUI/SplitView.cs @@ -445,9 +445,9 @@ public bool PerformDrop(EditorWindow dropWindow, DropInfo dropInfo, Vector2 scre parentForDrop.MakeRoomForRect(dropRect); parentForDrop.AddChild(newDockArea, dropIndex); newDockArea.position = dropRect; - DockArea.s_OriginalDragSource.RemoveTab(dropWindow); + DockArea.s_OriginalDragSource.RemoveTab(dropWindow, killIfEmpty: true, sendEvents: false); dropWindow.m_Parent = newDockArea; - newDockArea.AddTab(dropWindow); + newDockArea.AddTab(dropWindow, sendPaneEvents: false); Reflow(); RecalcMinMaxAndReflowAll(this); newDockArea.MakeVistaDWMHappyDance(); diff --git a/Editor/Mono/GUI/Splitter.cs b/Editor/Mono/GUI/Splitter.cs deleted file mode 100644 index 407e25370a..0000000000 --- a/Editor/Mono/GUI/Splitter.cs +++ /dev/null @@ -1,485 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - /// *undocumented* - [System.Serializable] - internal class SplitterState - { - const int defaultSplitSize = 6; - - public int ID; - public int splitterInitialOffset; - public int currentActiveSplitter = -1; - - public int[] realSizes; - public float[] relativeSizes; // these should always add up to 1 - - public int[] minSizes; - public int[] maxSizes; - - public int lastTotalSize = 0; - - public int splitSize; - - public float xOffset; - - public SplitterState(params float[] relativeSizes) - { - Init(relativeSizes, null, null, 0); - } - - public SplitterState(int[] realSizes, int[] minSizes, int[] maxSizes) - { - this.realSizes = realSizes; - this.minSizes = minSizes == null ? new int[realSizes.Length] : minSizes; - this.maxSizes = maxSizes == null ? new int[realSizes.Length] : maxSizes; - relativeSizes = new float[realSizes.Length]; - - this.splitSize = splitSize == 0 ? defaultSplitSize : splitSize; - - RealToRelativeSizes(); - } - - public SplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes) - { - Init(relativeSizes, minSizes, maxSizes, 0); - } - - public SplitterState(float[] relativeSizes, int[] minSizes, int[] maxSizes, int splitSize) - { - Init(relativeSizes, minSizes, maxSizes, splitSize); - } - - private void Init(float[] relativeSizes, int[] minSizes, int[] maxSizes, int splitSize) - { - this.relativeSizes = relativeSizes; - this.minSizes = minSizes == null ? new int[relativeSizes.Length] : minSizes; - this.maxSizes = maxSizes == null ? new int[relativeSizes.Length] : maxSizes; - realSizes = new int[relativeSizes.Length]; - - this.splitSize = splitSize == 0 ? defaultSplitSize : splitSize; - - NormalizeRelativeSizes(); - } - - public void NormalizeRelativeSizes() - { - float check = 1.0f; // try to avoid rounding issues - float total = 0; - int k; - - // distribute space relatively - for (k = 0; k < relativeSizes.Length; k++) - total += relativeSizes[k]; - - for (k = 0; k < relativeSizes.Length; k++) - { - relativeSizes[k] = relativeSizes[k] / total; - check -= relativeSizes[k]; - } - - relativeSizes[relativeSizes.Length - 1] += check; - } - - public void RealToRelativeSizes() - { - float check = 1.0f; // try to avoid rounding issues - float total = 0; - int k; - - // distribute space relatively - for (k = 0; k < realSizes.Length; k++) - total += realSizes[k]; - - for (k = 0; k < realSizes.Length; k++) - { - relativeSizes[k] = realSizes[k] / total; - check -= relativeSizes[k]; - } - if (relativeSizes.Length > 0) - relativeSizes[relativeSizes.Length - 1] += check; - } - - public void RelativeToRealSizes(int totalSpace) - { - int spaceToShare = totalSpace, k; - - for (k = 0; k < relativeSizes.Length; k++) - { - realSizes[k] = (int)Mathf.Round(relativeSizes[k] * totalSpace); - - if (realSizes[k] < minSizes[k]) - realSizes[k] = minSizes[k]; - - spaceToShare -= realSizes[k]; - } - - if (spaceToShare < 0) - { - for (k = 0; k < relativeSizes.Length; k++) - { - if (realSizes[k] > minSizes[k]) - { - int spaceInThisOne = realSizes[k] - minSizes[k]; - int spaceToTake = -spaceToShare < spaceInThisOne ? -spaceToShare : spaceInThisOne; - - spaceToShare += spaceToTake; - realSizes[k] -= spaceToTake; - - if (spaceToShare >= 0) - break; - } - } - } - - int last = realSizes.Length - 1; - if (last >= 0) - { - realSizes[last] += spaceToShare; // try to avoid rounding issues - - if (realSizes[last] < minSizes[last]) // but never ignore min size! - realSizes[last] = minSizes[last]; - } - } - - public void DoSplitter(int i1, int i2, int diff) - { - // TODO: This does not handle all cases properly. Theres a hope we will not encounter those cases in the editor. - // Needs to be fixed once its passed to users. - int h1 = realSizes[i1]; - int h2 = realSizes[i2]; - int m1 = minSizes[i1]; - int m2 = minSizes[i2]; - int x1 = maxSizes[i1]; - int x2 = maxSizes[i2]; - - bool diffed = false; - - if (m1 == 0) m1 = 16; - if (m2 == 0) m2 = 16; - - // min constraint - if (h1 + diff < m1) - { - diff -= m1 - h1; - realSizes[i2] += realSizes[i1] - m1; - realSizes[i1] = m1; - - if (i1 != 0) - DoSplitter(i1 - 1, i2, diff); - else - // can't resize more... - splitterInitialOffset -= diff; - - diffed = true; - } - else if (h2 - diff < m2) - { - diff -= h2 - m2; - realSizes[i1] += realSizes[i2] - m2; - realSizes[i2] = m2; - - if (i2 != realSizes.Length - 1) - DoSplitter(i1, i2 + 1, diff); - else - // can't resize more... - splitterInitialOffset -= diff; - - diffed = true; - } - - // max constraint - if (!diffed) - { - if ((x1 != 0) && (h1 + diff > x1)) - { - diff -= realSizes[i1] - x1; - realSizes[i2] += realSizes[i1] - x1; - realSizes[i1] = x1; - - if (i1 != 0) - DoSplitter(i1 - 1, i2, diff); - else - // can't resize more... - splitterInitialOffset -= diff; - - diffed = true; - } - else if ((x2 != 0) && (h2 - diff > x2)) - { - diff -= h2 - x2; - realSizes[i1] += realSizes[i2] - x2; - realSizes[i2] = x2; - - if (i2 != realSizes.Length - 1) - DoSplitter(i1, i2 + 1, diff); - else - // can't resize more... - splitterInitialOffset -= diff; - - diffed = true; - } - } - - // normal case - we have space for resizing - if (!diffed) - { - realSizes[i1] += diff; - realSizes[i2] -= diff; - } - } - } - - class SplitterGUILayout - { - static int splitterHash = "Splitter".GetHashCode(); - - /// *undocumented* - internal class GUISplitterGroup : GUILayoutGroup - { - public SplitterState state; - - public override void SetHorizontal(float x, float width) - { - if (!isVertical) - { - int k; - - state.xOffset = x; - - if (width != state.lastTotalSize) - { - state.RelativeToRealSizes((int)width); - state.lastTotalSize = (int)width; - - // maintain constraints while resizing - for (k = 0; k < state.realSizes.Length - 1; k++) - state.DoSplitter(k, k + 1, 0); - } - - k = 0; - - foreach (GUILayoutEntry i in entries) - { - float thisSize = state.realSizes[k]; - - i.SetHorizontal(Mathf.Round(x), Mathf.Round(thisSize)); - x += thisSize + spacing; - k++; - } - } - else - { - base.SetHorizontal(x, width); - } - } - - public override void SetVertical(float y, float height) - { - rect.y = y; rect.height = height; - - RectOffset padding = style.padding; - - if (isVertical) - { - // If we have a skin, adjust the sizing to take care of padding (if we don't have a skin the vertical margins have been propagated fully up the hierarchy)... - if (style != GUIStyle.none) - { - float topMar = padding.top, bottomMar = padding.bottom; - if (entries.Count != 0) - { - topMar = Mathf.Max(topMar, ((GUILayoutEntry)entries[0]).margin.top); - bottomMar = Mathf.Max(bottomMar, ((GUILayoutEntry)entries[entries.Count - 1]).margin.bottom); - } - y += topMar; - height -= bottomMar + topMar; - } - - // Set the positions - int k; - - if (height != state.lastTotalSize) - { - state.RelativeToRealSizes((int)height); - state.lastTotalSize = (int)height; - - // maintain constraints while resizing - for (k = 0; k < state.realSizes.Length - 1; k++) - state.DoSplitter(k, k + 1, 0); - } - - k = 0; - - foreach (GUILayoutEntry i in entries) - { - float thisSize = state.realSizes[k]; - - i.SetVertical(Mathf.Round(y), Mathf.Round(thisSize)); - y += thisSize + spacing; - k++; - } - } - else - { - // If we have a GUIStyle here, we need to respect the subelements' margins - if (style != GUIStyle.none) - { - foreach (GUILayoutEntry i in entries) - { - float topMar = Mathf.Max(i.margin.top, padding.top); - float thisY = y + topMar; - float thisHeight = height - Mathf.Max(i.margin.bottom, padding.bottom) - topMar; - - if (i.stretchHeight != 0) - i.SetVertical(thisY, thisHeight); - else - i.SetVertical(thisY, Mathf.Clamp(thisHeight, i.minHeight, i.maxHeight)); - } - } - else - { - // If not, the subelements' margins have already been propagated upwards to this group, so we can safely ignore them - float thisY = y - margin.top; - float thisHeight = height + margin.vertical; - foreach (GUILayoutEntry i in entries) - { - if (i.stretchHeight != 0) - i.SetVertical(thisY + i.margin.top, thisHeight - i.margin.vertical); - else - i.SetVertical(thisY + i.margin.top, Mathf.Clamp(thisHeight - i.margin.vertical, i.minHeight, i.maxHeight)); - } - } - } - } - } - - public static void BeginSplit(SplitterState state, GUIStyle style, bool vertical, params GUILayoutOption[] options) - { - int pos; - var g = (GUISplitterGroup)GUILayoutUtility.BeginLayoutGroup(style, null, typeof(GUISplitterGroup)); - state.ID = GUIUtility.GetControlID(splitterHash, FocusType.Passive); - - switch (Event.current.GetTypeForControl(state.ID)) - { - case EventType.Layout: - { - g.state = state; - g.resetCoords = false; - g.isVertical = vertical; - g.ApplyOptions(options); - break; - } - case EventType.MouseDown: - { - if ((Event.current.button == 0) && (Event.current.clickCount == 1)) - { - int cursor = g.isVertical ? (int)g.rect.y : (int)g.rect.x; - pos = g.isVertical ? (int)Event.current.mousePosition.y : (int)Event.current.mousePosition.x; - - for (int i = 0; i < state.relativeSizes.Length - 1; i++) - { - Rect splitterRect = g.isVertical ? - new Rect(state.xOffset + g.rect.x, cursor + state.realSizes[i] - state.splitSize / 2, g.rect.width, state.splitSize) : - new Rect(state.xOffset + cursor + state.realSizes[i] - state.splitSize / 2, g.rect.y, state.splitSize, g.rect.height); - - if (splitterRect.Contains(Event.current.mousePosition)) - { - state.splitterInitialOffset = pos; - state.currentActiveSplitter = i; - GUIUtility.hotControl = state.ID; - Event.current.Use(); - break; - } - - cursor += (int)state.realSizes[i]; - } - } - break; - } - case EventType.MouseDrag: - { - if ((GUIUtility.hotControl == state.ID) && (state.currentActiveSplitter >= 0)) - { - pos = g.isVertical ? (int)Event.current.mousePosition.y : (int)Event.current.mousePosition.x; - int diff = pos - state.splitterInitialOffset; - - if (diff != 0) - { - state.splitterInitialOffset = pos; - state.DoSplitter(state.currentActiveSplitter, state.currentActiveSplitter + 1, diff); - } - - Event.current.Use(); - } - break; - } - case EventType.MouseUp: - { - if (GUIUtility.hotControl == state.ID) - { - GUIUtility.hotControl = 0; - state.currentActiveSplitter = -1; - state.RealToRelativeSizes(); - Event.current.Use(); - } - break; - } - case EventType.Repaint: - { - int cursor = g.isVertical ? (int)g.rect.y : (int)g.rect.x; - - for (var i = 0; i < state.relativeSizes.Length - 1; i++) - { - var splitterRect = g.isVertical ? - new Rect(state.xOffset + g.rect.x, cursor + state.realSizes[i] - state.splitSize / 2, g.rect.width, state.splitSize) : - new Rect(state.xOffset + cursor + state.realSizes[i] - state.splitSize / 2, g.rect.y, state.splitSize, g.rect.height); - - EditorGUIUtility.AddCursorRect(splitterRect, g.isVertical ? MouseCursor.ResizeVertical : MouseCursor.SplitResizeLeftRight, state.ID); - - cursor += state.realSizes[i]; - } - } - - break; - } - } - - public static void BeginHorizontalSplit(SplitterState state, params GUILayoutOption[] options) - { - BeginSplit(state, GUIStyle.none, false, options); - } - - public static void BeginVerticalSplit(SplitterState state, params GUILayoutOption[] options) - { - BeginSplit(state, GUIStyle.none, true, options); - } - - public static void BeginHorizontalSplit(SplitterState state, GUIStyle style, params GUILayoutOption[] options) - { - BeginSplit(state, style, false, options); - } - - public static void BeginVerticalSplit(SplitterState state, GUIStyle style, params GUILayoutOption[] options) - { - BeginSplit(state, style, true, options); - } - - public static void EndVerticalSplit() - { - GUILayoutUtility.EndLayoutGroup(); - } - - public static void EndHorizontalSplit() - { - GUILayoutUtility.EndLayoutGroup(); - } - } -} diff --git a/Editor/Mono/GUI/TextFieldDropDown.cs b/Editor/Mono/GUI/TextFieldDropDown.cs deleted file mode 100644 index c6bc16c559..0000000000 --- a/Editor/Mono/GUI/TextFieldDropDown.cs +++ /dev/null @@ -1,44 +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 System.Collections.Generic; - -namespace UnityEditor -{ - public sealed partial class EditorGUI - { - private const string kEmptyDropDownElement = "--empty--"; - - static internal string DoTextFieldDropDown(Rect rect, int id, string text, string[] dropDownElements, bool delayed) - { - Rect textFieldRect = new Rect(rect.x, rect.y, rect.width - EditorStyles.textFieldDropDown.fixedWidth, rect.height); - Rect popupRect = new Rect(textFieldRect.xMax, textFieldRect.y, EditorStyles.textFieldDropDown.fixedWidth, rect.height); - - - if (delayed) - { - text = DelayedTextField(textFieldRect, text, EditorStyles.textFieldDropDownText); - } - else - { - bool dummy; - text = DoTextField(s_RecycledEditor, id, textFieldRect, text, EditorStyles.textFieldDropDownText, null, out dummy, false, false, false); - } - - - EditorGUI.BeginChangeCheck(); - int oldIndent = EditorGUI.indentLevel; - EditorGUI.indentLevel = 0; - int parameterIndex = EditorGUI.Popup(popupRect, "", -1, dropDownElements.Length > 0 ? dropDownElements : new string[] { kEmptyDropDownElement }, EditorStyles.textFieldDropDown); - if (EditorGUI.EndChangeCheck() && dropDownElements.Length > 0) - { - text = dropDownElements[parameterIndex]; - } - EditorGUI.indentLevel = oldIndent; - return text; - } - } -} diff --git a/Editor/Mono/GUI/Toolbar.cs b/Editor/Mono/GUI/Toolbar.cs index 22e979d006..12cebecd4d 100644 --- a/Editor/Mono/GUI/Toolbar.cs +++ b/Editor/Mono/GUI/Toolbar.cs @@ -137,6 +137,7 @@ protected override void OnDisable() public static Toolbar get = null; public static bool requestShowCollabToolbar = false; + public static bool isLastShowRequestPartial = true; internal static string lastLoadedLayoutName { diff --git a/Editor/Mono/GUI/Tools/SnapSettings.cs b/Editor/Mono/GUI/Tools/SnapSettings.cs deleted file mode 100644 index 7f897ac561..0000000000 --- a/Editor/Mono/GUI/Tools/SnapSettings.cs +++ /dev/null @@ -1,154 +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 UnityEditor; - -namespace UnityEditor -{ - internal class SnapSettings : EditorWindow - { - private static float s_MoveSnapX; - private static float s_MoveSnapY; - private static float s_MoveSnapZ; - - private static float s_ScaleSnap; - private static float s_RotationSnap; - - private static bool s_Initialized; - - private static void Initialize() - { - if (!s_Initialized) - { - s_MoveSnapX = EditorPrefs.GetFloat("MoveSnapX", 1f); - s_MoveSnapY = EditorPrefs.GetFloat("MoveSnapY", 1f); - s_MoveSnapZ = EditorPrefs.GetFloat("MoveSnapZ", 1f); - - s_ScaleSnap = EditorPrefs.GetFloat("ScaleSnap", .1f); - s_RotationSnap = EditorPrefs.GetFloat("RotationSnap", 15); - - s_Initialized = true; - } - } - - public static Vector3 move - { - get - { - Initialize(); - return new Vector3(s_MoveSnapX, s_MoveSnapY, s_MoveSnapZ); - } - set - { - EditorPrefs.SetFloat("MoveSnapX", value.x); - s_MoveSnapX = value.x; - EditorPrefs.SetFloat("MoveSnapY", value.y); - s_MoveSnapY = value.y; - EditorPrefs.SetFloat("MoveSnapZ", value.z); - s_MoveSnapZ = value.z; - } - } - - public static float scale - { - get - { - Initialize(); - return s_ScaleSnap; - } - set - { - EditorPrefs.SetFloat("ScaleSnap", value); - s_ScaleSnap = value; - } - } - - public static float rotation - { - get - { - Initialize(); - return s_RotationSnap; - } - set - { - EditorPrefs.SetFloat("RotationSnap", value); - s_RotationSnap = value; - } - } - - [MenuItem("Edit/Snap Settings...")] - static void ShowSnapSettings() - { - EditorWindow.GetWindowWithRect(new Rect(100, 100, 230, 130), true, "Snap settings"); - } - - class Styles - { - public GUIStyle buttonLeft = "ButtonLeft"; - public GUIStyle buttonMid = "ButtonMid"; - public GUIStyle buttonRight = "ButtonRight"; - public GUIContent snapAllAxes = EditorGUIUtility.TrTextContent("Snap All Axes", "Snaps selected objects to the grid"); - public GUIContent snapX = EditorGUIUtility.TrTextContent("X", "Snaps selected objects to the grid on the x axis"); - public GUIContent snapY = EditorGUIUtility.TrTextContent("Y", "Snaps selected objects to the grid on the y axis"); - public GUIContent snapZ = EditorGUIUtility.TrTextContent("Z", "Snaps selected objects to the grid on the z axis"); - public GUIContent moveX = EditorGUIUtility.TrTextContent("Move X", "Grid spacing X"); - public GUIContent moveY = EditorGUIUtility.TrTextContent("Move Y", "Grid spacing Y"); - public GUIContent moveZ = EditorGUIUtility.TrTextContent("Move Z", "Grid spacing Z"); - public GUIContent scale = EditorGUIUtility.TrTextContent("Scale", "Grid spacing for scaling"); - public GUIContent rotation = EditorGUIUtility.TrTextContent("Rotation", "Grid spacing for rotation in degrees"); - } - static Styles ms_Styles; - - void OnGUI() - { - if (ms_Styles == null) - ms_Styles = new Styles(); - - GUILayout.Space(5); - - EditorGUI.BeginChangeCheck(); - Vector3 m = move; - m.x = EditorGUILayout.FloatField(ms_Styles.moveX, m.x); - m.y = EditorGUILayout.FloatField(ms_Styles.moveY, m.y); - m.z = EditorGUILayout.FloatField(ms_Styles.moveZ, m.z); - - if (EditorGUI.EndChangeCheck()) - { - if (m.x <= 0) m.x = move.x; - if (m.y <= 0) m.y = move.y; - if (m.z <= 0) m.z = move.z; - move = m; - } - scale = EditorGUILayout.FloatField(ms_Styles.scale, scale); - rotation = EditorGUILayout.FloatField(ms_Styles.rotation, rotation); - - GUILayout.Space(5); - - bool snapX = false, snapY = false, snapZ = false; - GUILayout.BeginHorizontal(); - if (GUILayout.Button(ms_Styles.snapAllAxes, ms_Styles.buttonLeft)) { snapX = true; snapY = true; snapZ = true; } - if (GUILayout.Button(ms_Styles.snapX, ms_Styles.buttonMid)) { snapX = true; } - if (GUILayout.Button(ms_Styles.snapY, ms_Styles.buttonMid)) { snapY = true; } - if (GUILayout.Button(ms_Styles.snapZ, ms_Styles.buttonRight)) { snapZ = true; } - GUILayout.EndHorizontal(); - - if (snapX | snapY | snapZ) - { - Vector3 scaleTmp = new Vector3(1.0f / move.x, 1.0f / move.y, 1.0f / move.z); - - Undo.RecordObjects(Selection.transforms, "Snap " + (Selection.transforms.Length == 1 ? Selection.activeGameObject.name : " selection") + " to grid"); - foreach (Transform t in Selection.transforms) - { - Vector3 pos = t.position; - if (snapX) pos.x = Mathf.Round(pos.x * scaleTmp.x) / scaleTmp.x; - if (snapY) pos.y = Mathf.Round(pos.y * scaleTmp.y) / scaleTmp.y; - if (snapZ) pos.z = Mathf.Round(pos.z * scaleTmp.z) / scaleTmp.z; - t.position = pos; - } - } - } - } -} // namespace diff --git a/Editor/Mono/GUI/TreeView/GameObjectTreeViewDataSource.cs b/Editor/Mono/GUI/TreeView/GameObjectTreeViewDataSource.cs index 26f2ba9e37..1182c65d9d 100644 --- a/Editor/Mono/GUI/TreeView/GameObjectTreeViewDataSource.cs +++ b/Editor/Mono/GUI/TreeView/GameObjectTreeViewDataSource.cs @@ -208,10 +208,6 @@ void CreateRootItem(HierarchyProperty property) // All game objects m_RootItem = new GameObjectTreeViewItem(m_RootInstanceID, rootDepth, null, "RootOfAll"); } - - // Ensure root is expanded if not shown - if (!showRootItem) - SetExpanded(m_RootItem, true); } void ClearSearchFilter() diff --git a/Editor/Mono/GUI/TreeView/ITreeViewDataSource.cs b/Editor/Mono/GUI/TreeView/ITreeViewDataSource.cs deleted file mode 100644 index 5a7ae5cb3f..0000000000 --- a/Editor/Mono/GUI/TreeView/ITreeViewDataSource.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 System.Collections.Generic; -using UnityEngine; - -// The TreeView requires implementations from the following three interfaces: -// ITreeViewDataSource: Should handle data fetching, build the tree/data structure and hold expanded state -// ITreeViewGUI: Should handle visual representation of TreeView and input handling -// ITreeViewDragging Should handle dragging, temp expansion of items, allow/disallow dropping -// The TreeView handles: Navigation, Item selection and initiates dragging - - -namespace UnityEditor.IMGUI.Controls -{ - // Represents a complete data tree - internal interface ITreeViewDataSource - { - void OnInitialize(); - - // Return root of tree - TreeViewItem root { get; } - - // For data sources where GetRows() might be an expensive operation - int rowCount { get; } - - // Reload data - void ReloadData(); - - void InitIfNeeded(); - - // Find Item by id - TreeViewItem FindItem(int id); - - // Get current row of an item (using the current expanded state in TreeViewState) - // Returns -1 if not found - int GetRow(int id); - - // Check rowCount before requesting - TreeViewItem GetItem(int row); - - // Get the flattened tree of visible items. If possible use GetItem(int row) instead - IList GetRows(); - - bool IsRevealed(int id); - - void RevealItem(int id); - - // Expand / collapse interface - // The DataSource has the interface for this because it should be able to rebuild - // tree when expanding - void SetExpandedWithChildren(TreeViewItem item, bool expand); - void SetExpanded(TreeViewItem item, bool expand); - bool IsExpanded(TreeViewItem item); - bool IsExpandable(TreeViewItem item); - void SetExpandedWithChildren(int id, bool expand); - int[] GetExpandedIDs(); - void SetExpandedIDs(int[] ids); - bool SetExpanded(int id, bool expand); - bool IsExpanded(int id); - - // Selection - bool CanBeMultiSelected(TreeViewItem item); - bool CanBeParent(TreeViewItem item); - - // Renaming - bool IsRenamingItemAllowed(TreeViewItem item); - void InsertFakeItem(int id, int parentID, string name, Texture2D icon); - void RemoveFakeItem(); - bool HasFakeItem(); - - // Search - void OnSearchChanged(); - } -} // namespace UnityEditor diff --git a/Editor/Mono/GUI/TreeView/ITreeViewDragging.cs b/Editor/Mono/GUI/TreeView/ITreeViewDragging.cs deleted file mode 100644 index f7fad5c91f..0000000000 --- a/Editor/Mono/GUI/TreeView/ITreeViewDragging.cs +++ /dev/null @@ -1,30 +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.Collections.Generic; -using UnityEngine; - - -namespace UnityEditor.IMGUI.Controls -{ - // The TreeView requires implementations from the following three interfaces: - // ITreeViewDataSource: Should handle data fetching and data structure - // ITreeViewGUI: Should handle visual representation of TreeView and input handling - // ITreeViewDragging Should handle dragging, temp expansion of items, allow/disallow dropping - // The TreeView handles: Navigation, Item selection and initiates dragging - - - // DragNDrop interface for tree views - internal interface ITreeViewDragging - { - void OnInitialize(); - bool CanStartDrag(TreeViewItem targetItem, List draggedItemIDs, Vector2 mouseDownPosition); - void StartDrag(TreeViewItem draggedItem, List draggedItemIDs); - bool DragElement(TreeViewItem targetItem, Rect targetItemRect, int row); // 'targetItem' is null when not hovering over any target Item. Returns true if drag was handled. - void DragCleanup(bool revertExpanded); - int GetDropTargetControlID(); - int GetRowMarkerControlID(); - bool drawRowMarkerAbove { get; set; } - } -} diff --git a/Editor/Mono/GUI/TreeView/ITreeViewGUI.cs b/Editor/Mono/GUI/TreeView/ITreeViewGUI.cs deleted file mode 100644 index 5a58489427..0000000000 --- a/Editor/Mono/GUI/TreeView/ITreeViewGUI.cs +++ /dev/null @@ -1,54 +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; - -// The TreeView requires implementations from the following three interfaces: -// ITreeViewDataSource: Should handle data fetching and data structure -// ITreeViewGUI: Should handle visual representation of TreeView and input handling -// ITreeViewDragging Should handle dragging, temp expansion of items, allow/disallow dropping -// The TreeView handles: Navigation, Item selection and initiates dragging - - -namespace UnityEditor.IMGUI.Controls -{ - internal interface ITreeViewGUI - { - void OnInitialize(); - - // Should return the size of the entire visible content (in pixels). - Vector2 GetTotalSize(); - - // Should return the row number of the first and last row thats fits between top pixel and the height of the window - // If the treeview contains items with varying heights then use the minium height for determining the lastRowVisible - // this is needed when animating the treeview to ensure all items are rendered while animating. - // Can use TreeView.GetTotalRect and m_TreeView.state.scrollPos.y for calculating first and last values - void GetFirstAndLastRowVisible(out int firstRowVisible, out int lastRowVisible); - - Rect GetRowRect(int row, float rowWidth); - Rect GetRectForFraming(int row); - - int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView); - - // OnGUI: Implement to handle TreeView OnGUI - void OnRowGUI(Rect rowRect, TreeViewItem item, int row, bool selected, bool focused); - void BeginRowGUI(); // use for e.g clearing state before OnRowGUI calls - void EndRowGUI(); // use for handling stuff after all rows have had their OnRowGUI - - // Ping Item interface (implement a rendering of a 'ping' for a Item). - void BeginPingItem(TreeViewItem item, float topPixelOfRow, float availableWidth); - void EndPingItem(); - - // Rename interface (BeginRename should return true if rename is handled) - bool BeginRename(TreeViewItem item, float delay); - void EndRename(); - Rect GetRenameRect(Rect rowRect, int row, TreeViewItem item); - - float GetContentIndent(TreeViewItem item); - - float halfDropBetweenHeight { get; } - float topRowMargin { get; } - float bottomRowMargin { get; } - } -} diff --git a/Editor/Mono/GUI/TreeView/LazyTreeViewDataSource.cs b/Editor/Mono/GUI/TreeView/LazyTreeViewDataSource.cs deleted file mode 100644 index 20034bd783..0000000000 --- a/Editor/Mono/GUI/TreeView/LazyTreeViewDataSource.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.Collections.Generic; -using System.Linq; - - -namespace UnityEditor.IMGUI.Controls -{ - // LazyTreeViewDataSource assumes that the Item tree only contains visible items, optimal for large data sets. - // Usage: - // - Override FetchData () and build the tree with visible items with m_RootItem as root (and and populate the m_VisibleRows List) - // - FetchData () is called every time the expanded state changes. - // - Configure showRootItem and rootIsCollapsable as wanted - // - // Note: if dealing with small trees consider using TreeViewDataSource instead: it assumes that the tree contains all items. - - internal abstract class LazyTreeViewDataSource : TreeViewDataSource - { - public LazyTreeViewDataSource(TreeViewController treeView) - : base(treeView) - { - } - - public static List CreateChildListForCollapsedParent() - { - // To mark a collapsed parent we use a list with one element that is null. - // The null element in the children list ensures we show the collapse arrow. - return new List() { null }; - } - - public static bool IsChildListForACollapsedParent(IList childList) - { - return (childList != null && childList.Count == 1 && childList[0] == null); // see CreateChildListForCollapsedParent - } - - // Return all ancestor items of the Item with 'id' - protected abstract HashSet GetParentsAbove(int id); - - // Return all descendant items that have children from the Item with 'id' - protected abstract HashSet GetParentsBelow(int id); - - override public void RevealItem(int itemID) - { - // Get existing expanded in hashset - HashSet expandedSet = new HashSet(expandedIDs); - int orgSize = expandedSet.Count; - - // Get all parents above id - HashSet candidates = GetParentsAbove(itemID); - - // Add parent ids - expandedSet.UnionWith(candidates); - - if (orgSize != expandedSet.Count) - { - // Bulk set expanded ids (is sorted in SetExpandedIDs) - SetExpandedIDs(expandedSet.ToArray()); - - // Refresh immediately if any Item was expanded - if (m_NeedRefreshRows) - FetchData(); - } - } - - override public TreeViewItem FindItem(int itemID) - { - // Since this is a LazyTreeViewDataSource that only knows about expanded items - // we need to reveal the item before searching for it (expand its ancestors) - RevealItem(itemID); - - // Now find the item after we have expanded and created parent items - return base.FindItem(itemID); - } - - override public void SetExpandedWithChildren(TreeViewItem item, bool expand) - { - SetExpandedWithChildren(item.id, expand); - } - - // Override for special handling of recursion - // We cannot recurse normally to tree Item children because we have not loaded children of collapsed items - // therefore let client implement GetParentsBelow to fetch ids instead - override public void SetExpandedWithChildren(int id, bool expand) - { - // Get existing expanded in hashset - HashSet oldExpandedSet = new HashSet(expandedIDs); - - // Add all children expanded ids to hashset - HashSet candidates = GetParentsBelow(id); - - if (expand) oldExpandedSet.UnionWith(candidates); - else oldExpandedSet.ExceptWith(candidates); - - // Bulk set expanded ids (is sorted in SetExpandedIDs) - SetExpandedIDs(oldExpandedSet.ToArray()); - - // Keep for debugging - // Debug.Log ("New expanded state (bulk): " + DebugUtils.ListToString(new List(expandedIDs))); - } - - public override void InitIfNeeded() - { - // Cached for large trees... - if (m_Rows == null || m_NeedRefreshRows) - { - FetchData(); // Only need to fetch visible data.. - - m_NeedRefreshRows = false; - - if (onVisibleRowsChanged != null) - onVisibleRowsChanged(); - - m_TreeView.Repaint(); - } - } - - // Get the flattened tree of visible items. Use GetFirstAndLastRowVisible to cull invisible items - override public IList GetRows() - { - InitIfNeeded(); - return m_Rows; - } - } -} diff --git a/Editor/Mono/GUI/TreeView/MultiColumnHeader.cs b/Editor/Mono/GUI/TreeView/MultiColumnHeader.cs deleted file mode 100644 index dacafac7d6..0000000000 --- a/Editor/Mono/GUI/TreeView/MultiColumnHeader.cs +++ /dev/null @@ -1,497 +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; - -namespace UnityEditor.IMGUI.Controls -{ - public partial class MultiColumnHeader - { - MultiColumnHeaderState m_State; - float m_Height = DefaultGUI.defaultHeight; - float m_DividerWidth = 6; - Rect m_PreviousRect; - bool m_ResizeToFit = false; - bool m_CanSort = true; - GUIView m_GUIView; - Rect[] m_ColumnRects; - - public delegate void HeaderCallback(MultiColumnHeader multiColumnHeader); - public event HeaderCallback sortingChanged; - public event HeaderCallback visibleColumnsChanged; - - public MultiColumnHeader(MultiColumnHeaderState state) - { - m_State = state; - } - - public int sortedColumnIndex - { - get { return state.sortedColumnIndex; } - set - { - if (value != state.sortedColumnIndex) - { - state.sortedColumnIndex = value; - OnSortingChanged(); - } - } - } - - public void SetSortingColumns(int[] columnIndices, bool[] sortAscending) - { - if (columnIndices == null) - throw new ArgumentNullException("columnIndices"); - - if (sortAscending == null) - throw new ArgumentNullException("sortAscending"); - - if (columnIndices.Length != sortAscending.Length) - throw new ArgumentException("Input arrays should have same length"); - - if (columnIndices.Length > state.maximumNumberOfSortedColumns) - throw new ArgumentException("The maximum number of sorted columns is " + state.maximumNumberOfSortedColumns + ". Trying to set " + columnIndices.Length + " columns."); - - if (columnIndices.Length != columnIndices.Distinct().Count()) - throw new ArgumentException("Duplicate column indices are not allowed", "columnIndices"); - - bool changed = false; - - if (!columnIndices.SequenceEqual(state.sortedColumns)) - { - state.sortedColumns = columnIndices; - changed = true; - } - - for (int i = 0; i < columnIndices.Length; ++i) - { - var column = GetColumn(columnIndices[i]); - if (column.sortedAscending != sortAscending[i]) - { - column.sortedAscending = sortAscending[i]; - changed = true; - } - } - - if (changed) - OnSortingChanged(); - } - - public void SetSorting(int columnIndex, bool sortAscending) - { - bool changed = false; - if (state.sortedColumnIndex != columnIndex) - { - state.sortedColumnIndex = columnIndex; - changed = true; - } - - var column = GetColumn(columnIndex); - if (column.sortedAscending != sortAscending) - { - column.sortedAscending = sortAscending; - changed = true; - } - - if (changed) - OnSortingChanged(); - } - - public void SetSortDirection(int columnIndex, bool sortAscending) - { - var column = GetColumn(columnIndex); - if (column.sortedAscending != sortAscending) - { - column.sortedAscending = sortAscending; - OnSortingChanged(); - } - } - - public bool IsSortedAscending(int columnIndex) - { - return GetColumn(columnIndex).sortedAscending; - } - - public MultiColumnHeaderState.Column GetColumn(int columnIndex) - { - if (columnIndex < 0 || columnIndex >= state.columns.Length) - throw new ArgumentOutOfRangeException("columnIndex", string.Format("columnIndex {0} is not valid when the current column count is {1}", columnIndex, state.columns.Length)); - return state.columns[columnIndex]; - } - - public MultiColumnHeaderState state - { - get { return m_State; } - set - { - if (value == null) - throw new ArgumentNullException("state", "MultiColumnHeader state is not allowed to be null"); - m_State = value; - } - } - - public float height - { - get { return m_Height; } - set { m_Height = value; } - } - - public bool canSort - { - get { return m_CanSort; } - set - { - m_CanSort = value; - height = m_Height; - } - } - - public bool IsColumnVisible(int columnIndex) - { - return state.visibleColumns.Any(t => t == columnIndex); - } - - public int GetVisibleColumnIndex(int columnIndex) - { - for (int i = 0; i < state.visibleColumns.Length; i++) - { - if (state.visibleColumns[i] == columnIndex) - return i; - } - string visibleIndices = string.Join(", ", state.visibleColumns.Select(t => t.ToString()).ToArray()); - throw new ArgumentException(string.Format("Invalid columnIndex: {0}. The index is not part of the current visible columns: {1}", columnIndex, visibleIndices), "columnIndex"); - } - - public Rect GetCellRect(int visibleColumnIndex, Rect rowRect) - { - Rect result = GetColumnRect(visibleColumnIndex); - result.y = rowRect.y; - result.height = rowRect.height; - return result; - } - - public Rect GetColumnRect(int visibleColumnIndex) - { - if (visibleColumnIndex < 0 || visibleColumnIndex >= m_ColumnRects.Length) - throw new ArgumentException(string.Format("The provided visibleColumnIndex is invalid. Ensure the index ({0}) is within the number of visible columns ({1})", visibleColumnIndex, m_ColumnRects.Length), "visibleColumnIndex"); - - return m_ColumnRects[visibleColumnIndex]; - } - - public void ResizeToFit() - { - m_ResizeToFit = true; - Repaint(); - } - - void UpdateColumnHeaderRects(Rect totalHeaderRect) - { - if (m_ColumnRects == null || m_ColumnRects.Length != state.visibleColumns.Length) - m_ColumnRects = new Rect[state.visibleColumns.Length]; - - Rect curRect = totalHeaderRect; - for (int v = 0; v < state.visibleColumns.Length; v++) - { - int columnIndex = state.visibleColumns[v]; - MultiColumnHeaderState.Column column = state.columns[columnIndex]; - - if (v > 0) - curRect.x += curRect.width; - curRect.width = column.width; - - m_ColumnRects[v] = curRect; - } - } - - // Virtual so clients can override header behavior and rendering entirely - public virtual void OnGUI(Rect rect, float xScroll) - { - Event evt = Event.current; - - if (m_GUIView == null) - m_GUIView = GUIView.current; - - DetectSizeChanges(rect); - - if (m_ResizeToFit && evt.type == EventType.Repaint) - { - m_ResizeToFit = false; - ResizeColumnsWidthsProportionally(rect.width - GUI.skin.verticalScrollbar.fixedWidth - state.widthOfAllVisibleColumns); - } - - // We create a guiclip to let the header be able to scroll horizontally according to the tree view's horizontal scroll - GUIClip.Push(rect, new Vector2(-xScroll, 0f), Vector2.zero, false); - { - Rect localRect = new Rect(0, 0, rect.width, rect.height); - - // Background ( We always add the width of the vertical scrollbar to accomodate if this is being shown below e.g by a tree view) - float widthOfAllColumns = state.widthOfAllVisibleColumns; - float backgroundWidth = (localRect.width > widthOfAllColumns ? localRect.width : widthOfAllColumns) + GUI.skin.verticalScrollbar.fixedWidth; - Rect backgroundRect = new Rect(0, 0, backgroundWidth, localRect.height); - GUI.Label(backgroundRect, GUIContent.none, DefaultStyles.background); - - // Context menu - if (evt.type == EventType.ContextClick && backgroundRect.Contains(evt.mousePosition)) - { - evt.Use(); - DoContextMenu(); - } - - // Update column rects (cached for clients to have fast access to column rects by using GetCellRect) - UpdateColumnHeaderRects(localRect); - - // Columns - for (int v = 0; v < state.visibleColumns.Length; v++) - { - int columnIndex = state.visibleColumns[v]; - MultiColumnHeaderState.Column column = state.columns[columnIndex]; - - Rect headerRect = m_ColumnRects[v]; - const float limitHeightOfDivider = 4f; - Rect dividerRect = new Rect(headerRect.xMax - 1, headerRect.y + limitHeightOfDivider, 1f, headerRect.height - 2 * limitHeightOfDivider); - - // Resize columns logic - Rect dragRect = new Rect(dividerRect.x - m_DividerWidth * 0.5f, localRect.y, m_DividerWidth, localRect.height); - bool hasControl; - column.width = EditorGUI.WidthResizer(dragRect, column.width, column.minWidth, column.maxWidth, out hasControl); - if (hasControl && evt.type == EventType.Repaint) - { - DrawColumnResizing(headerRect, column); - } - - // Draw divider (can be overridden) - DrawDivider(dividerRect, column); - - // Draw header (can be overridden) - ColumnHeaderGUI(column, headerRect, columnIndex); - } - } - GUIClip.Pop(); - } - - internal virtual void DrawColumnResizing(Rect headerRect, MultiColumnHeaderState.Column column) - { - const float margin = 1; - headerRect.y += margin; - headerRect.width -= margin; - headerRect.height -= 2 * margin; - EditorGUI.DrawRect(headerRect, new Color(0.5f, 0.5f, 0.5f, 0.1f)); - } - - internal virtual void DrawDivider(Rect dividerRect, MultiColumnHeaderState.Column column) - { - EditorGUI.DrawRect(dividerRect, new Color(0.5f, 0.5f, 0.5f, 0.5f)); - } - - protected virtual void ColumnHeaderClicked(MultiColumnHeaderState.Column column, int columnIndex) - { - if (state.sortedColumnIndex == columnIndex) - column.sortedAscending = !column.sortedAscending; - else - state.sortedColumnIndex = columnIndex; - - OnSortingChanged(); - } - - protected virtual void OnSortingChanged() - { - if (sortingChanged != null) - sortingChanged(this); - } - - protected virtual void ColumnHeaderGUI(MultiColumnHeaderState.Column column, Rect headerRect, int columnIndex) - { - if (canSort && column.canSort) - { - SortingButton(column, headerRect, columnIndex); - } - - GUIStyle style = GetStyle(column.headerTextAlignment); - - float labelHeight = EditorGUIUtility.singleLineHeight; - Rect labelRect = new Rect(headerRect.x, headerRect.yMax - labelHeight - DefaultGUI.labelSpaceFromBottom, headerRect.width, labelHeight); - GUI.Label(labelRect, column.headerContent, style); - } - - protected void SortingButton(MultiColumnHeaderState.Column column, Rect headerRect, int columnIndex) - { - // Button logic - if (EditorGUI.Button(headerRect, GUIContent.none, GUIStyle.none)) - { - ColumnHeaderClicked(column, columnIndex); - } - - // Draw sorting arrow - if (columnIndex == state.sortedColumnIndex && Event.current.type == EventType.Repaint) - { - var arrowRect = GetArrowRect(column, headerRect); - - Matrix4x4 normalMatrix = GUI.matrix; - if (column.sortedAscending) - GUIUtility.RotateAroundPivot(180, arrowRect.center - new Vector2(0, 1)); - - GUI.Label(arrowRect, "\u25BE", DefaultStyles.arrowStyle); - - if (column.sortedAscending) - GUI.matrix = normalMatrix; - } - } - - internal virtual Rect GetArrowRect(MultiColumnHeaderState.Column column, Rect headerRect) - { - float sortingArrowWidth = DefaultStyles.arrowStyle.fixedWidth; - float arrowYPos = headerRect.y; - float arrowXPos = 0f; - - switch (column.sortingArrowAlignment) - { - case TextAlignment.Left: - arrowXPos = headerRect.x + DefaultStyles.columnHeader.padding.left; - break; - case TextAlignment.Center: - arrowXPos = headerRect.x + headerRect.width * 0.5f - sortingArrowWidth * 0.5f; - break; - case TextAlignment.Right: - arrowXPos = headerRect.xMax - DefaultStyles.columnHeader.padding.right - sortingArrowWidth; - break; - default: - Debug.LogError("Unhandled enum"); - break; - } - - Rect arrowRect = new Rect(Mathf.Round(arrowXPos), arrowYPos, sortingArrowWidth, 16f); - return arrowRect; - } - - GUIStyle GetStyle(TextAlignment alignment) - { - switch (alignment) - { - case TextAlignment.Left: return DefaultStyles.columnHeader; - case TextAlignment.Center: return DefaultStyles.columnHeaderCenterAligned; - case TextAlignment.Right: return DefaultStyles.columnHeaderRightAligned; - default: return DefaultStyles.columnHeader; - } - } - - void DoContextMenu() - { - var menu = new GenericMenu(); - AddColumnHeaderContextMenuItems(menu); - menu.ShowAsContext(); - } - - protected virtual void AddColumnHeaderContextMenuItems(GenericMenu menu) - { - menu.AddItem(EditorGUIUtility.TrTextContent("Resize to Fit"), false, ResizeToFit); - - menu.AddSeparator(""); - - for (int i = 0; i < state.columns.Length; ++i) - { - var column = state.columns[i]; - var menuText = !string.IsNullOrEmpty(column.contextMenuText) ? column.contextMenuText : column.headerContent.text; - if (column.allowToggleVisibility) - menu.AddItem(new GUIContent(menuText), state.visibleColumns.Contains(i), ToggleVisibility, i); - else - menu.AddDisabledItem(new GUIContent(menuText)); - } - } - - protected virtual void OnVisibleColumnsChanged() - { - if (visibleColumnsChanged != null) - visibleColumnsChanged(this); - } - - void ToggleVisibility(object userData) - { - ToggleVisibility((int)userData); - } - - protected virtual void ToggleVisibility(int columnIndex) - { - var newVisibleColumns = new List(state.visibleColumns); - if (newVisibleColumns.Contains(columnIndex)) - { - newVisibleColumns.Remove(columnIndex); - } - else - { - newVisibleColumns.Add(columnIndex); - newVisibleColumns.Sort(); - } - state.visibleColumns = newVisibleColumns.ToArray(); - Repaint(); - - OnVisibleColumnsChanged(); - } - - public void Repaint() - { - if (m_GUIView != null) - m_GUIView.Repaint(); - } - - void DetectSizeChanges(Rect rect) - { - if (Event.current.type == EventType.Repaint) - { - if (m_PreviousRect.width > 0f) - { - float deltaWidth = Mathf.Round(rect.width - m_PreviousRect.width); - if (deltaWidth != 0f) - { - float tep = GUI.skin.verticalScrollbar.fixedWidth; - bool isColumnsVisible = rect.width - tep > state.widthOfAllVisibleColumns; - if (isColumnsVisible || deltaWidth < 0f) - ResizeColumnsWidthsProportionally(deltaWidth); - } - } - m_PreviousRect = rect; - } - } - - void ResizeColumnsWidthsProportionally(float deltaWidth) - { - // Find auto resizing columns - List autoResizeColumns = null; - foreach (int i in state.visibleColumns) - { - MultiColumnHeaderState.Column column = state.columns[i]; - if (column.autoResize) - { - // Ignore the columns that cannot expand anymore - if (deltaWidth > 0f && column.width >= column.maxWidth) - continue; - // Ignore the columns that cannot shrink anymore - if (deltaWidth < 0f && column.width <= column.minWidth) - continue; - - if (autoResizeColumns == null) - autoResizeColumns = new List(); - - autoResizeColumns.Add(column); - } - } - - // Any auto resizing columns? - if (autoResizeColumns == null) - return; - - // Sum - float totalAutoResizeWidth = autoResizeColumns.Sum(x => x.width); - - // Distribute - foreach (var column in autoResizeColumns) - { - column.width += deltaWidth * (column.width / totalAutoResizeWidth); - column.width = Mathf.Clamp(column.width, column.minWidth, column.maxWidth); - } - } - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDataSource.cs b/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDataSource.cs deleted file mode 100644 index 7fef75d816..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDataSource.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; - -namespace UnityEditor.IMGUI.Controls -{ - public partial class TreeView - { - internal class TreeViewControlDataSource : LazyTreeViewDataSource - { - readonly TreeView m_Owner; - - public TreeViewControlDataSource(TreeViewController treeView, TreeView owner) : base(treeView) - { - m_Owner = owner; - - // The user should just create the visible rows, we create the hidden root - showRootItem = false; - } - - public override void ReloadData() - { - // Clear root item to ensure client gets a call to BuildRoot every time Reload is called - m_RootItem = null; - base.ReloadData(); - } - - void ValidateRootItem() - { - if (m_RootItem == null) - { - throw new NullReferenceException("BuildRoot should set a valid root item."); - } - if (m_RootItem.depth != -1) - { - Debug.LogError("BuildRoot should ensure the root item has a depth == -1. The visible items start at depth == 0."); - m_RootItem.depth = -1; - } - if (m_RootItem.children == null && !m_Owner.m_OverriddenMethods.hasBuildRows) - { - throw new InvalidOperationException("TreeView: 'rootItem.children == null'. Did you forget to add children? If you intend to only create the list of rows (not the full tree) then you need to override: BuildRows, GetAncestors and GetDescendantsThatHaveChildren."); - } - } - - public override void FetchData() - { - // Set before BuildRoot and BuildRows so we can call GetRows in them without recursion - m_NeedRefreshRows = false; - - // Root - if (m_RootItem == null) - { - m_RootItem = m_Owner.BuildRoot(); - ValidateRootItem(); - } - - // Rows - m_Rows = m_Owner.BuildRows(m_RootItem); - if (m_Rows == null) - throw new NullReferenceException("RefreshRows should set valid list of rows."); - - // Custom row rects - if (m_Owner.m_OverriddenMethods.hasGetCustomRowHeight) - m_Owner.m_GUI.RefreshRowRects(m_Rows); - } - - public void SearchFullTree(string search, List result) - { - if (string.IsNullOrEmpty(search)) - throw new ArgumentException("Invalid search: cannot be null or empty", "search"); - - if (result == null) - throw new ArgumentException("Invalid list: cannot be null", "result"); - - var stack = new Stack(); - stack.Push(m_RootItem); - while (stack.Count > 0) - { - TreeViewItem current = stack.Pop(); - if (current.children != null) - { - foreach (var child in current.children) - { - if (child != null) - { - if (m_Owner.DoesItemMatchSearch(child, search)) - result.Add(child); - - stack.Push(child); - } - } - } - } - - result.Sort((x, y) => EditorUtility.NaturalCompare(x.displayName, y.displayName)); - } - - protected override HashSet GetParentsAbove(int id) - { - return new HashSet(m_Owner.GetAncestors(id)); - } - - protected override HashSet GetParentsBelow(int id) - { - return new HashSet(m_Owner.GetDescendantsThatHaveChildren(id)); - } - - public override bool IsExpandable(TreeViewItem item) - { - return m_Owner.CanChangeExpandedState(item); - } - - public override bool CanBeMultiSelected(TreeViewItem item) - { - return m_Owner.CanMultiSelect(item); - } - - public override bool CanBeParent(TreeViewItem item) - { - return m_Owner.CanBeParent(item); - } - - public override bool IsRenamingItemAllowed(TreeViewItem item) - { - return m_Owner.CanRename(item); - } - } - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDefaults.cs b/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDefaults.cs deleted file mode 100644 index 518c64ea7f..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDefaults.cs +++ /dev/null @@ -1,85 +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; - -namespace UnityEditor.IMGUI.Controls -{ - public partial class TreeView - { - public static class DefaultGUI - { - public static void FoldoutLabel(Rect rect, string label, bool selected, bool focused) - { - if (Event.current.type == EventType.Repaint) - DefaultStyles.foldoutLabel.Draw(rect, GUIContent.Temp(label), false, false, selected, focused); - } - - public static void Label(Rect rect, string label, bool selected, bool focused) - { - if (Event.current.type == EventType.Repaint) - DefaultStyles.label.Draw(rect, GUIContent.Temp(label), false, false, selected, focused); - } - - public static void LabelRightAligned(Rect rect, string label, bool selected, bool focused) - { - if (Event.current.type == EventType.Repaint) - DefaultStyles.labelRightAligned.Draw(rect, GUIContent.Temp(label), false, false, selected, focused); - } - - public static void BoldLabel(Rect rect, string label, bool selected, bool focused) - { - if (Event.current.type == EventType.Repaint) - DefaultStyles.boldLabel.Draw(rect, GUIContent.Temp(label), false, false, selected, focused); - } - - public static void BoldLabelRightAligned(Rect rect, string label, bool selected, bool focused) - { - if (Event.current.type == EventType.Repaint) - DefaultStyles.boldLabelRightAligned.Draw(rect, GUIContent.Temp(label), false, false, selected, focused); - } - - internal static float contentLeftMargin - { - get { return DefaultStyles.foldoutLabel.margin.left; } - } - } - - public static class DefaultStyles - { - public static GUIStyle foldoutLabel; - public static GUIStyle label; - public static GUIStyle labelRightAligned; - - public static GUIStyle boldLabel; - public static GUIStyle boldLabelRightAligned; - - public static GUIStyle backgroundEven = "OL EntryBackEven"; - public static GUIStyle backgroundOdd = "OL EntryBackOdd"; - - static DefaultStyles() - { - // Make a copy of lineStyle since left padding is being dynamically changed on that - // Note the left padding of 0 for exact placement of content after foldout or icon - foldoutLabel = new GUIStyle(TreeViewGUI.Styles.lineStyle); - foldoutLabel.padding.left = 0; - - // For generic labels use same padding values as the standard EditorStyles.label for consistency - label = new GUIStyle(foldoutLabel); - label.padding.left = 2; - label.padding.right = 2; - - labelRightAligned = new GUIStyle(label); - labelRightAligned.alignment = TextAnchor.UpperRight; - - boldLabel = new GUIStyle(label); - boldLabel.font = EditorStyles.boldLabel.font; - boldLabel.fontStyle = EditorStyles.boldLabel.fontStyle; - - boldLabelRightAligned = new GUIStyle(boldLabel); - boldLabelRightAligned.alignment = TextAnchor.UpperRight; - } - } - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDragging.cs b/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDragging.cs deleted file mode 100644 index 63963bc86e..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDragging.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.Collections.Generic; -using UnityEngine; - - -namespace UnityEditor.IMGUI.Controls -{ - public partial class TreeView - { - private class TreeViewControlDragging : TreeViewDragging - { - private TreeView m_Owner; - - public TreeViewControlDragging(TreeViewController treeView, TreeView owner) - : base(treeView) - { - m_Owner = owner; - } - - public override bool CanStartDrag(TreeViewItem targetItem, List draggedItemIDs, Vector2 mouseDownPosition) - { - return m_Owner.CanStartDrag(new CanStartDragArgs { draggedItem = targetItem, draggedItemIDs = draggedItemIDs }); - } - - public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) - { - m_Owner.SetupDragAndDrop(new SetupDragAndDropArgs { draggedItemIDs = draggedItemIDs}); - } - - public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, DropPosition dropPosition) - { - if (m_Owner.m_OverriddenMethods.hasHandleDragAndDrop) - { - var args = new DragAndDropArgs - { - dragAndDropPosition = GetDragAndDropPosition(parentItem, targetItem), - insertAtIndex = GetInsertionIndex(parentItem, targetItem, dropPosition), - parentItem = parentItem, - performDrop = perform - }; - - return m_Owner.HandleDragAndDrop(args); - } - - return DragAndDropVisualMode.None; - } - - DragAndDropPosition GetDragAndDropPosition(TreeViewItem parentItem, TreeViewItem targetItem) - { - if (parentItem == null) - return DragAndDropPosition.OutsideItems; - - if (parentItem == targetItem) - return DragAndDropPosition.UponItem; - - return DragAndDropPosition.BetweenItems; - } - } - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewDataSource.cs b/Editor/Mono/GUI/TreeView/TreeViewDataSource.cs deleted file mode 100644 index ed23094cec..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewDataSource.cs +++ /dev/null @@ -1,359 +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.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace UnityEditor.IMGUI.Controls -{ - // TreeViewDataSource is a base abstract class for a data source for a TreeView. - // Usage: - // Override FetchData () and build the entire tree with m_RootItem as root. - // Configure showRootItem and rootIsCollapsable as wanted - // - // Note: if dealing with very large trees use LazyTreeViewDataSource instead: it assumes that tree only contains visible items. - - internal abstract class TreeViewDataSource : ITreeViewDataSource - { - protected readonly TreeViewController m_TreeView; // TreeView using this data source - protected TreeViewItem m_RootItem; - protected IList m_Rows; - protected bool m_NeedRefreshRows = true; - protected TreeViewItem m_FakeItem; - - public bool showRootItem { get; set; } - public bool rootIsCollapsable { get; set; } - public bool alwaysAddFirstItemToSearchResult { get; set; } // is only used in searches when showRootItem is false. It Doesn't make sense for visible roots - public TreeViewItem root { get { return m_RootItem; } } - public System.Action onVisibleRowsChanged; - - protected List expandedIDs - { - get {return m_TreeView.state.expandedIDs; } - set { m_TreeView.state.expandedIDs = value; } - } - - public TreeViewDataSource(TreeViewController treeView) - { - m_TreeView = treeView; - showRootItem = true; - rootIsCollapsable = false; - m_RootItem = null; - onVisibleRowsChanged = null; - } - - virtual public void OnInitialize() - { - } - - // Implement this function and build entire tree with m_RootItem as root - public abstract void FetchData(); - - public virtual void ReloadData() - { - m_FakeItem = null; - FetchData(); - } - - virtual public TreeViewItem FindItem(int id) - { - return TreeViewUtility.FindItem(id, m_RootItem); - } - - virtual public bool IsRevealed(int id) - { - IList rows = GetRows(); - return TreeViewController.GetIndexOfID(rows, id) >= 0; - } - - virtual public void RevealItem(int id) - { - if (IsRevealed(id)) - return; - - // Reveal (expand parents up to root) - TreeViewItem item = FindItem(id); - if (item != null) - { - TreeViewItem parent = item.parent; - while (parent != null) - { - SetExpanded(parent, true); - parent = parent.parent; - } - } - } - - virtual public void OnSearchChanged() - { - m_NeedRefreshRows = true; - } - - //---------------------------- - // Visible Item section - - protected void GetVisibleItemsRecursive(TreeViewItem item, IList items) - { - if (item != m_RootItem || showRootItem) - items.Add(item); - - if (item.hasChildren && IsExpanded(item)) - foreach (TreeViewItem child in item.children) - GetVisibleItemsRecursive(child, items); - } - - protected void SearchRecursive(TreeViewItem item, string search, IList searchResult) - { - if (item.displayName.ToLower().Contains(search)) - searchResult.Add(item); - - if (item.children != null) - foreach (TreeViewItem child in item.children) - SearchRecursive(child, search, searchResult); - } - - virtual protected List ExpandedRows(TreeViewItem root) - { - var result = new List(); - GetVisibleItemsRecursive(m_RootItem, result); - return result; - } - - // Searches the current tree by displayName. - virtual protected List Search(TreeViewItem root, string search) - { - var result = new List(); - - if (showRootItem) - { - SearchRecursive(root, search, result); - result.Sort(new TreeViewItemAlphaNumericSort()); - } - else - { - int startIndex = alwaysAddFirstItemToSearchResult ? 1 : 0; - - if (root.hasChildren) - { - for (int i = startIndex; i < root.children.Count; ++i) - { - SearchRecursive(root.children[i], search, result); - } - result.Sort(new TreeViewItemAlphaNumericSort()); - - if (alwaysAddFirstItemToSearchResult) - result.Insert(0, root.children[0]); - } - } - - return result; - } - - virtual public int rowCount - { - get - { - return GetRows().Count; - } - } - - virtual public int GetRow(int id) - { - var rows = GetRows(); - for (int row = 0; row < rows.Count; ++row) - { - if (rows[row].id == id) - return row; - } - return -1; - } - - virtual public TreeViewItem GetItem(int row) - { - return GetRows()[row]; - } - - // Get the flattend tree of visible items. - virtual public IList GetRows() - { - InitIfNeeded(); - return m_Rows; - } - - virtual public void InitIfNeeded() - { - // Cached for large trees... - if (m_Rows == null || m_NeedRefreshRows) - { - if (m_RootItem != null) - { - if (m_TreeView.isSearching) - m_Rows = Search(m_RootItem, m_TreeView.searchString.ToLower()); - else - m_Rows = ExpandedRows(m_RootItem); - } - else - { - Debug.LogError("TreeView root item is null. Ensure that your TreeViewDataSource sets up at least a root item."); - m_Rows = new List(); - } - - m_NeedRefreshRows = false; - - // TODO: This should be named something like: 'onVisibleRowsReloaded' - if (onVisibleRowsChanged != null) - onVisibleRowsChanged(); - - // Expanded state has changed ensure that we repaint - m_TreeView.Repaint(); - } - } - - public bool isInitialized - { - get { return m_RootItem != null && m_Rows != null; } - } - - //---------------------------- - // Expanded/collapsed section - - virtual public int[] GetExpandedIDs() - { - return expandedIDs.ToArray(); - } - - virtual public void SetExpandedIDs(int[] ids) - { - expandedIDs = new List(ids); - expandedIDs.Sort(); - m_NeedRefreshRows = true; - OnExpandedStateChanged(); - } - - virtual public bool IsExpanded(int id) - { - return expandedIDs.BinarySearch(id) >= 0; - } - - virtual public bool SetExpanded(int id, bool expand) - { - bool expanded = IsExpanded(id); - if (expand != expanded) - { - if (expand) - { - System.Diagnostics.Debug.Assert(!expandedIDs.Contains(id)); - expandedIDs.Add(id); - expandedIDs.Sort(); - } - else - { - expandedIDs.Remove(id); - } - m_NeedRefreshRows = true; - OnExpandedStateChanged(); - return true; - } - return false; - } - - virtual public void SetExpandedWithChildren(int id, bool expand) - { - SetExpandedWithChildren(FindItem(id), expand); - } - - virtual public void SetExpandedWithChildren(TreeViewItem fromItem, bool expand) - { - if (fromItem == null) - { - Debug.LogError("item is null"); - return; - } - - HashSet parents = TreeViewUtility.GetParentsBelowItem(fromItem); - - // Get existing expanded in hashset - HashSet oldExpandedSet = new HashSet(expandedIDs); - - if (expand) - oldExpandedSet.UnionWith(parents); - else - oldExpandedSet.ExceptWith(parents); - - // Bulk set expanded ids (is sorted in SetExpandedIDs) - SetExpandedIDs(oldExpandedSet.ToArray()); - } - - virtual public void SetExpanded(TreeViewItem item, bool expand) - { - SetExpanded(item.id, expand); - } - - virtual public bool IsExpanded(TreeViewItem item) - { - return IsExpanded(item.id); - } - - virtual public bool IsExpandable(TreeViewItem item) - { - // Ignore expansion (foldout arrow) when showing search results - if (m_TreeView.isSearching) - return false; - return item.hasChildren; - } - - virtual public bool CanBeMultiSelected(TreeViewItem item) - { - return true; - } - - virtual public bool CanBeParent(TreeViewItem item) - { - return true; - } - - virtual public void OnExpandedStateChanged() - { - if (m_TreeView.expandedStateChanged != null) - m_TreeView.expandedStateChanged(); - } - - //---------------------------- - // Renaming section - - virtual public bool IsRenamingItemAllowed(TreeViewItem item) - { - return true; - } - - //---------------------------- - // Insert tempoary Item section - - // Fake Item should be inserted into the m_VisibleRows (not the tree itself). - virtual public void InsertFakeItem(int id, int parentID, string name, Texture2D icon) - { - Debug.LogError("InsertFakeItem missing implementation"); - } - - virtual public bool HasFakeItem() - { - return m_FakeItem != null; - } - - virtual public void RemoveFakeItem() - { - if (!HasFakeItem()) - return; - - var visibleRows = GetRows(); - int index = TreeViewController.GetIndexOfID(visibleRows, m_FakeItem.id); - if (index != -1) - { - visibleRows.RemoveAt(index); - } - m_FakeItem = null; - } - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewExpandAnimator.cs b/Editor/Mono/GUI/TreeView/TreeViewExpandAnimator.cs deleted file mode 100644 index 1e09233d63..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewExpandAnimator.cs +++ /dev/null @@ -1,320 +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.IMGUI.Controls -{ - // Setup animation, tracks animation, fires callback when done (fully expanded/collapsed) - // - - internal class TreeViewItemExpansionAnimator - { - TreeViewAnimationInput m_Setup; // when null we are not animating - bool m_InsideGUIClip; - Rect m_CurrentClipRect; - static bool s_Debug = false; - - public void BeginAnimating(TreeViewAnimationInput setup) - { - if (m_Setup != null) - { - if (m_Setup.item.id == setup.item.id && m_Setup.expanding != setup.expanding) - { - // If same item (changed expand/collapse while animating) then just change direction, but skip the time that already passed - if (m_Setup.elapsedTime >= 0) - { - setup.elapsedTime = m_Setup.animationDuration - m_Setup.elapsedTime; - } - else - Debug.LogError("Invalid duration " + m_Setup.elapsedTime); - - m_Setup = setup; - } - else - { - // Ensure current animation ends before starting a new (just finish it immediately) - SkipAnimating(); - m_Setup = setup; - } - - m_Setup.expanding = setup.expanding; - } - - m_Setup = setup; - if (m_Setup == null) - Debug.LogError("Setup is null"); - - if (printDebug) - Console.WriteLine("Begin animating: " + m_Setup); - - m_CurrentClipRect = GetCurrentClippingRect(); - } - - public void SkipAnimating() - { - if (m_Setup != null) - { - m_Setup.FireAnimationEndedEvent(); - m_Setup = null; - } - } - - // Returns true if row should be culled - public bool CullRow(int row, ITreeViewGUI gui) - { - if (!isAnimating) - { - return false; - } - - if (printDebug && row == 0) - Console.WriteLine("--------"); - - // Check rows that are inside animation clip rect if they can be culled - if (row > m_Setup.startRow && row <= m_Setup.endRow) - { - Rect rowRect = gui.GetRowRect(row, 1); // we do not care about the width - - // Check row Y local to clipRect - float rowY = rowRect.y - m_Setup.startRowRect.y; - - if (rowY > m_CurrentClipRect.height) - { - // Ensure to end animation clip since items after - // culling should be rendered normally - if (m_InsideGUIClip) - { - EndClip(); - } - - return true; - } - } - - // Row is not culled - return false; - } - - public void OnRowGUI(int row) - { - if (printDebug) - Console.WriteLine(row + " Do item " + DebugItemName(row)); - } - - // Call before of TreeViewGUI's OnRowGUI (Needs to be called for all items (changes rects for rows comming after the animating rows) - public Rect OnBeginRowGUI(int row, Rect rowRect) - { - if (!isAnimating) - return rowRect; - - if (row == m_Setup.startRow) - { - BeginClip(); - } - - // Make row rect local to guiclip if animating - if (row >= m_Setup.startRow && row <= m_Setup.endRow) - { - rowRect.y -= m_Setup.startRowRect.y; - } - // rows following the animation snap to cliprect bottom - else if (row > m_Setup.endRow) - { - rowRect.y -= m_Setup.rowsRect.height - m_CurrentClipRect.height; - } - - return rowRect; - } - - // Call at the after TreeViewGUI's OnRowGUI - public void OnEndRowGUI(int row) - { - if (!isAnimating) - return; - - if (m_InsideGUIClip && row == m_Setup.endRow) - { - EndClip(); - } - } - - // Call before all items are being handling - - - private void BeginClip() - { - GUI.BeginClip(m_CurrentClipRect); - m_InsideGUIClip = true; - if (printDebug) - Console.WriteLine("BeginClip startRow: " + m_Setup.startRow); - } - - private void EndClip() - { - GUI.EndClip(); - m_InsideGUIClip = false; - if (printDebug) - Console.WriteLine("EndClip endRow: " + m_Setup.endRow); - } - - public void OnBeforeAllRowsGUI() - { - if (!isAnimating) - return; - - // Cache to ensure consistent across all rows (it is dependant on time) - m_CurrentClipRect = GetCurrentClippingRect(); - - // Stop animation when duration has passed - if (m_Setup.elapsedTime > m_Setup.animationDuration) - { - m_Setup.FireAnimationEndedEvent(); - m_Setup = null; - - if (printDebug) - Debug.Log("Animation ended"); - } - } - - public void OnAfterAllRowsGUI() - { - // Ensure to end clip if not done in CullRow (while iterating rows) - if (m_InsideGUIClip) - { - EndClip(); - } - - if (isAnimating) - HandleUtility.Repaint(); - - // Capture time at intervals to ensure that expansion value is consistent across layout and repaint. - // This fixes that the scroll view showed its scrollbars during expansion since using realtime - // would give higher values on repaint than on layout event. - if (isAnimating && Event.current.type == EventType.Repaint) - m_Setup.CaptureTime(); - } - - public bool IsAnimating(int itemID) - { - if (!isAnimating) - return false; - - return m_Setup.item.id == itemID; - } - - // 1 fully expanded, 0 fully collapsed - public float expandedValueNormalized - { - get - { - float frac = m_Setup.elapsedTimeNormalized; - return m_Setup.expanding ? frac : (1.0f - frac); - } - } - - public int startRow - { - get { return m_Setup.startRow; } - } - - public int endRow - { - get { return m_Setup.endRow; } - } - - public float deltaHeight - { - get { return Mathf.Floor(m_Setup.rowsRect.height - m_Setup.rowsRect.height * expandedValueNormalized); } - } - - public bool isAnimating - { - get { return m_Setup != null; } - } - - public bool isExpanding - { - get { return m_Setup.expanding; } - } - - Rect GetCurrentClippingRect() - { - Rect rect = m_Setup.rowsRect; - rect.height *= expandedValueNormalized; - return rect; - } - - bool printDebug - { - get { return s_Debug && (m_Setup != null) && (m_Setup.treeView != null) && (Event.current.type == EventType.Repaint); } - } - - string DebugItemName(int row) - { - return m_Setup.treeView.data.GetRows()[row].displayName; - } - } - - internal class TreeViewAnimationInput - { - public TreeViewAnimationInput() - { - startTime = timeCaptured = EditorApplication.timeSinceStartup; - } - - public void CaptureTime() - { - timeCaptured = EditorApplication.timeSinceStartup; - } - - public float elapsedTimeNormalized - { - get - { - return Mathf.Clamp01((float)elapsedTime / (float)animationDuration); - } - } - - public double elapsedTime - { - get - { - return timeCaptured - startTime; - } - - set - { - startTime = timeCaptured - value; - } - } - - public int startRow { get; set; } - public int endRow { get; set; } - public Rect rowsRect {get; set; } // the rect encapsulating startrow and endrow - - public Rect startRowRect {get; set; } - public double startTime { get; set; } - public double timeCaptured { get; set; } - public double animationDuration { get; set; } - public bool expanding { get; set; } - public bool includeChildren { get; set; } - public TreeViewItem item { get; set; } - public TreeViewController treeView { get; set; } - - public System.Action animationEnded; // set to get a callback when animation ends - - public void FireAnimationEndedEvent() - { - if (animationEnded != null) - animationEnded(this); - } - - public override string ToString() - { - return "Input: startRow " + startRow + " endRow " + endRow + " rowsRect " + rowsRect + " startTime " + startTime + " anitmationDuration" + animationDuration + " " + expanding + " " + item.displayName; - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewGUIWithCustomItemHeights.cs b/Editor/Mono/GUI/TreeView/TreeViewGUIWithCustomItemHeights.cs deleted file mode 100644 index f4f50e3e0b..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewGUIWithCustomItemHeights.cs +++ /dev/null @@ -1,196 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - - -namespace UnityEditor -{ - // Total size: 1) When changing: non changing rows + changing rows fraction, 2) When not changing sum of rows - // Size of changing rows fraction used for finding new endRow after last changing row - - internal abstract class TreeViewGUIWithCustomItemsHeights : ITreeViewGUI - { - private List m_RowRects = new List(); - private float m_MaxWidthOfRows; - protected readonly TreeViewController m_TreeView; - - public TreeViewGUIWithCustomItemsHeights(TreeViewController treeView) - { - m_TreeView = treeView; - } - - public virtual void OnInitialize() - { - } - - public Rect GetRowRect(int row, float rowWidth) - { - if (m_RowRects.Count == 0) - { - Debug.LogError("Ensure precalc rects"); - return new Rect(); - } - - return m_RowRects[row]; - } - - public Rect GetRenameRect(Rect rowRect, int row, TreeViewItem item) - { - return new Rect(); - } - - public Rect GetRectForFraming(int row) - { - return GetRowRect(row, 1); - } - - public abstract void OnRowGUI(Rect rowRect, TreeViewItem item, int row, bool selected, bool focused); - - protected virtual float AddSpaceBefore(TreeViewItem item) - { - return 0; - } - - protected virtual Vector2 GetSizeOfRow(TreeViewItem item) - { - return new Vector2(m_TreeView.GetTotalRect().width, 16); - } - - public void CalculateRowRects() - { - if (m_TreeView.isSearching) - return; - const float startY = 2f; - var rows = m_TreeView.data.GetRows(); - m_RowRects = new List(rows.Count); - float curY = startY; - m_MaxWidthOfRows = 1f; - for (int i = 0; i < rows.Count; ++i) - { - TreeViewItem item = rows[i]; - float space = AddSpaceBefore(item); - curY += space; - Vector2 rowSize = GetSizeOfRow(item); - m_RowRects.Add(new Rect(0, curY, rowSize.x, rowSize.y)); - curY += rowSize.y; - if (rowSize.x > m_MaxWidthOfRows) - m_MaxWidthOfRows = rowSize.x; - } - } - - // Calc correct width if horizontal scrollbar is wanted return new Vector2(1, height) - public Vector2 GetTotalSize() - { - if (m_RowRects.Count == 0) - return new Vector2(0, 0); - - return new Vector2(m_MaxWidthOfRows, m_RowRects[m_RowRects.Count - 1].yMax); - } - - public int GetNumRowsOnPageUpDown(TreeViewItem fromItem, bool pageUp, float heightOfTreeView) - { - Debug.LogError("GetNumRowsOnPageUpDown: Not impemented"); - return (int)Mathf.Floor(heightOfTreeView / 30); // return something - } - - // Should return the row number of the first and last row thats fits in the pixel rect defined by top and height - public void GetFirstAndLastRowVisible(out int firstRowVisible, out int lastRowVisible) - { - float topPixel = m_TreeView.state.scrollPos.y; - float heightInPixels = m_TreeView.GetTotalRect().height; - - var rowCount = m_TreeView.data.rowCount; - if (rowCount != m_RowRects.Count) - { - Debug.LogError("Mismatch in state: rows vs cached rects. Did you remember to hook up: dataSource.onVisibleRowsChanged += gui.CalculateRowRects ?"); - CalculateRowRects(); - } - - int firstVisible = -1; - int lastVisible = -1; - - for (int i = 0; i < m_RowRects.Count; ++i) - { - bool visible = ((m_RowRects[i].y > topPixel && (m_RowRects[i].y < topPixel + heightInPixels))) || - ((m_RowRects[i].yMax > topPixel && (m_RowRects[i].yMax < topPixel + heightInPixels))); - - if (visible) - { - if (firstVisible == -1) - firstVisible = i; - lastVisible = i; - } - } - - if (firstVisible != -1 && lastVisible != -1) - { - firstRowVisible = firstVisible; - lastRowVisible = lastVisible; - } - else - { - firstRowVisible = 0; - lastRowVisible = rowCount - 1; - } - } - - public virtual void BeginRowGUI() - { - } - - public virtual void EndRowGUI() - { - } - - public virtual void BeginPingItem(TreeViewItem item, float topPixelOfRow, float availableWidth) - { - throw new NotImplementedException(); - } - - public virtual void EndPingItem() - { - throw new NotImplementedException(); - } - - public virtual bool BeginRename(TreeViewItem item, float delay) - { - throw new NotImplementedException(); - } - - public virtual void EndRename() - { - throw new NotImplementedException(); - } - - public virtual float halfDropBetweenHeight - { - get { return 8f; } - } - public virtual float topRowMargin { get; private set; } - public virtual float bottomRowMargin { get; private set; } - - protected float m_BaseIndent = 2f; - protected float m_IndentWidth = 14f; - protected float m_FoldoutWidth = 12f; - protected float indentWidth { get { return m_IndentWidth; } } - - virtual public float GetFoldoutIndent(TreeViewItem item) - { - // Ignore depth when showing search results - if (m_TreeView.isSearching) - return m_BaseIndent; - - return m_BaseIndent + item.depth * indentWidth; - } - - virtual public float GetContentIndent(TreeViewItem item) - { - return GetFoldoutIndent(item) + m_FoldoutWidth; - } - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewItem.cs b/Editor/Mono/GUI/TreeView/TreeViewItem.cs deleted file mode 100644 index 44edd51115..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewItem.cs +++ /dev/null @@ -1,88 +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.Collections.Generic; -using UnityEngine; - -namespace UnityEditor.IMGUI.Controls -{ - public class TreeViewItem : System.IComparable - { - int m_ID; // The id should be unique for all items in TreeView because it is used for searching, selection etc. - TreeViewItem m_Parent; - List m_Children = null; - int m_Depth; - string m_DisplayName; - Texture2D m_Icon; - - public TreeViewItem() {} - - public TreeViewItem(int id) - { - m_ID = id; - } - - public TreeViewItem(int id, int depth) - { - m_ID = id; - m_Depth = depth; - } - - public TreeViewItem(int id, int depth, string displayName) - { - m_Depth = depth; - m_ID = id; - m_DisplayName = displayName; - } - - internal TreeViewItem(int id, int depth, TreeViewItem parent, string displayName) - { - m_Depth = depth; - m_Parent = parent; - m_ID = id; - m_DisplayName = displayName; - } - - public virtual int id { get { return m_ID; } set { m_ID = value; }} - public virtual string displayName { get { return m_DisplayName; } set { m_DisplayName = value; } } - public virtual int depth { get { return m_Depth; } set { m_Depth = value; } } - public virtual bool hasChildren { get { return m_Children != null && m_Children.Count > 0; } } - public virtual List children { get { return m_Children; } set { m_Children = value; } } - public virtual TreeViewItem parent { get { return m_Parent; } set { m_Parent = value; } } - public virtual Texture2D icon { get { return m_Icon; } set { m_Icon = value; } } - - public void AddChild(TreeViewItem child) - { - if (m_Children == null) - m_Children = new List(); - - m_Children.Add(child); - - if (child != null) - child.parent = this; - } - - public virtual int CompareTo(TreeViewItem other) - { - return displayName.CompareTo(other.displayName); - } - - public override string ToString() - { - return string.Format("Item: '{0}' ({1}), has {2} children, depth {3}, parent id {4}", displayName, id, hasChildren ? children.Count : 0, depth, (parent != null) ? parent.id : -1); - } - } - - class TreeViewItemAlphaNumericSort : IComparer - { - public int Compare(TreeViewItem lhs, TreeViewItem rhs) - { - if (lhs == rhs) return 0; - if (lhs == null) return -1; - if (rhs == null) return 1; - - return EditorUtility.NaturalCompare(lhs.displayName, rhs.displayName); - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTest.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTest.cs deleted file mode 100644 index e1cf5d1224..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTest.cs +++ /dev/null @@ -1,143 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; -using UnityEngine.Profiling; - - -namespace UnityEditor.TreeViewExamples -{ - internal class TreeViewStateWithColumns : TreeViewState - { - [SerializeField] - public float[] columnWidths; - } - - internal class TreeViewTest - { - private BackendData m_BackendData; - private TreeViewController m_TreeView; - private EditorWindow m_EditorWindow; - private bool m_Lazy; - private TreeViewColumnHeader m_ColumnHeader; - private GUIStyle m_HeaderStyle; - private GUIStyle m_HeaderStyleRightAligned; - - public int GetNumItemsInData() - { - return m_BackendData.IDCounter; - } - - public int GetNumItemsInTree() - { - var data = m_TreeView.data as LazyTestDataSource; - if (data != null) - return data.itemCounter; - - var data2 = m_TreeView.data as TestDataSource; - if (data2 != null) - return data2.itemCounter; - - return -1; - } - - public TreeViewTest(EditorWindow editorWindow, bool lazy) - { - m_EditorWindow = editorWindow; - m_Lazy = lazy; - } - - public void Init(Rect rect, BackendData backendData) - { - if (m_TreeView != null) - return; - - m_BackendData = backendData; - - var state = new TreeViewStateWithColumns(); - state.columnWidths = new float[] {250f, 90f, 93f, 98f, 74f, 78f}; - - m_TreeView = new TreeViewController(m_EditorWindow, state); - ITreeViewGUI gui = new TestGUI(m_TreeView); - ITreeViewDragging dragging = new TestDragging(m_TreeView, m_BackendData); - ITreeViewDataSource dataSource; - if (m_Lazy) dataSource = new LazyTestDataSource(m_TreeView, m_BackendData); - else dataSource = new TestDataSource(m_TreeView, m_BackendData); - m_TreeView.Init(rect, dataSource, gui, dragging); - - - m_ColumnHeader = new TreeViewColumnHeader(); - m_ColumnHeader.columnWidths = state.columnWidths; - m_ColumnHeader.minColumnWidth = 30f; - m_ColumnHeader.columnRenderer += OnColumnRenderer; - } - - void OnColumnRenderer(int column, Rect rect) - { - if (m_HeaderStyle == null) - { - m_HeaderStyle = new GUIStyle(EditorStyles.toolbarButton); - m_HeaderStyle.padding.left = 4; - m_HeaderStyle.alignment = TextAnchor.MiddleLeft; - - m_HeaderStyleRightAligned = new GUIStyle(EditorStyles.toolbarButton); - m_HeaderStyleRightAligned.padding.right = 4; - m_HeaderStyleRightAligned.alignment = TextAnchor.MiddleRight; - } - - string[] headers = new[] { "Name", "Date Modified", "Size", "Kind", "Author", "Platform", "Faster", "Slower" }; - GUI.Label(rect, headers[column], (column % 2 == 0) ? m_HeaderStyle : m_HeaderStyleRightAligned); - } - - public void OnGUI(Rect rect) - { - int keyboardControl = GUIUtility.GetControlID(FocusType.Keyboard, rect); - - const float kHeaderHeight = 17f; - const float kBottomHeight = 20f; - Rect headerRect = new Rect(rect.x, rect.y, rect.width, kHeaderHeight); - Rect bottomRect = new Rect(rect.x, rect.yMax - kBottomHeight, rect.width, kBottomHeight); - - // Header - GUI.Label(headerRect, "", EditorStyles.toolbar); - m_ColumnHeader.OnGUI(headerRect); - - Profiler.BeginSample("TREEVIEW"); - - // TreeView - rect.y += headerRect.height; - rect.height -= headerRect.height + bottomRect.height; - m_TreeView.OnEvent(); - m_TreeView.OnGUI(rect, keyboardControl); - - Profiler.EndSample(); - - // BottomBar - GUILayout.BeginArea(bottomRect, GetHeader(), EditorStyles.helpBox); - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - m_BackendData.m_RecursiveFindParentsBelow = GUILayout.Toggle(m_BackendData.m_RecursiveFindParentsBelow, GUIContent.Temp("Recursive")); - if (GUILayout.Button("Ping", EditorStyles.miniButton)) - { - int id = GetNumItemsInData() / 2; - m_TreeView.Frame(id, true, true); - m_TreeView.SetSelection(new[] {id}, false); - } - if (GUILayout.Button("Frame", EditorStyles.miniButton)) - { - int id = GetNumItemsInData() / 10; - m_TreeView.Frame(id, true, false); - m_TreeView.SetSelection(new[] { id }, false); - } - GUILayout.EndHorizontal(); - GUILayout.EndArea(); - } - - private string GetHeader() - { - return (m_Lazy ? "LAZY: " : "FULL: ") + "GUI items: " + GetNumItemsInTree() + " (data items: " + GetNumItemsInData() + ")"; - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestBackEnd.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestBackEnd.cs deleted file mode 100644 index 9049664ee2..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestBackEnd.cs +++ /dev/null @@ -1,243 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - - -namespace UnityEditor.TreeViewExamples -{ - internal class BackendData - { - public class Foo - { - public Foo(string name, int depth, int id) - { - this.name = name; - this.depth = depth; this.id = id; - } - - public string name { get; set; } - public int id { get; set; } - public int depth { get; set; } - public Foo parent { get; set; } - public List children { get; set; } - public bool hasChildren { get { return children != null && children.Count > 0; } } - } - - public Foo root { get { return m_Root; } } - - private Foo m_Root; - public bool m_RecursiveFindParentsBelow = true; - public int IDCounter { get; private set; } - private int m_MaxItems = 10000; - private const int k_MinChildren = 3; - private const int k_MaxChildren = 15; - private const float k_ProbOfLastDescendent = 0.5f; - private const int k_MaxDepth = 12; - - public void GenerateData(int maxNumItems) - { - m_MaxItems = maxNumItems; - IDCounter = 1; - m_Root = new Foo("Root", 0, 0); - for (int i = 0; i < 10; ++i) - AddChildrenRecursive(m_Root, UnityEngine.Random.Range(k_MinChildren, k_MaxChildren), true); - } - - public Foo Find(int id) - { - return FindRecursive(id, m_Root); - } - - public Foo FindRecursive(int id, Foo parent) - { - if (!parent.hasChildren) - return null; - - foreach (var child in parent.children) - { - if (child.id == id) - return child; - - var result = FindRecursive(id, child); - if (result != null) - return result; - } - - return null; - } - - public HashSet GetParentsBelow(int id) - { - Foo searchFromThis = FindItemRecursive(root, id); - if (searchFromThis != null) - { - if (m_RecursiveFindParentsBelow) - return GetParentsBelowRecursive(searchFromThis); - - return GetParentsBelowStackBased(searchFromThis); - } - return new HashSet(); - } - - private HashSet GetParentsBelowStackBased(Foo searchFromThis) - { - Stack stack = new Stack(); - stack.Push(searchFromThis); - - HashSet parentsBelow = new HashSet(); - while (stack.Count > 0) - { - Foo current = stack.Pop(); - if (current.hasChildren) - { - parentsBelow.Add(current.id); - foreach (var foo in current.children) - { - stack.Push(foo); - } - } - } - - return parentsBelow; - } - - private HashSet GetParentsBelowRecursive(Foo searchFromThis) - { - HashSet result = new HashSet(); - GetParentsBelowRecursive(searchFromThis, result); - return result; - } - - private static void GetParentsBelowRecursive(Foo item, HashSet parentIDs) - { - if (!item.hasChildren) - return; - parentIDs.Add(item.id); - foreach (var child in item.children) - GetParentsBelowRecursive(child, parentIDs); - } - - public void ReparentSelection(Foo parentItem, int insertionIndex, List draggedItems) - { - // Invalid reparenting input - if (parentItem == null) - return; - - // We are moving items so we adjust the insertion index to accomodate that any items above the insertion index is removed before inserting - if (insertionIndex > 0) - insertionIndex -= parentItem.children.GetRange(0, insertionIndex).Count(draggedItems.Contains); - - // Remove draggedItems from their parents - foreach (var draggedItem in draggedItems) - { - draggedItem.parent.children.Remove(draggedItem); // remove from old parent - draggedItem.parent = parentItem; // set new parent - } - - if (!parentItem.hasChildren) - parentItem.children = new List(); - var newChildren = new List(parentItem.children); - - // If insertionIndex is -1 then item was dropped upon the parent: client have to decide where to place the dragged items. We add as the first. - if (insertionIndex == -1) - insertionIndex = 0; - - // Insert dragged items under new parent - newChildren.InsertRange(insertionIndex, draggedItems); - parentItem.children = newChildren; - } - - void AddChildrenRecursive(Foo foo, int numChildren, bool force) - { - if (IDCounter > m_MaxItems) - return; - - if (foo.depth >= k_MaxDepth) - return; - - if (!force && UnityEngine.Random.value < k_ProbOfLastDescendent) - return; - - if (foo.children == null) - foo.children = new List(numChildren); - for (int i = 0; i < numChildren; ++i) - { - Foo child = new Foo("Tud" + IDCounter, foo.depth + 1, ++IDCounter); - child.parent = foo; - foo.children.Add(child); - } - - if (IDCounter > m_MaxItems) - return; - - foreach (var child in foo.children) - { - AddChildrenRecursive(child, UnityEngine.Random.Range(k_MinChildren, k_MaxChildren), false); - } - } - - public static Foo FindItemRecursive(Foo item, int id) - { - if (item == null) - return null; - - if (item.id == id) - return item; - - if (item.children == null) - return null; - - foreach (Foo child in item.children) - { - Foo result = FindItemRecursive(child, id); - if (result != null) - return result; - } - return null; - } - } - - internal class TreeViewColumnHeader - { - public float[] columnWidths { get; set; } - public float minColumnWidth { get; set; } - public float dragWidth { get; set; } - public Action columnRenderer { get; set; } - - public TreeViewColumnHeader() - { - minColumnWidth = 10; - dragWidth = 6f; - } - - public void OnGUI(Rect rect) - { - const float dragAreaWidth = 3f; - float columnPos = rect.x; - for (int i = 0; i < columnWidths.Length; ++i) - { - Rect columnRect = new Rect(columnPos, rect.y, columnWidths[i], rect.height); - columnPos += columnWidths[i]; - Rect dragRect = new Rect(columnPos - dragWidth / 2, rect.y, dragAreaWidth, rect.height); - float deltaX = EditorGUI.MouseDeltaReader(dragRect, true).x; - if (deltaX != 0f) - { - columnWidths[i] += deltaX; - columnWidths[i] = Mathf.Max(columnWidths[i], minColumnWidth); - } - - if (columnRenderer != null) - columnRenderer(i, columnRect); - - if (Event.current.type == EventType.Repaint) - EditorGUIUtility.AddCursorRect(dragRect, MouseCursor.SplitResizeLeftRight); - } - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestDataSource.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestDataSource.cs deleted file mode 100644 index 6fccb91416..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestDataSource.cs +++ /dev/null @@ -1,50 +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.Collections.Generic; -using UnityEditor.IMGUI.Controls; - - -namespace UnityEditor.TreeViewExamples -{ - class TestDataSource : TreeViewDataSource - { - private BackendData m_Backend; - public int itemCounter { get; private set; } - - public TestDataSource(TreeViewController treeView, BackendData data) : base(treeView) - { - m_Backend = data; - FetchData(); - } - - public override void FetchData() - { - itemCounter = 1; - m_RootItem = new FooTreeViewItem(m_Backend.root.id, 0, null, m_Backend.root.name, m_Backend.root); - AddChildrenRecursive(m_Backend.root, m_RootItem); - m_NeedRefreshRows = true; - } - - void AddChildrenRecursive(BackendData.Foo source, TreeViewItem dest) - { - if (source.hasChildren) - { - dest.children = new List(source.children.Count); - for (int i = 0; i < source.children.Count; ++i) - { - BackendData.Foo s = source.children[i]; - dest.children.Add(new FooTreeViewItem(s.id, dest.depth + 1, dest, s.name, s)); - itemCounter++; - AddChildrenRecursive(s, dest.children[i]); - } - } - } - - public override bool CanBeParent(TreeViewItem item) - { - return true; - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestDragging.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestDragging.cs deleted file mode 100644 index e48657c331..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestDragging.cs +++ /dev/null @@ -1,82 +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.Collections.Generic; -using System.Linq; -using UnityEditor.IMGUI.Controls; - - -namespace UnityEditor.TreeViewExamples -{ - internal class TestDragging : TreeViewDragging - { - private const string k_GenericDragID = "FooDragging"; - private BackendData m_BackendData; - - - class FooDragData - { - public FooDragData(List draggedItems) - { - m_DraggedItems = draggedItems; - } - - public List m_DraggedItems; - } - - public TestDragging(TreeViewController treeView, BackendData data) - : base(treeView) - { - m_BackendData = data; - } - - public override void StartDrag(TreeViewItem draggedItem, List draggedItemIDs) - { - DragAndDrop.PrepareStartDrag(); - DragAndDrop.SetGenericData(k_GenericDragID, new FooDragData(GetItemsFromIDs(draggedItemIDs))); - string title = draggedItemIDs.Count + " Foo" + (draggedItemIDs.Count > 1 ? "s" : ""); // title is only shown on OSX (at the cursor) - DragAndDrop.StartDrag(title); - } - - public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, DropPosition dropPos) - { - var dragData = DragAndDrop.GetGenericData(k_GenericDragID) as FooDragData; - var fooParent = parentItem as FooTreeViewItem; - if (fooParent != null && dragData != null) - { - bool validDrag = ValidDrag(parentItem, dragData.m_DraggedItems); - if (perform && validDrag) - { - // Do reparenting here - List draggedFoos = (from x in dragData.m_DraggedItems where x is FooTreeViewItem select((FooTreeViewItem)x).foo).ToList(); - var selectedIDs = (from x in dragData.m_DraggedItems where x is FooTreeViewItem select((FooTreeViewItem)x).id).ToArray(); - int insertionIndex = GetInsertionIndex(parentItem, targetItem, dropPos); - m_BackendData.ReparentSelection(fooParent.foo, insertionIndex, draggedFoos); - m_TreeView.ReloadData(); - m_TreeView.SetSelection(selectedIDs, true); - } - return validDrag ? DragAndDropVisualMode.Move : DragAndDropVisualMode.None; - } - return DragAndDropVisualMode.None; - } - - bool ValidDrag(TreeViewItem parent, List draggedItems) - { - TreeViewItem currentParent = parent; - while (currentParent != null) - { - if (draggedItems.Contains(currentParent)) - return false; - currentParent = currentParent.parent; - } - return true; - } - - private List GetItemsFromIDs(IEnumerable draggedItemIDs) - { - // Note we only drag visible items here... - return TreeViewUtility.FindItemsInList(draggedItemIDs, m_TreeView.data.GetRows()); - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestGUICustom.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestGUICustom.cs deleted file mode 100644 index 6150d5e55a..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestGUICustom.cs +++ /dev/null @@ -1,130 +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.ComponentModel; -using UnityEditor.IMGUI.Controls; -using UnityEngine; - - -namespace UnityEditor.TreeViewExamples -{ - class TestGUICustomItemHeights : TreeViewGUIWithCustomItemsHeights - { - internal class Styles - { - public static GUIStyle foldout = "IN Foldout"; - } - - private float m_Column1Width = 300; - protected Rect m_DraggingInsertionMarkerRect; - - public TestGUICustomItemHeights(TreeViewController treeView) - : base(treeView) - { - m_FoldoutWidth = Styles.foldout.fixedWidth; - } - - protected override Vector2 GetSizeOfRow(TreeViewItem item) - { - return new Vector2(m_TreeView.GetTotalRect().width, item.hasChildren ? 20 : 36f); - } - - public override void BeginRowGUI() - { - // Reset - m_DraggingInsertionMarkerRect.x = -1; - } - - public override void EndRowGUI() - { - base.EndRowGUI(); - - // Draw row marker when dragging - if (m_DraggingInsertionMarkerRect.x >= 0 && Event.current.type == EventType.Repaint) - { - Rect insertionRect = m_DraggingInsertionMarkerRect; - insertionRect.height = 2f; - insertionRect.y -= insertionRect.height / 2; - if (!m_TreeView.dragging.drawRowMarkerAbove) - insertionRect.y += m_DraggingInsertionMarkerRect.height; - - EditorGUI.DrawRect(insertionRect, Color.white); - } - } - - public override void OnRowGUI(Rect rowRect, TreeViewItem item, int row, bool selected, bool focused) - { - rowRect.height -= 1f; - Rect column1Rect = rowRect; - Rect column2Rect = rowRect; - column1Rect.width = m_Column1Width; - column1Rect.xMin += GetFoldoutIndent(item); - column2Rect.xMin += m_Column1Width + 1; - - float indent = GetFoldoutIndent(item); - Rect tmpRect = rowRect; - - int itemControlID = TreeViewController.GetItemControlID(item); - - bool isDropTarget = false; - if (m_TreeView.dragging != null) - isDropTarget = m_TreeView.dragging.GetDropTargetControlID() == itemControlID && m_TreeView.data.CanBeParent(item); - bool showFoldout = m_TreeView.data.IsExpandable(item); - - - Color selectedColor = new Color(0.0f, 0.22f, 0.44f); - Color normalColor = new Color(0.1f, 0.1f, 0.1f); - - EditorGUI.DrawRect(column1Rect, selected ? selectedColor : normalColor); - EditorGUI.DrawRect(column2Rect, selected ? selectedColor : normalColor); - - if (isDropTarget) - { - EditorGUI.DrawRect(new Rect(rowRect.x, rowRect.y, 3, rowRect.height), Color.yellow); - } - - if (Event.current.type == EventType.Repaint) - { - Rect labelRect = column1Rect; - labelRect.xMin += m_FoldoutWidth; - - GUI.Label(labelRect, item.displayName, EditorStyles.largeLabel); - if (rowRect.height > 20f) - { - labelRect.y += 16f; - GUI.Label(labelRect, "Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar", EditorStyles.miniLabel); - } - - // Show marker below this Item - if (m_TreeView.dragging != null && m_TreeView.dragging.GetRowMarkerControlID() == itemControlID) - m_DraggingInsertionMarkerRect = new Rect(rowRect.x + indent , rowRect.y, rowRect.width - indent, rowRect.height); - } - - // Draw foldout (after text content above to ensure drop down icon is rendered above selection highlight) - if (showFoldout) - { - tmpRect.x = indent; - tmpRect.width = m_FoldoutWidth; - EditorGUI.BeginChangeCheck(); - bool newExpandedValue = GUI.Toggle(tmpRect, m_TreeView.data.IsExpanded(item), GUIContent.none, Styles.foldout); - if (EditorGUI.EndChangeCheck()) - { - m_TreeView.UserInputChangedExpandedState(item, row, newExpandedValue); - } - } - } - - /* - void ChangeExpandedState(TreeViewItem item, bool expand) - { - if (Event.current.alt) - m_TreeView.data.SetExpandedWithChildren(item, expand); - else - m_TreeView.data.SetExpanded(item, expand); - - if (expand) - m_TreeView.UserExpandedItem(item); - }*/ - } -} diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestLazyDataSource.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestLazyDataSource.cs deleted file mode 100644 index 1299439d0b..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestLazyDataSource.cs +++ /dev/null @@ -1,85 +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.Collections.Generic; -using UnityEditor.IMGUI.Controls; - - -namespace UnityEditor.TreeViewExamples -{ - class LazyTestDataSource : LazyTreeViewDataSource - { - private BackendData m_Backend; - public int itemCounter { get; private set; } - - public LazyTestDataSource(TreeViewController treeView, BackendData data) - : base(treeView) - { - m_Backend = data; - FetchData(); - } - - public override void FetchData() - { - // For LazyTreeViewDataSources we just generate the 'm_VisibleRows' items: - itemCounter = 1; - m_RootItem = new FooTreeViewItem(m_Backend.root.id, 0, null, m_Backend.root.name, m_Backend.root); - AddVisibleChildrenRecursive(m_Backend.root, m_RootItem); - - m_Rows = new List(); - GetVisibleItemsRecursive(m_RootItem, m_Rows); - m_NeedRefreshRows = false; - } - - void AddVisibleChildrenRecursive(BackendData.Foo source, TreeViewItem dest) - { - if (IsExpanded(source.id)) - { - if (source.children != null && source.children.Count > 0) - { - dest.children = new List(source.children.Count); - for (int i = 0; i < source.children.Count; ++i) - { - BackendData.Foo s = source.children[i]; - dest.children.Add(new FooTreeViewItem(s.id, dest.depth + 1, dest, s.name, s)); - ++itemCounter; - AddVisibleChildrenRecursive(s, dest.children[i]); - } - } - } - else - { - if (source.hasChildren) - { - dest.children = CreateChildListForCollapsedParent(); // ensure we show the collapse arrow (because we do not fetch data for collapsed items) - } - } - } - - public override bool CanBeParent(TreeViewItem item) - { - return item.hasChildren; - } - - protected override HashSet GetParentsAbove(int id) - { - HashSet parentsAbove = new HashSet(); - BackendData.Foo target = BackendData.FindItemRecursive(m_Backend.root, id); - - while (target != null) - { - if (target.parent != null) - parentsAbove.Add(target.parent.id); - target = target.parent; - } - return parentsAbove; - } - - protected override HashSet GetParentsBelow(int id) - { - HashSet parents = m_Backend.GetParentsBelow(id); - return parents; - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWindow.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWindow.cs deleted file mode 100644 index 969bebc7e3..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWindow.cs +++ /dev/null @@ -1,95 +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; - - -namespace UnityEditor.TreeViewExamples -{ - internal class TreeViewTestWindow : EditorWindow, IHasCustomMenu - { - // Test 1 - private BackendData m_BackendData; - private TreeViewTest m_TreeViewTest; - private TreeViewTest m_TreeViewTest2; - - // Test 2 - private BackendData m_BackendData2; - private TreeViewTestWithCustomHeight m_TreeViewWithCustomHeight; - - private TestType m_TestType = TestType.LargeTreesWithStandardGUI; - - enum TestType - { - LargeTreesWithStandardGUI, - TreeWithCustomItemHeight - } - - public TreeViewTestWindow() - { - titleContent = EditorGUIUtility.TrTextContent("TreeView Test"); - } - - void OnEnable() - { - position = new Rect(100, 100, 600, 600); - } - - void OnGUI() - { - switch (m_TestType) - { - case TestType.LargeTreesWithStandardGUI: - TestLargeTreesWithFixedItemHeightAndPingingAndFraming(); - break; - case TestType.TreeWithCustomItemHeight: - TestTreeWithCustomItemHeights(); - break; - } - } - - void TestTreeWithCustomItemHeights() - { - Rect rect = new Rect(0, 0, position.width, position.height); - if (m_TreeViewWithCustomHeight == null) - { - m_BackendData2 = new BackendData(); - m_BackendData2.GenerateData(300); - - m_TreeViewWithCustomHeight = new TreeViewTestWithCustomHeight(this, m_BackendData2, rect); - } - - m_TreeViewWithCustomHeight.OnGUI(rect); - } - - void TestLargeTreesWithFixedItemHeightAndPingingAndFraming() - { - Rect leftRect = new Rect(0, 0, position.width / 2, position.height); - Rect rightRect = new Rect(position.width / 2, 0, position.width / 2, position.height); - if (m_TreeViewTest == null) - { - m_BackendData = new BackendData(); - m_BackendData.GenerateData(1000000); - - bool lazy = false; - m_TreeViewTest = new TreeViewTest(this, lazy); - m_TreeViewTest.Init(leftRect, m_BackendData); - - lazy = true; - m_TreeViewTest2 = new TreeViewTest(this, lazy); - m_TreeViewTest2.Init(rightRect, m_BackendData); - } - - m_TreeViewTest.OnGUI(leftRect); - m_TreeViewTest2.OnGUI(rightRect); - EditorGUI.DrawRect(new Rect(leftRect.xMax - 1, 0, 2, position.height), new Color(0.4f, 0.4f, 0.4f, 0.8f)); - } - - public virtual void AddItemsToMenu(GenericMenu menu) - { - menu.AddItem(EditorGUIUtility.TrTextContent("Large TreeView"), m_TestType == TestType.LargeTreesWithStandardGUI, () => m_TestType = TestType.LargeTreesWithStandardGUI); - menu.AddItem(EditorGUIUtility.TrTextContent("Custom Item Height TreeView"), m_TestType == TestType.TreeWithCustomItemHeight, () => m_TestType = TestType.TreeWithCustomItemHeight); - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWithCustomHeight.cs b/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWithCustomHeight.cs deleted file mode 100644 index 700b25b8d1..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWithCustomHeight.cs +++ /dev/null @@ -1,37 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - - -namespace UnityEditor.TreeViewExamples -{ - internal class TreeViewTestWithCustomHeight - { - private BackendData m_BackendData; - private TreeViewController m_TreeView; - - public TreeViewTestWithCustomHeight(EditorWindow editorWindow, BackendData backendData, Rect rect) - { - m_BackendData = backendData; - - var state = new TreeViewState(); - - m_TreeView = new TreeViewController(editorWindow, state); - var gui = new TestGUICustomItemHeights(m_TreeView); - var dragging = new TestDragging(m_TreeView, m_BackendData); - var dataSource = new TestDataSource(m_TreeView, m_BackendData); - dataSource.onVisibleRowsChanged += gui.CalculateRowRects; - m_TreeView.Init(rect, dataSource, gui, dragging); - dataSource.SetExpanded(dataSource.root, true); - } - - public void OnGUI(Rect rect) - { - int keyboardControl = GUIUtility.GetControlID(FocusType.Keyboard, rect); - m_TreeView.OnGUI(rect, keyboardControl); - } - } -} // UnityEditor diff --git a/Editor/Mono/GUI/TreeView/TreeViewUtililty.cs b/Editor/Mono/GUI/TreeView/TreeViewUtililty.cs deleted file mode 100644 index c1925becf4..0000000000 --- a/Editor/Mono/GUI/TreeView/TreeViewUtililty.cs +++ /dev/null @@ -1,223 +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; - -namespace UnityEditor.IMGUI.Controls -{ - internal static class TreeViewUtility - { - internal static void SetParentAndChildrenForItems(IList rows, TreeViewItem root) - { - SetChildParentReferences(rows, root); - } - - // For setting depths values based on children state of the items - internal static void SetDepthValuesForItems(TreeViewItem root) - { - if (root == null) - throw new ArgumentNullException("root", "The root is null"); - - Stack stack = new Stack(); - stack.Push(root); - while (stack.Count > 0) - { - TreeViewItem current = stack.Pop(); - if (current.children != null) - { - foreach (var child in current.children) - { - if (child != null) - { - child.depth = current.depth + 1; - stack.Push(child); - } - } - } - } - } - - internal static List FindItemsInList(IEnumerable itemIDs, IList treeViewItems) - { - return (from x in treeViewItems where itemIDs.Contains(x.id) select x).ToList(); - } - - internal static TreeViewItem FindItemInList(int id, IList treeViewItems) where T : TreeViewItem - { - return treeViewItems.FirstOrDefault(t => t.id == id); - } - - // Assumes full tree - internal static TreeViewItem FindItem(int id, TreeViewItem searchFromThisItem) - { - return FindItemRecursive(id, searchFromThisItem); - } - - static TreeViewItem FindItemRecursive(int id, TreeViewItem item) - { - if (item == null) - return null; - - if (item.id == id) - return item; - - if (!item.hasChildren) - return null; - - foreach (TreeViewItem child in item.children) - { - TreeViewItem result = FindItemRecursive(id, child); - if (result != null) - return result; - } - return null; - } - - // Assumes full tree - internal static HashSet GetParentsAboveItem(TreeViewItem fromItem) - { - if (fromItem == null) - throw new ArgumentNullException("fromItem"); - - var hashSet = new HashSet(); - TreeViewItem parent = fromItem.parent; - while (parent != null) - { - hashSet.Add(parent.id); - parent = parent.parent; - } - return hashSet; - } - - // Assumes full tree - internal static HashSet GetParentsBelowItem(TreeViewItem fromItem) - { - if (fromItem == null) - throw new ArgumentNullException("fromItem"); - - Stack stack = new Stack(); - stack.Push(fromItem); - - HashSet parents = new HashSet(); - while (stack.Count > 0) - { - TreeViewItem current = stack.Pop(); - if (current.hasChildren) - { - parents.Add(current.id); - if (LazyTreeViewDataSource.IsChildListForACollapsedParent(current.children)) - throw new InvalidOperationException("Invalid tree for finding descendants: Ensure a complete tree when using this utillity method."); - - foreach (var foo in current.children) - { - stack.Push(foo); - } - } - } - return parents; - } - - internal static void DebugPrintToEditorLogRecursive(TreeViewItem item) - { - if (item == null) - return; - System.Console.WriteLine(new System.String(' ', item.depth * 3) + item.displayName); - - if (!item.hasChildren) - return; - - foreach (TreeViewItem child in item.children) - { - DebugPrintToEditorLogRecursive(child); - } - } - - // Setup child and parent references based on the depth of the tree view items in 'visibleItems' - internal static void SetChildParentReferences(IList visibleItems, TreeViewItem root) - { - for (int i = 0; i < visibleItems.Count; i++) - visibleItems[i].parent = null; - - // Set child and parent references using depth info - int rootChildCount = 0; - for (int i = 0; i < visibleItems.Count; i++) - { - SetChildParentReferences(i, visibleItems); - - if (visibleItems[i].parent == null) - rootChildCount++; - } - - // Ensure items without a parent gets 'root' as parent - if (rootChildCount > 0) - { - var rootChildren = new List(rootChildCount); - for (int i = 0; i < visibleItems.Count; i++) - { - if (visibleItems[i].parent == null) - { - rootChildren.Add(visibleItems[i]); - visibleItems[i].parent = root; - } - } - root.children = rootChildren; - } - else - root.children = new List(); - } - - static void SetChildren(TreeViewItem item, List newChildList) - { - // Do not touch children if we have a LazyParent and did not find any children == keep lazy children - if (LazyTreeViewDataSource.IsChildListForACollapsedParent(item.children) && newChildList == null) - return; - - item.children = newChildList; - } - - static void SetChildParentReferences(int parentIndex, IList visibleItems) - { - TreeViewItem parent = visibleItems[parentIndex]; - bool alreadyHasValidChildren = parent.children != null && parent.children.Count > 0 && parent.children[0] != null; - if (alreadyHasValidChildren) - return; - - int parentDepth = parent.depth; - int childCount = 0; - - // Count children based depth value, we are looking at children until it's the same depth as this object - for (int i = parentIndex + 1; i < visibleItems.Count; i++) - { - if (visibleItems[i].depth == parentDepth + 1) - childCount++; - if (visibleItems[i].depth <= parentDepth) - break; - } - - // Fill child array - List childList = null; - if (childCount != 0) - { - childList = new List(childCount); // Allocate once - childCount = 0; - for (int i = parentIndex + 1; i < visibleItems.Count; i++) - { - if (visibleItems[i].depth == parentDepth + 1) - { - visibleItems[i].parent = parent; - childList.Add(visibleItems[i]); - childCount++; - } - - if (visibleItems[i].depth <= parentDepth) - break; - } - } - - SetChildren(parent, childList); - } - } -} diff --git a/Editor/Mono/GUI/VUMeter.cs b/Editor/Mono/GUI/VUMeter.cs deleted file mode 100644 index b4142d24d0..0000000000 --- a/Editor/Mono/GUI/VUMeter.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 UnityEngine; - -namespace UnityEditor -{ - public sealed partial class EditorGUI - { - internal class VUMeter - { - static Texture2D s_VerticalVUTexture; - static Texture2D s_HorizontalVUTexture; - const float VU_SPLIT = 0.9f; - - public struct SmoothingData - { - public float lastValue; - public float peakValue; - public float peakValueTime; - } - - public static Texture2D verticalVUTexture - { - get - { - if (s_VerticalVUTexture == null) - s_VerticalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureVertical"); - return s_VerticalVUTexture; - } - } - - public static Texture2D horizontalVUTexture - { - get - { - if (s_HorizontalVUTexture == null) - s_HorizontalVUTexture = EditorGUIUtility.LoadIcon("VUMeterTextureHorizontal"); - return s_HorizontalVUTexture; - } - } - - public static void HorizontalMeter(Rect position, float value, float peak, Texture2D foregroundTexture, Color peakColor) - { - if (Event.current.type != EventType.Repaint) - return; - - Color temp = GUI.color; - - // Draw background - EditorStyles.progressBarBack.Draw(position, false, false, false, false); - - // Draw foreground - GUI.color = new Color(1f, 1f, 1f, GUI.enabled ? 1 : 0.5f); - float width = position.width * value - 2; - if (width < 2) - width = 2; - Rect newRect = new Rect(position.x + 1, position.y + 1, width, position.height - 2); - Rect uvRect = new Rect(0, 0, value, 1); - GUI.DrawTextureWithTexCoords(newRect, foregroundTexture, uvRect); - - // Draw peak indicator - GUI.color = peakColor; - float peakpos = position.width * peak - 2; - if (peakpos < 2) - peakpos = 2; - newRect = new Rect(position.x + peakpos, position.y + 1, 1, position.height - 2); - GUI.DrawTexture(newRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); - - // Reset color - GUI.color = temp; - } - - public static void VerticalMeter(Rect position, float value, float peak, Texture2D foregroundTexture, Color peakColor) - { - if (Event.current.type != EventType.Repaint) - return; - - Color temp = GUI.color; - - // Draw background - EditorStyles.progressBarBack.Draw(position, false, false, false, false); - - // Draw foreground - GUI.color = new Color(1f, 1f, 1f, GUI.enabled ? 1 : 0.5f); - float height = (position.height - 2) * value; - if (height < 2) - height = 2; - Rect newRect = new Rect(position.x + 1, (position.y + position.height - 1) - height, position.width - 2, height); - Rect uvRect = new Rect(0, 0, 1, value); - GUI.DrawTextureWithTexCoords(newRect, foregroundTexture, uvRect); - - // Draw peak indicator - GUI.color = peakColor; - float peakpos = (position.height - 2) * peak; - if (peakpos < 2) - peakpos = 2; - newRect = new Rect(position.x + 1, (position.y + position.height - 1) - peakpos, position.width - 2, 1); - GUI.DrawTexture(newRect, EditorGUIUtility.whiteTexture, ScaleMode.StretchToFill); - - // Reset color - GUI.color = temp; - } - - // Auto smoothing version - public static void HorizontalMeter(Rect position, float value, ref SmoothingData data, Texture2D foregroundTexture, Color peakColor) - { - if (Event.current.type != EventType.Repaint) - return; - - float renderValue, renderPeak; - SmoothVUMeterData(ref value, ref data, out renderValue, out renderPeak); - HorizontalMeter(position, renderValue, renderPeak, foregroundTexture, peakColor); - } - - // Auto smoothing version - public static void VerticalMeter(Rect position, float value, ref SmoothingData data, Texture2D foregroundTexture, Color peakColor) - { - if (Event.current.type != EventType.Repaint) - return; - - float renderValue, renderPeak; - SmoothVUMeterData(ref value, ref data, out renderValue, out renderPeak); - VerticalMeter(position, renderValue, renderPeak, foregroundTexture, peakColor); - } - - static void SmoothVUMeterData(ref float value, ref SmoothingData data, out float renderValue, out float renderPeak) - { - if (value <= data.lastValue) - { - value = Mathf.Lerp(data.lastValue, value, Time.smoothDeltaTime * 7.0f); - } - else - { - value = Mathf.Lerp(value, data.lastValue, Time.smoothDeltaTime * 2.0f); - data.peakValue = value; - data.peakValueTime = Time.realtimeSinceStartup; - } - - if (value > 1.0f / VU_SPLIT) - value = 1.0f / VU_SPLIT; - if (data.peakValue > 1.0f / VU_SPLIT) - data.peakValue = 1.0f / VU_SPLIT; - - renderValue = value * VU_SPLIT; - renderPeak = data.peakValue * VU_SPLIT; - - data.lastValue = value; - } - } // VUMeter - } // UnityGUI -} // UnityEditor diff --git a/Editor/Mono/GUI/VerticalGrid.cs b/Editor/Mono/GUI/VerticalGrid.cs deleted file mode 100644 index a0c37349aa..0000000000 --- a/Editor/Mono/GUI/VerticalGrid.cs +++ /dev/null @@ -1,270 +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; - -namespace UnityEditor -{ - internal class VerticalGrid - { - int m_Columns = 1; - int m_Rows; - float m_Height; - float m_HorizontalSpacing; - - public int columns { get {return m_Columns; } } - public int rows { get {return m_Rows; } } - public float height { get {return m_Height; } } - public float horizontalSpacing { get {return m_HorizontalSpacing; } } - - // Adjust grid values - public float fixedWidth { get; set; } - public Vector2 itemSize { get; set; } - public float verticalSpacing { get; set; } // spacing between each row of items - public float minHorizontalSpacing { get; set; } // minimum spacing between each column in grid - public float topMargin { get; set; } - public float bottomMargin { get; set; } - public float rightMargin { get; set; } - public float leftMargin { get; set; } - public float fixedHorizontalSpacing {get; set; } - public bool useFixedHorizontalSpacing {get; set; } - - // Call after setting parameters above and before using CalcRect - public void InitNumRowsAndColumns(int itemCount, int maxNumRows) - { - if (useFixedHorizontalSpacing) - { - // Set columns (with an excess of 1 fixedHorizontalSpacing) - m_Columns = CalcColumns(); - - // Set horizontal spacing - m_HorizontalSpacing = fixedHorizontalSpacing; - - // Set rows - m_Rows = Mathf.Min(maxNumRows, CalcRows(itemCount)); - - // Set height - m_Height = m_Rows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; - } - else // center columns - { - // Set columns (with an excess of 1 minHorizontalSpacing) - m_Columns = CalcColumns(); - - // Set horizontal spacing - m_HorizontalSpacing = Mathf.Max(0f, (fixedWidth - (m_Columns * itemSize.x + leftMargin + rightMargin)) / (m_Columns)); - - // Set rows - m_Rows = Mathf.Min(maxNumRows, CalcRows(itemCount)); - - if (m_Rows == 1) - m_HorizontalSpacing = minHorizontalSpacing; - - // Set height - m_Height = m_Rows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; - } - } - - public int CalcColumns() - { - float horizontalSpacing = useFixedHorizontalSpacing ? fixedHorizontalSpacing : minHorizontalSpacing; - int cols = (int)Mathf.Floor((fixedWidth - leftMargin - rightMargin) / (itemSize.x + horizontalSpacing)); - cols = Mathf.Max(cols, 1); - return cols; - } - - public int CalcRows(int itemCount) - { - int t = (int)Mathf.Ceil(itemCount / (float)CalcColumns()); - if (t < 0) - return int.MaxValue; - return t; - } - - public Rect CalcRect(int itemIdx, float yOffset) - { - float row = Mathf.Floor(itemIdx / columns); - float column = itemIdx - row * columns; - - if (useFixedHorizontalSpacing) - { - return new Rect(leftMargin + column * (itemSize.x + fixedHorizontalSpacing), - row * (itemSize.y + verticalSpacing) + topMargin + yOffset, - itemSize.x, - itemSize.y); - } - else - { - return new Rect(leftMargin + horizontalSpacing * 0.5f + column * (itemSize.x + horizontalSpacing), - row * (itemSize.y + verticalSpacing) + topMargin + yOffset, - itemSize.x, - itemSize.y); - } - } - - public int GetMaxVisibleItems(float height) - { - int visibleRows = (int)Mathf.Ceil((height - topMargin - bottomMargin) / (itemSize.y + verticalSpacing)); - return visibleRows * columns; - } - - public bool IsVisibleInScrollView(float scrollViewHeight, float scrollPos, float gridStartY, int maxIndex, out int startIndex, out int endIndex) - { - startIndex = endIndex = 0; - - // In grid coordinates - - float scrollViewStart = scrollPos; - float scrollViewEnd = scrollPos + scrollViewHeight; - - float offsetY = gridStartY + topMargin; - - // Entirely below view - if (offsetY > scrollViewEnd) - return false; - - // Entirely above view - if (offsetY + height < scrollViewStart) - return false; - - float itemHeightAndSpacing = itemSize.y + verticalSpacing; - - // startRow can be negative if grid is starting in the middle of the view - int startRow = Mathf.FloorToInt((scrollViewStart - offsetY) / itemHeightAndSpacing); - startIndex = startRow * columns; - startIndex = Mathf.Clamp(startIndex, 0, maxIndex); - - // endRow can be negative if grid is starting in the middle of the view - int endRow = Mathf.FloorToInt((scrollViewEnd - offsetY) / itemHeightAndSpacing); - endIndex = (endRow + 1) * columns - 1; - endIndex = Mathf.Clamp(endIndex, 0, maxIndex); - - return true; - } - - public override string ToString() - { - return string.Format("VerticalGrid: rows {0}, columns {1}, fixedWidth {2}, itemSize {3}", rows, columns, fixedWidth, itemSize); - } - } - - - internal class VerticalGridWithSplitter - { - int m_Columns = 1; - int m_Rows; - float m_Height; - float m_HorizontalSpacing; - - public int columns { get {return m_Columns; } } - public int rows { get {return m_Rows; } } - public float height { get {return m_Height; } } - public float horizontalSpacing { get {return m_HorizontalSpacing; } } - - // Adjust grid values - public float fixedWidth { get; set; } - public Vector2 itemSize { get; set; } - public float verticalSpacing { get; set; } // spacing between each row of items - public float minHorizontalSpacing { get; set; } // minimum spacing between each column in grid - public float topMargin { get; set; } - public float bottomMargin { get; set; } - public float rightMargin { get; set; } - public float leftMargin { get; set; } - - // Call after setting parameters above and before using CalcRect - public void InitNumRowsAndColumns(int itemCount, int maxNumRows) - { - // Set columns (with an excess of 1 minHorizontalSpacing) - m_Columns = (int)Mathf.Floor((fixedWidth - leftMargin - rightMargin) / (itemSize.x + minHorizontalSpacing)); - m_Columns = Mathf.Max(m_Columns, 1); - - // Set horizontal spacing - m_HorizontalSpacing = 0f; - if (m_Columns > 1) - m_HorizontalSpacing = (fixedWidth - (m_Columns * itemSize.x + leftMargin + rightMargin)) / (m_Columns - 1); - - // Set rows - m_Rows = Mathf.Min(maxNumRows, (int)Mathf.Ceil(itemCount / (float)m_Columns)); - - // Set height - m_Height = m_Rows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; - } - - public Rect CalcRect(int itemIdx, float yOffset) - { - float row = Mathf.Floor(itemIdx / columns); - float column = itemIdx - row * columns; - - return new Rect(column * (itemSize.x + horizontalSpacing) + leftMargin, - row * (itemSize.y + verticalSpacing) + topMargin + yOffset, - itemSize.x, - itemSize.y); - } - - public int GetMaxVisibleItems(float height) - { - int visibleRows = (int)Mathf.Ceil((height - topMargin - bottomMargin) / (itemSize.y + verticalSpacing)); - return visibleRows * columns; - } - - int m_SplitAfterRow; - float m_CurrentSplitHeight; - float m_LastSplitUpdate; - float m_TargetSplitHeight; - - public void ResetSplit() - { - m_SplitAfterRow = -1; - m_CurrentSplitHeight = 0f; - m_LastSplitUpdate = -1f; - m_TargetSplitHeight = 0f; - } - - public void OpenSplit(int splitAfterRowIndex, int numItems) - { - int numRows = (int)Mathf.Ceil(numItems / (float)m_Columns); - float splitHeight = numRows * (itemSize.y + verticalSpacing) - verticalSpacing + topMargin + bottomMargin; - m_SplitAfterRow = splitAfterRowIndex; - m_TargetSplitHeight = splitHeight; - m_LastSplitUpdate = Time.realtimeSinceStartup; - } - - // Returns Rect of split content starting from index 0 - public Rect CalcSplitRect(int splitIndex, float yOffset) - { - Rect rect = new Rect(0, 0, 0, 0); - - return rect; - } - - public void CloseSplit() - { - m_TargetSplitHeight = 0f; - } - - // Returns true if animating (client should ensure to repaint in this case) - public bool UpdateSplitAnimationOnGUI() - { - if (m_SplitAfterRow != -1) - { - float delta = Time.realtimeSinceStartup - m_LastSplitUpdate; - m_CurrentSplitHeight = delta * m_TargetSplitHeight; - - m_LastSplitUpdate = Time.realtimeSinceStartup; - - // Animate - if (m_CurrentSplitHeight != m_TargetSplitHeight && Event.current.type == EventType.Repaint) - { - m_CurrentSplitHeight = Mathf.MoveTowards(m_CurrentSplitHeight, m_TargetSplitHeight, 0.03f); - if (m_CurrentSplitHeight == 0 && m_TargetSplitHeight == 0) - { - ResetSplit(); - } - return true; - } - } - return false; - } - } -} diff --git a/Editor/Mono/GUI/WindowLayout.cs b/Editor/Mono/GUI/WindowLayout.cs index 7ce55f3e21..0b3d4ea174 100644 --- a/Editor/Mono/GUI/WindowLayout.cs +++ b/Editor/Mono/GUI/WindowLayout.cs @@ -356,10 +356,13 @@ internal static void MaximizeKeyHandler(ShortcutArguments args) var mouseOverWindow = EditorWindow.mouseOverWindow; - if (IsMaximized(mouseOverWindow)) - Unmaximize(mouseOverWindow); - else - Maximize(mouseOverWindow); + if (mouseOverWindow != null) + { + if (IsMaximized(mouseOverWindow)) + Unmaximize(mouseOverWindow); + else + Maximize(mouseOverWindow); + } } public static void AddSplitViewAndChildrenRecurse(View splitview, ArrayList list) @@ -597,7 +600,7 @@ public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated throw new System.Exception(); } - mainWindow.Show(mainWindow.showMode, true, true); + mainWindow.Show(mainWindow.showMode, loadPosition: true, displayImmediately: true, setFocus: true); // Show other windows for (int i = 0; i < newWindows.Count; i++) @@ -608,7 +611,7 @@ public static bool LoadWindowLayout(string path, bool newProjectLayoutWasCreated ContainerWindow containerWindow = newWindows[i] as ContainerWindow; if (containerWindow && containerWindow != mainWindow) - containerWindow.Show(containerWindow.showMode, true, true); + containerWindow.Show(containerWindow.showMode, loadPosition: true, displayImmediately: true, setFocus: true); } // Unmaximize maximized GameView if maximize on play is enabled diff --git a/Editor/Mono/GUIView.cs b/Editor/Mono/GUIView.cs index 2398aec6e2..a86b7dd95c 100644 --- a/Editor/Mono/GUIView.cs +++ b/Editor/Mono/GUIView.cs @@ -36,7 +36,6 @@ protected Panel panel { if (m_Panel == null) { - UXMLEditorFactories.RegisterAll(); m_Panel = UIElementsUtility.FindOrCreatePanel(this, ContextType.Editor, DataWatchService.sharedInstance); m_Panel.cursorManager = m_CursorManager; m_Panel.contextualMenuManager = s_ContextualMenuManager; diff --git a/Editor/Mono/GameView/GameView.cs b/Editor/Mono/GameView/GameView.cs index 628b539d89..8f0c17b335 100644 --- a/Editor/Mono/GameView/GameView.cs +++ b/Editor/Mono/GameView/GameView.cs @@ -385,6 +385,9 @@ private void UpdateZoomAreaAndParent() CopyDimensionsToParentView(); m_LastWindowPixelSize = position.size * EditorGUIUtility.pixelsPerPoint; EditorApplication.SetSceneRepaintDirty(); + + // update the scale according to new resolution + m_ZoomArea.UpdateZoomScale(maxScale, minScale); } void AllowCursorLockAndHide(bool enable) diff --git a/Editor/Mono/GameView/GameViewSizeGroup.cs b/Editor/Mono/GameView/GameViewSizeGroup.cs deleted file mode 100644 index b97cb0f1d5..0000000000 --- a/Editor/Mono/GameView/GameViewSizeGroup.cs +++ /dev/null @@ -1,118 +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 System.Collections.Generic; - -namespace UnityEditor -{ - [System.Serializable] - internal class GameViewSizeGroup - { - [System.NonSerialized] - private List m_Builtin = new List(); - - [SerializeField] - private List m_Custom = new List(); - - // Builtin sizes first then custom sizes - public GameViewSize GetGameViewSize(int index) - { - if (index < m_Builtin.Count) - return m_Builtin[index]; - - index -= m_Builtin.Count; - - if (index >= 0 && index < m_Custom.Count) - return m_Custom[index]; - - Debug.LogError("Invalid index " + (index + m_Builtin.Count) + " " + m_Builtin.Count + " " + m_Custom.Count); - return new GameViewSize(GameViewSizeType.AspectRatio, 0, 0, ""); - } - - public string[] GetDisplayTexts() - { - List displayList = new List(); - foreach (GameViewSize size in m_Builtin) - displayList.Add(size.displayText); - foreach (GameViewSize size in m_Custom) - displayList.Add(size.displayText); - return displayList.ToArray(); - } - - public int GetTotalCount() - { - return m_Builtin.Count + m_Custom.Count; - } - - public int GetBuiltinCount() - { - return m_Builtin.Count; - } - - public int GetCustomCount() - { - return m_Custom.Count; - } - - public void AddBuiltinSizes(params GameViewSize[] sizes) - { - for (int i = 0; i < sizes.Length; i++) - AddBuiltinSize(sizes[i]); - } - - public void AddBuiltinSize(GameViewSize size) - { - m_Builtin.Add(size); - GameViewSizes.instance.Changed(); - } - - public void AddCustomSizes(params GameViewSize[] sizes) - { - for (int i = 0; i < sizes.Length; i++) - AddCustomSize(sizes[i]); - } - - public void AddCustomSize(GameViewSize size) - { - m_Custom.Add(size); - GameViewSizes.instance.Changed(); - } - - public void RemoveCustomSize(int index) - { - int customIndex = TotalIndexToCustomIndex(index); - if (customIndex >= 0 && customIndex < m_Custom.Count) - { - m_Custom.RemoveAt(customIndex); - GameViewSizes.instance.Changed(); - } - else - { - Debug.LogError("Invalid index " + index + " " + m_Builtin.Count + " " + m_Custom.Count); - } - } - - public bool IsCustomSize(int index) - { - if (index < m_Builtin.Count) - return false; - return true; - } - - public int TotalIndexToCustomIndex(int index) - { - return index - m_Builtin.Count; - } - - public int IndexOf(GameViewSize view) - { - int index = m_Builtin.IndexOf(view); - if (index >= 0) - return index; - - return m_Custom.IndexOf(view); - } - } -} diff --git a/Editor/Mono/GameView/GameViewSizes.cs b/Editor/Mono/GameView/GameViewSizes.cs index 6a326192d2..72b896eda3 100644 --- a/Editor/Mono/GameView/GameViewSizes.cs +++ b/Editor/Mono/GameView/GameViewSizes.cs @@ -239,9 +239,10 @@ private void InitBuiltinGroups() k_4_3_Landscape, k_4_3_Portrait, k_iPhone4_Portrait, k_iPhone4_Landscape, k_iPhone5_Portrait, k_iPhone5_Landscape, - k_iPad_768p_Landscape, k_iPad_768p_Portrait); + k_iPad_768p_Landscape, k_iPad_768p_Portrait, + m_Remote); - m_Android.AddBuiltinSizes(kFree, m_Remote, + m_Android.AddBuiltinSizes(kFree, k_800x480_Portrait, k_800x480_Landscape, k_720p_Portrait, k_720p_Landscape, k_1080p_Portrait, k_1080p_Landscape, @@ -249,7 +250,8 @@ private void InitBuiltinGroups() k_2560x1440_Portrait, k_2560x1440_Landscape, k_2960x1440_Portrait, k_2960x1440_Landscape, k_16_9_Portrait, k_16_9_Landscape, - k_18_9_Portrait, k_18_9_Landscape); + k_18_9_Portrait, k_18_9_Landscape, + m_Remote); m_HMD.AddBuiltinSizes(kFree, m_Remote); } diff --git a/Editor/Mono/GameView/GameViewSizesMenuModifyItemUI.cs b/Editor/Mono/GameView/GameViewSizesMenuModifyItemUI.cs deleted file mode 100644 index 3c6eb2fd22..0000000000 --- a/Editor/Mono/GameView/GameViewSizesMenuModifyItemUI.cs +++ /dev/null @@ -1,152 +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; - -namespace UnityEditor -{ - internal class GameViewSizesMenuModifyItemUI : FlexibleMenuModifyItemUI - { - private class Styles - { - public GUIContent headerAdd = EditorGUIUtility.TrTextContent("Add"); - public GUIContent headerEdit = EditorGUIUtility.TrTextContent("Edit"); - public GUIContent typeName = EditorGUIUtility.TrTextContent("Type"); - public GUIContent widthHeightText = EditorGUIUtility.TrTextContent("Width & Height"); - public GUIContent optionalText = EditorGUIUtility.TrTextContent("Label"); - public GUIContent ok = EditorGUIUtility.TrTextContent("OK"); - public GUIContent cancel = EditorGUIUtility.TrTextContent("Cancel"); - public GUIContent[] typeNames = new[] {EditorGUIUtility.TrTextContent("Aspect Ratio"), EditorGUIUtility.TrTextContent("Fixed Resolution")}; - } - - private static Styles s_Styles; - private GameViewSize m_GameViewSize; - - public override void OnClose() - { - m_GameViewSize = null; - base.OnClose(); - } - - override public Vector2 GetWindowSize() - { - return new Vector2(230, 140); - } - - override public void OnGUI(Rect rect) - { - if (s_Styles == null) - s_Styles = new Styles(); - - GameViewSize gameViewSizeState = m_Object as GameViewSize; - if (gameViewSizeState == null) - { - Debug.LogError("Invalid object"); - return; - } - - // We use a local gameviewsize to ensure we do not edit the original state (if user presses cancel state is not changed) - if (m_GameViewSize == null) - m_GameViewSize = new GameViewSize(gameViewSizeState); - - bool validSettings = m_GameViewSize.width > 0 && m_GameViewSize.height > 0; - const float kColumnWidth = 90f; - const float kSpacing = 10f; - - GUILayout.Space(3); - GUILayout.Label(m_MenuType == MenuType.Add ? s_Styles.headerAdd : s_Styles.headerEdit, - EditorStyles.boldLabel); - - Rect seperatorRect = GUILayoutUtility.GetRect(1, 1); - FlexibleMenu.DrawRect(seperatorRect, - (EditorGUIUtility.isProSkin) - ? new Color(0.32f, 0.32f, 0.32f, 1.333f) - : new Color(0.6f, 0.6f, 0.6f, 1.333f)); // dark : light - GUILayout.Space(4); - - // Optional text - GUILayout.BeginHorizontal(); - GUILayout.Label(s_Styles.optionalText, GUILayout.Width(kColumnWidth)); - GUILayout.Space(kSpacing); - m_GameViewSize.baseText = EditorGUILayout.TextField(m_GameViewSize.baseText); - GUILayout.EndHorizontal(); - - // Drop list (aspect / fixed res) - GUILayout.BeginHorizontal(); - GUILayout.Label(s_Styles.typeName, GUILayout.Width(kColumnWidth)); - GUILayout.Space(kSpacing); - m_GameViewSize.sizeType = (GameViewSizeType)EditorGUILayout.Popup((int)m_GameViewSize.sizeType, s_Styles.typeNames); - GUILayout.EndHorizontal(); - - // Width Height - GUILayout.BeginHorizontal(); - GUILayout.Label(s_Styles.widthHeightText, GUILayout.Width(kColumnWidth)); - GUILayout.Space(kSpacing); - m_GameViewSize.width = EditorGUILayout.IntField(m_GameViewSize.width); - GUILayout.Space(5); - m_GameViewSize.height = EditorGUILayout.IntField(m_GameViewSize.height); - GUILayout.EndHorizontal(); - - GUILayout.Space(10f); - - // Displayed text - float margin = 10f; - float cropWidth = rect.width - 2 * margin; - GUILayout.BeginHorizontal(); - GUILayout.Space(margin); - GUILayout.FlexibleSpace(); - string displayText = m_GameViewSize.displayText; - using (new EditorGUI.DisabledScope(string.IsNullOrEmpty(displayText))) - { - if (string.IsNullOrEmpty(displayText)) - displayText = "Result"; - else - displayText = GetCroppedText(displayText, cropWidth, EditorStyles.label); - GUILayout.Label(GUIContent.Temp(displayText), EditorStyles.label); - } - GUILayout.FlexibleSpace(); - GUILayout.Space(margin); - GUILayout.EndHorizontal(); - - GUILayout.Space(5f); - - // Cancel, Ok - GUILayout.BeginHorizontal(); - GUILayout.Space(10); - if (GUILayout.Button(s_Styles.cancel)) - { - editorWindow.Close(); - } - - using (new EditorGUI.DisabledScope(!validSettings)) - { - if (GUILayout.Button(s_Styles.ok)) - { - gameViewSizeState.Set(m_GameViewSize); - Accepted(); - editorWindow.Close(); - } - } - GUILayout.Space(10); - GUILayout.EndHorizontal(); - } - - string GetCroppedText(string fullText, float cropWidth, GUIStyle style) - { - // Check if we need to crop - int characterCountVisible = style.GetNumCharactersThatFitWithinWidth(fullText, cropWidth); - if (characterCountVisible == -1) - { - return fullText; - } - - if (characterCountVisible > 1 && characterCountVisible != fullText.Length) - return fullText.Substring(0, characterCountVisible - 1) + ("\u2026"); // 'horizontal ellipsis' (U+2026) is: ... - else - return fullText; - } - } -} - -// namespace diff --git a/Editor/Mono/Grid/GridSnapping.cs b/Editor/Mono/Grid/GridSnapping.cs deleted file mode 100644 index 17e124810c..0000000000 --- a/Editor/Mono/Grid/GridSnapping.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; - -namespace UnityEditor -{ - internal static class GridSnapping - { - public static Func snapPosition; - public static Func activeFunc; - - public static bool active - { - get { return (activeFunc != null ? activeFunc() : false); } - } - - public static Vector3 Snap(Vector3 position) - { - if (snapPosition != null) - return snapPosition(position); - return position; - } - } -} diff --git a/Editor/Mono/HandleUtility.cs b/Editor/Mono/HandleUtility.cs index 8fc8f52881..2e87d2449c 100644 --- a/Editor/Mono/HandleUtility.cs +++ b/Editor/Mono/HandleUtility.cs @@ -26,7 +26,7 @@ public static float CalcLineTranslation(Vector2 src, Vector2 dest, Vector3 srcPo // The constrained direction is facing towards the camera, THATS BAD when the handle is close to the camera // The srcPosition goes through to the other side of the camera float invert = 1.0F; - Vector3 cameraForward = Camera.current.transform.forward; + Vector3 cameraForward = Camera.current == null ? Vector3.forward : Camera.current.transform.forward; if (Vector3.Dot(constraintDir, cameraForward) < 0.0F) invert = -1.0F; @@ -36,8 +36,13 @@ public static float CalcLineTranslation(Vector2 src, Vector2 dest, Vector3 srcPo Vector3 cd = constraintDir; cd.y = -cd.y; Camera cam = Camera.current; - Vector2 p1 = EditorGUIUtility.PixelsToPoints(cam.WorldToScreenPoint(srcPosition)); - Vector2 p2 = EditorGUIUtility.PixelsToPoints(cam.WorldToScreenPoint(srcPosition + constraintDir * invert)); + // if camera is null, then we are drawing in OnGUI, where y-coordinate goes top-to-bottom + Vector2 p1 = cam == null + ? Vector2.Scale(srcPosition, new Vector2(1f, -1f)) + : EditorGUIUtility.PixelsToPoints(cam.WorldToScreenPoint(srcPosition)); + Vector2 p2 = cam == null + ? Vector2.Scale(srcPosition + constraintDir * invert, new Vector2(1f, -1f)) + : EditorGUIUtility.PixelsToPoints(cam.WorldToScreenPoint(srcPosition + constraintDir * invert)); Vector2 p3 = dest; Vector2 p4 = src; diff --git a/Editor/Mono/Handles.cs b/Editor/Mono/Handles.cs index 4dd97995b5..db89421be6 100644 --- a/Editor/Mono/Handles.cs +++ b/Editor/Mono/Handles.cs @@ -550,8 +550,8 @@ public static void DotHandleCap(int controlID, Vector3 position, Quaternion rota // Only apply matrix to the position because DotCap is camera facing position = matrix.MultiplyPoint(position); - Vector3 sideways = Camera.current.transform.right * size; - Vector3 up = Camera.current.transform.up * size; + Vector3 sideways = (Camera.current == null ? Vector3.right : Camera.current.transform.right) * size; + Vector3 up = (Camera.current == null ? Vector3.up : Camera.current.transform.up) * size; Color col = color * new Color(1, 1, 1, 0.99f); HandleUtility.ApplyWireMaterial(Handles.zTest); diff --git a/Editor/Mono/Help.bindings.cs b/Editor/Mono/Help.bindings.cs deleted file mode 100644 index 23058cd14d..0000000000 --- a/Editor/Mono/Help.bindings.cs +++ /dev/null @@ -1,55 +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 Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngine.Bindings; - -namespace UnityEditor -{ - // Helper class to access Unity documentation. - [NativeHeader("Editor/Src/Panels/HelpPanel.h")] - [NativeHeader("Editor/Platform/Interface/EditorUtility.h")] - public class Help - { - // Is there a help page for this object? - public static bool HasHelpForObject(Object obj) { return HasHelpForObject(obj, true); } - - // Intentionally internal. Extra argument only used to make doc authoring easier. - [FreeFunction] - internal static extern bool HasHelpForObject(Object obj, bool defaultToMonoBehaviour); - - // Intentionally internal. - internal static string GetNiceHelpNameForObject(Object obj) - { - return GetNiceHelpNameForObject(obj, true); - } - - // Intentionally internal. - [FreeFunction] - internal static extern string GetNiceHelpNameForObject(Object obj, bool defaultToMonoBehaviour); - - public static string GetHelpURLForObject(Object obj) - { - return GetHelpURLForObject(obj, true); - } - - [FreeFunction] - private static extern string GetHelpURLForObject(Object obj, bool defaultToMonoBehaviour); - // Show help page for this object. - [FreeFunction] - public static extern void ShowHelpForObject(Object obj); - // Show a help page. - [FreeFunction("ShowNamedHelp")] - public static extern void ShowHelpPage(string page); - // Open /url/ in the default web browser. - [FreeFunction("OpenURLInWebbrowser")] - public static extern void BrowseURL(string url); - } -} diff --git a/Editor/Mono/HomeWindow.bindings.cs b/Editor/Mono/HomeWindow.bindings.cs deleted file mode 100644 index 66cc9c124f..0000000000 --- a/Editor/Mono/HomeWindow.bindings.cs +++ /dev/null @@ -1,28 +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.Bindings; - -namespace UnityEditor -{ - [NativeHeader("Editor/Src/HomeWindow/HomeWindow.h")] - static class HomeWindow - { - // NOTE: Keep in sync with enum in Editor/Src/HomeWindow/HomeWindow.h - public enum HomeMode - { - Login, - License, - Launching, - NewProjectOnly, - OpenProjectOnly, - ManageLicense, - Welcome, - Tutorial, - } - - [NativeMethod("StaticShow")] - public static extern bool Show(HomeMode mode); - } -} diff --git a/Editor/Mono/HostView.cs b/Editor/Mono/HostView.cs index ceccdc8cc7..bcd640d654 100644 --- a/Editor/Mono/HostView.cs +++ b/Editor/Mono/HostView.cs @@ -32,22 +32,24 @@ internal class HostView : GUIView internal EditorWindow actualView { get { return m_ActualView; } - set - { - if (m_ActualView == value) - return; - DeregisterSelectedPane(true); - m_ActualView = value; - m_IsGameView = m_ActualView is GameView; - RegisterSelectedPane(); - actualViewChanged?.Invoke(this); - } + set { SetActualViewInternal(value, sendEvents: true); } + } + + internal void SetActualViewInternal(EditorWindow value, bool sendEvents) + { + if (m_ActualView == value) + return; + DeregisterSelectedPane(clearActualView: true, sendEvents: true); + m_ActualView = value; + m_IsGameView = m_ActualView is GameView; + RegisterSelectedPane(sendEvents); + actualViewChanged?.Invoke(this); } internal void ResetActiveView() { - DeregisterSelectedPane(false); - RegisterSelectedPane(); + DeregisterSelectedPane(clearActualView: false, sendEvents: true); + RegisterSelectedPane(sendEvents: true); if (actualViewChanged != null) actualViewChanged(this); } @@ -94,7 +96,7 @@ protected override void OnEnable() EditorPrefs.onValueWasUpdated += PlayModeTintColorChangedCallback; base.OnEnable(); background = null; - RegisterSelectedPane(); + RegisterSelectedPane(sendEvents: true); } protected override void OnDisable() @@ -102,7 +104,7 @@ protected override void OnDisable() EditorApplication.playModeStateChanged -= PlayModeStateChangedCallback; EditorPrefs.onValueWasUpdated -= PlayModeTintColorChangedCallback; base.OnDisable(); - DeregisterSelectedPane(false); + DeregisterSelectedPane(clearActualView: false, sendEvents: true); } protected override void OldOnGUI() @@ -159,6 +161,11 @@ internal void OnLostFocus() { EditorGUI.EndEditingActiveTextField(); Invoke("OnLostFocus"); + + // Callback could have killed us + if (!this) + return; + Repaint(); } @@ -339,7 +346,7 @@ protected void Invoke(string methodName, object obj) mi?.Invoke(obj, null); } - protected void RegisterSelectedPane() + protected void RegisterSelectedPane(bool sendEvents) { if (!m_ActualView) return; @@ -368,24 +375,27 @@ protected void RegisterSelectedPane() EditorApplication.update += m_ActualView.CheckForWindowRepaint; } - try - { - Invoke("OnBecameVisible"); - EditorModes.OnBecameVisible(m_ActualView); - Invoke("OnFocus"); - EditorModes.OnFocus(m_ActualView); - } - catch (TargetInvocationException ex) + if (sendEvents) { - // We need to catch these so the window initialization doesn't get screwed - if (ex.InnerException != null) - Debug.LogError(ex.InnerException.GetType().Name + ":" + ex.InnerException.Message); + try + { + Invoke("OnBecameVisible"); + EditorModes.OnBecameVisible(m_ActualView); + Invoke("OnFocus"); + EditorModes.OnFocus(m_ActualView); + } + catch (TargetInvocationException ex) + { + // We need to catch these so the window initialization doesn't get screwed + if (ex.InnerException != null) + Debug.LogError(ex.InnerException.GetType().Name + ":" + ex.InnerException.Message); + } } UpdateViewMargins(m_ActualView); } - protected void DeregisterSelectedPane(bool clearActualView) + protected void DeregisterSelectedPane(bool clearActualView, bool sendEvents) { if (!m_ActualView) return; @@ -417,10 +427,13 @@ protected void DeregisterSelectedPane(bool clearActualView) { EditorWindow oldActualView = m_ActualView; m_ActualView = null; - Invoke("OnLostFocus", oldActualView); - EditorModes.OnLostFocus(m_ActualView); - Invoke("OnBecameInvisible", oldActualView); - EditorModes.OnBecameInvisible(oldActualView); + if (sendEvents) + { + Invoke("OnLostFocus", oldActualView); + EditorModes.OnLostFocus(m_ActualView); + Invoke("OnBecameInvisible", oldActualView); + EditorModes.OnBecameInvisible(oldActualView); + } } } diff --git a/Editor/Mono/ICleanuppable.cs b/Editor/Mono/ICleanuppable.cs deleted file mode 100644 index edb2df5192..0000000000 --- a/Editor/Mono/ICleanuppable.cs +++ /dev/null @@ -1,11 +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 -{ - internal interface ICleanuppable - { - void Cleanup(); - } -} diff --git a/Editor/Mono/IDropArea.cs b/Editor/Mono/IDropArea.cs deleted file mode 100644 index bf898ae0dc..0000000000 --- a/Editor/Mono/IDropArea.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 UnityEngine; -using UnityEditor; - -namespace UnityEditor -{ - // Interface for drag-dropping windows over each other. - // Must be implemented by anyone who can handle a dragged tab. - internal interface IDropArea - { - // Fill out a dropinfo class telling what should be done. - // NULL if no action - DropInfo DragOver(EditorWindow w, Vector2 screenPos); - - // If the client returned a DropInfo from the DragOver, they will get this call when the user releases the mouse - bool PerformDrop(EditorWindow w, DropInfo dropInfo, Vector2 screenPos); - } -} diff --git a/Editor/Mono/IHasCustomMenu.cs b/Editor/Mono/IHasCustomMenu.cs deleted file mode 100644 index 6419415567..0000000000 --- a/Editor/Mono/IHasCustomMenu.cs +++ /dev/null @@ -1,13 +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 UnityEditor; - -namespace UnityEditor -{ - public interface IHasCustomMenu - { - void AddItemsToMenu(GenericMenu menu); - } -} diff --git a/Editor/Mono/ImportSettings/AssetImporterEditor.cs b/Editor/Mono/ImportSettings/AssetImporterEditor.cs index d2e0537a7b..f981e73479 100644 --- a/Editor/Mono/ImportSettings/AssetImporterEditor.cs +++ b/Editor/Mono/ImportSettings/AssetImporterEditor.cs @@ -22,11 +22,13 @@ internal void InternalSetAssetImporterTargetEditor(Object editor) protected internal Object assetTarget { get { return m_AssetEditor != null ? m_AssetEditor.target : null; } } protected internal SerializedObject assetSerializedObject { get { return m_AssetEditor != null ? m_AssetEditor.serializedObject : null; } } + static string s_LocalizedTitleString = L10n.Tr("{0} Import Settings"); + internal override string targetTitle { get { - return string.Format(L10n.Tr("{0} Import Settings"), m_AssetEditor == null ? string.Empty : m_AssetEditor.targetTitle); + return string.Format(s_LocalizedTitleString, m_AssetEditor == null ? string.Empty : m_AssetEditor.targetTitle); } } diff --git a/Editor/Mono/ImportSettings/DesktopPluginImporterExtension.cs b/Editor/Mono/ImportSettings/DesktopPluginImporterExtension.cs index b2e66d701a..2264c4dac2 100644 --- a/Editor/Mono/ImportSettings/DesktopPluginImporterExtension.cs +++ b/Editor/Mono/ImportSettings/DesktopPluginImporterExtension.cs @@ -49,7 +49,7 @@ internal override void OnGUI(PluginImporterInspector inspector) // This toggle controls two things: // * Is platform enabled/disabled? // * Platform CPU value - bool isTargetEnabled = EditorGUILayout.Toggle(name, IsTargetEnabled(inspector)); + bool isTargetEnabled = EditorGUILayout.Toggle(name, IsTargetEnabled(inspector) && value.ToString() == defaultValue.ToString()); if (EditorGUI.EndChangeCheck()) { value = isTargetEnabled ? defaultValue : DesktopPluginCPUArchitecture.None; diff --git a/Editor/Mono/ImportSettings/EditorPluginImporterExtension.cs b/Editor/Mono/ImportSettings/EditorPluginImporterExtension.cs deleted file mode 100644 index d6866b0f13..0000000000 --- a/Editor/Mono/ImportSettings/EditorPluginImporterExtension.cs +++ /dev/null @@ -1,64 +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.IO; -using System.Text; -using System.Text.RegularExpressions; -using UnityEngine; -using UnityEditor; -using UnityEditor.Modules; - -namespace UnityEditor -{ - internal class EditorPluginImporterExtension : DefaultPluginImporterExtension - { - internal enum EditorPluginCPUArchitecture - { - AnyCPU, - x86, - x86_64 - }; - - internal enum EditorPluginOSArchitecture - { - AnyOS, - OSX, - Windows, - Linux - }; - - internal class EditorProperty : Property - { - public EditorProperty(GUIContent name, string key, object defaultValue) - : base(name, key, defaultValue, BuildPipeline.GetEditorTargetName()) - { - } - - internal override void Reset(PluginImporterInspector inspector) - { - string valueString = inspector.importer.GetEditorData(key); - ParseStringValue(inspector, valueString); - } - - internal override void Apply(PluginImporterInspector inspector) - { - inspector.importer.SetEditorData(key, value.ToString()); - } - } - - public EditorPluginImporterExtension() : base(GetProperties()) - { - } - - private static Property[] GetProperties() - { - return new[] - { - new EditorProperty(EditorGUIUtility.TrTextContent("CPU", "Is plugin compatible with 32bit or 64bit Editor?"), "CPU", EditorPluginCPUArchitecture.AnyCPU), - new EditorProperty(EditorGUIUtility.TrTextContent("OS", "Is plugin compatible with Windows, OS X or Linux Editor?"), "OS", EditorPluginOSArchitecture.AnyOS), - }; - } - } -} diff --git a/Editor/Mono/ImportSettings/PatchImportSettingsRecycleID.cs b/Editor/Mono/ImportSettings/PatchImportSettingsRecycleID.cs deleted file mode 100644 index 6d31ab153e..0000000000 --- a/Editor/Mono/ImportSettings/PatchImportSettingsRecycleID.cs +++ /dev/null @@ -1,38 +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 UnityEditor; -using UnityEngine; -using System; - -internal class PatchImportSettingRecycleID -{ - static public void Patch(SerializedObject serializedObject, int classID, string oldName, string newName) - { - PatchMultiple(serializedObject, classID, new string[] { oldName }, new string[] { newName }); - } - - // Patches multiple entries at once to avoid situations where swapping names of two entries would break references - static public void PatchMultiple(SerializedObject serializedObject, int classID, string[] oldNames, string[] newNames) - { - int left = oldNames.Length; - - SerializedProperty recycleMap = serializedObject.FindProperty("m_FileIDToRecycleName"); - foreach (SerializedProperty element in recycleMap) - { - SerializedProperty first = element.FindPropertyRelative("first"); - if (AssetImporter.LocalFileIDToClassID(first.longValue) == classID) - { - SerializedProperty second = element.FindPropertyRelative("second"); - int idx = Array.IndexOf(oldNames, second.stringValue); - if (idx >= 0) - { - second.stringValue = newNames[idx]; - if (--left == 0) - break; - } - } - } - } -} diff --git a/Editor/Mono/Inspector/AimConstraintEditor.cs b/Editor/Mono/Inspector/AimConstraintEditor.cs deleted file mode 100644 index 6f1ca2cdfe..0000000000 --- a/Editor/Mono/Inspector/AimConstraintEditor.cs +++ /dev/null @@ -1,142 +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.Animations; - -namespace UnityEditor -{ - [CustomEditor(typeof(AimConstraint))] - [CanEditMultipleObjects] - internal class AimConstraintEditor : ConstraintEditorBase - { - private SerializedProperty m_RotationAtRest; - private SerializedProperty m_RotationOffset; - private SerializedProperty m_AimVector; - private SerializedProperty m_UpVector; - private SerializedProperty m_WorldUpVector; - private SerializedProperty m_WorldUpObject; - private SerializedProperty m_WorldUpType; - private SerializedProperty m_Weight; - private SerializedProperty m_IsContraintActive; - private SerializedProperty m_IsLocked; - private SerializedProperty m_Sources; - - internal override SerializedProperty atRest { get { return m_RotationAtRest; } } - internal override SerializedProperty offset { get { return m_RotationOffset; } } - internal override SerializedProperty weight { get { return m_Weight; } } - internal override SerializedProperty isContraintActive { get { return m_IsContraintActive; } } - internal override SerializedProperty isLocked { get { return m_IsLocked; } } - internal override SerializedProperty sources { get { return m_Sources; } } - - private class Styles : ConstraintStyleBase - { - GUIContent m_RotationAtRest = EditorGUIUtility.TrTextContent("Rotation At Rest", "The orientation of the constrained object when the weights of the sources add up to zero or when all the rotation axes are disabled."); - GUIContent m_RotationOffset = EditorGUIUtility.TrTextContent("Rotation Offset", "The offset from the constrained orientation."); - - GUIContent m_RotationAxes = EditorGUIUtility.TrTextContent("Freeze Rotation Axes", "The axes along which the constraint is applied."); - - GUIContent m_AimVector = EditorGUIUtility.TrTextContent("Aim Vector", "Specifies which axis of the constrained object should aim at the target."); - GUIContent m_UpVector = EditorGUIUtility.TrTextContent("Up Vector", "Specifies the direction of the up vector in local space."); - GUIContent m_WorldUpVector = EditorGUIUtility.TrTextContent("World Up Vector", "Specifies the direction of the global up vector."); - GUIContent m_WorldUpObject = EditorGUIUtility.TrTextContent("World Up Object", "The reference object when the World Up Type is either Object Up or Object Rotation Up."); - GUIContent m_WorldUpType = EditorGUIUtility.TrTextContent("World Up Type", "Specifies how the world up vector should be computed."); - GUIContent[] m_WorldUpTypes = - { - EditorGUIUtility.TrTextContent("Scene Up", "Use the Y axis as the world up vector."), - EditorGUIUtility.TrTextContent("Object Up", "Use a vector that points to the reference object as the world up vector."), - EditorGUIUtility.TrTextContent("Object Rotation Up", "Use a vector defined in the reference object's local space as the world up vector."), - EditorGUIUtility.TrTextContent("Vector", "The world up vector is user defined."), - EditorGUIUtility.TrTextContent("None", "The world up vector is ignored.") - }; - public override GUIContent AtRest { get { return m_RotationAtRest; } } - public override GUIContent Offset { get { return m_RotationOffset; } } - public GUIContent FreezeAxes { get { return m_RotationAxes; } } - public GUIContent AimVector { get { return m_AimVector; } } - public GUIContent UpVector { get { return m_UpVector; } } - public GUIContent WorldUpVector { get { return m_WorldUpVector; } } - public GUIContent WorldUpObject { get { return m_WorldUpObject; } } - public GUIContent WorldUpType { get { return m_WorldUpType; } } - public GUIContent[] WorldUpTypes { get { return m_WorldUpTypes; } } - } - - private static Styles s_Style = null; - - public void OnEnable() - { - if (s_Style == null) - s_Style = new Styles(); - - m_RotationAtRest = serializedObject.FindProperty("m_RotationAtRest"); - m_RotationOffset = serializedObject.FindProperty("m_RotationOffset"); - - m_AimVector = serializedObject.FindProperty("m_AimVector"); - m_UpVector = serializedObject.FindProperty("m_UpVector"); - m_WorldUpVector = serializedObject.FindProperty("m_WorldUpVector"); - m_WorldUpObject = serializedObject.FindProperty("m_WorldUpObject"); - m_WorldUpType = serializedObject.FindProperty("m_UpType"); - - m_Weight = serializedObject.FindProperty("m_Weight"); - m_IsContraintActive = serializedObject.FindProperty("m_IsContraintActive"); - m_IsLocked = serializedObject.FindProperty("m_IsLocked"); - m_Sources = serializedObject.FindProperty("m_Sources"); - - OnEnable(s_Style); - } - - internal override void OnValueAtRestChanged() - { - foreach (var t in targets) - (t as AimConstraint).transform.SetLocalEulerAngles(atRest.vector3Value, RotationOrder.OrderZXY); - } - - internal override void ShowOffset(ConstraintStyleBase style) - { - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(offset, style.Offset); - if (EditorGUI.EndChangeCheck()) - { - foreach (var t in targets) - (t as T).UserUpdateOffset(); - } - } - - internal override void ShowCustomProperties() - { - EditorGUILayout.PropertyField(m_AimVector, s_Style.AimVector); - EditorGUILayout.PropertyField(m_UpVector, s_Style.UpVector); - EditorGUILayout.Popup(m_WorldUpType, s_Style.WorldUpTypes, s_Style.WorldUpType); - - var worldUpType = (AimConstraint.WorldUpType)m_WorldUpType.intValue; - using (new EditorGUI.DisabledGroupScope(worldUpType != AimConstraint.WorldUpType.ObjectRotationUp && worldUpType != AimConstraint.WorldUpType.Vector)) - { - EditorGUILayout.PropertyField(m_WorldUpVector, s_Style.WorldUpVector); - } - - using (new EditorGUI.DisabledGroupScope(worldUpType != AimConstraint.WorldUpType.ObjectUp && worldUpType != AimConstraint.WorldUpType.ObjectRotationUp)) - { - EditorGUILayout.PropertyField(m_WorldUpObject, s_Style.WorldUpObject); - } - } - - internal override void ShowFreezeAxesControl() - { - Rect drawRect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector3, s_Style.FreezeAxes), EditorStyles.toggle); - EditorGUI.MultiPropertyField(drawRect, s_Style.Axes, serializedObject.FindProperty("m_AffectRotationX"), s_Style.FreezeAxes); - } - - public override void OnInspectorGUI() - { - if (s_Style == null) - s_Style = new Styles(); - - serializedObject.Update(); - - ShowConstraintEditor(s_Style); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/AnchoredJoint2DEditor.cs b/Editor/Mono/Inspector/AnchoredJoint2DEditor.cs deleted file mode 100644 index c6cbed3e26..0000000000 --- a/Editor/Mono/Inspector/AnchoredJoint2DEditor.cs +++ /dev/null @@ -1,73 +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 -{ - [CustomEditor(typeof(AnchoredJoint2D), true)] - [CanEditMultipleObjects] - internal class AnchoredJoint2DEditor : Joint2DEditor - { - const float k_SnapDistance = 0.13f; - AnchoredJoint2D anchorJoint2D; - - public void OnSceneGUI() - { - anchorJoint2D = (AnchoredJoint2D)target; - - // Ignore disabled joint. - if (!anchorJoint2D.enabled) - return; - - Vector3 worldAnchor = TransformPoint(anchorJoint2D.transform, anchorJoint2D.anchor); - Vector3 worldConnectedAnchor = anchorJoint2D.connectedAnchor; - if (anchorJoint2D.connectedBody) - worldConnectedAnchor = TransformPoint(anchorJoint2D.connectedBody.transform, worldConnectedAnchor); - - // Draw line between anchors - Vector3 startPoint = worldAnchor + (worldConnectedAnchor - worldAnchor).normalized * HandleUtility.GetHandleSize(worldAnchor) * 0.1f; - Handles.color = Color.green; - Handles.DrawAAPolyLine(new Vector3[] { startPoint, worldConnectedAnchor }); - - // Connected anchor - if (HandleAnchor(ref worldConnectedAnchor, true)) - { - worldConnectedAnchor = SnapToSprites(worldConnectedAnchor); - worldConnectedAnchor = SnapToPoint(worldConnectedAnchor, worldAnchor, k_SnapDistance); - - if (anchorJoint2D.connectedBody) - worldConnectedAnchor = InverseTransformPoint(anchorJoint2D.connectedBody.transform, worldConnectedAnchor); - - Undo.RecordObject(anchorJoint2D, "Move Connected Anchor"); - anchorJoint2D.connectedAnchor = worldConnectedAnchor; - } - - // Anchor - if (HandleAnchor(ref worldAnchor, false)) - { - worldAnchor = SnapToSprites(worldAnchor); - worldAnchor = SnapToPoint(worldAnchor, worldConnectedAnchor, k_SnapDistance); - - Undo.RecordObject(anchorJoint2D, "Move Anchor"); - anchorJoint2D.anchor = InverseTransformPoint(anchorJoint2D.transform, worldAnchor); - } - } - - Vector3 SnapToSprites(Vector3 position) - { - SpriteRenderer spriteRenderer = anchorJoint2D.GetComponent(); - position = SnapToSprite(spriteRenderer, position, k_SnapDistance); - - if (anchorJoint2D.connectedBody) - { - spriteRenderer = anchorJoint2D.connectedBody.GetComponent(); - position = SnapToSprite(spriteRenderer, position, k_SnapDistance); - } - - return position; - } - } -} diff --git a/Editor/Mono/Inspector/AnimationClipEditor.cs b/Editor/Mono/Inspector/AnimationClipEditor.cs index 23fc6cffb2..93bbbb54b9 100644 --- a/Editor/Mono/Inspector/AnimationClipEditor.cs +++ b/Editor/Mono/Inspector/AnimationClipEditor.cs @@ -217,6 +217,7 @@ public bool needsToGenerateClipInfo const int kPosition = 3; Vector2[][][] m_QualityCurves = new Vector2[4][][]; bool m_DirtyQualityCurves = false; + bool m_FirstInitialization = true; private void InitController() { @@ -269,7 +270,12 @@ private void InitController() { m_AvatarPreview.Animator.Play(0, 0, 0); m_AvatarPreview.Animator.Update(0); - m_AvatarPreview.ResetPreviewFocus(); + + if (m_FirstInitialization) + { + m_AvatarPreview.ResetPreviewFocus(); + m_FirstInitialization = false; + } } } } diff --git a/Editor/Mono/Inspector/AnimationEditor.cs b/Editor/Mono/Inspector/AnimationEditor.cs deleted file mode 100644 index 6924db0d6e..0000000000 --- a/Editor/Mono/Inspector/AnimationEditor.cs +++ /dev/null @@ -1,61 +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.Collections; -using System.Collections.Generic; -using UnityEditorInternal; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(Animation))] - [CanEditMultipleObjects] - internal class AnimationEditor : Editor - { - private int m_PrePreviewAnimationArraySize = -1; - - public void OnEnable() - { - m_PrePreviewAnimationArraySize = -1; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - SerializedProperty clipProperty = serializedObject.FindProperty("m_Animation"); - - EditorGUILayout.PropertyField(clipProperty, true); - int newAnimID = clipProperty.objectReferenceInstanceIDValue; - - SerializedProperty arrProperty = serializedObject.FindProperty("m_Animations"); - int arrSize = arrProperty.arraySize; - - // Remember the array size when ObjectSelector becomes visible - if (ObjectSelector.isVisible && m_PrePreviewAnimationArraySize == -1) - m_PrePreviewAnimationArraySize = arrSize; - - // Make sure the array is the original array size + 1 at max (+1 for the ObjectSelector preview slot) - if (m_PrePreviewAnimationArraySize != -1) - { - // Always resize if the last anim element is not the current animation - int lastAnimID = arrSize > 0 ? arrProperty.GetArrayElementAtIndex(arrSize - 1).objectReferenceInstanceIDValue : -1; - if (lastAnimID != newAnimID) - arrProperty.arraySize = m_PrePreviewAnimationArraySize; - if (!ObjectSelector.isVisible) - m_PrePreviewAnimationArraySize = -1; - } - - DrawPropertiesExcluding(serializedObject, "m_Animation", "m_UserAABB"); - - serializedObject.ApplyModifiedProperties(); - } - - // A minimal list of settings to be shown in the Asset Store preview inspector - internal override void OnAssetStoreInspectorGUI() - { - OnInspectorGUI(); - } - } -} diff --git a/Editor/Mono/Inspector/AnimatorInspector.cs b/Editor/Mono/Inspector/AnimatorInspector.cs deleted file mode 100644 index 430ab6bab1..0000000000 --- a/Editor/Mono/Inspector/AnimatorInspector.cs +++ /dev/null @@ -1,154 +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 UnityEngine; -using UnityEditor; -using UnityEditorInternal; -using UnityEditor.AnimatedValues; - -namespace UnityEditor -{ - [CustomEditor(typeof(Animator))] - [CanEditMultipleObjects] - internal class AnimatorInspector : Editor - { - SerializedProperty m_Avatar; - SerializedProperty m_ApplyRootMotion; - SerializedProperty m_CullingMode; - SerializedProperty m_UpdateMode; - SerializedProperty m_WarningMessage; - - AnimBool m_ShowWarningMessage = new AnimBool(); - bool m_IsRootPositionOrRotationControlledByCurves; - - private bool IsWarningMessageEmpty { get { return m_WarningMessage != null && m_WarningMessage.stringValue.Length > 0; } } - private string WarningMessage { get { return m_WarningMessage != null ? m_WarningMessage.stringValue : ""; } } - - class Styles - { - public GUIContent applyRootMotion = new GUIContent(EditorGUIUtility.TrTextContent("Apply Root Motion")); - public GUIContent updateMode = new GUIContent(EditorGUIUtility.TrTextContent("Update Mode")); - public GUIContent cullingMode = new GUIContent(EditorGUIUtility.TrTextContent("Culling Mode")); - - public Styles() - { - applyRootMotion.tooltip = "Automatically move the object using the root motion from the animations"; - updateMode.tooltip = "Controls when and how often the Animator is updated"; - cullingMode.tooltip = "Controls what is updated when the object has been culled"; - } - } - static Styles styles; - - private void Init() - { - if (styles == null) - { - styles = new Styles(); - } - InitShowOptions(); - } - - private void InitShowOptions() - { - m_ShowWarningMessage.value = IsWarningMessageEmpty; - - m_ShowWarningMessage.valueChanged.AddListener(Repaint); - } - - private void UpdateShowOptions() - { - m_ShowWarningMessage.target = IsWarningMessageEmpty; - } - - void OnEnable() - { - m_Avatar = serializedObject.FindProperty("m_Avatar"); - m_ApplyRootMotion = serializedObject.FindProperty("m_ApplyRootMotion"); - m_CullingMode = serializedObject.FindProperty("m_CullingMode"); - m_UpdateMode = serializedObject.FindProperty("m_UpdateMode"); - m_WarningMessage = serializedObject.FindProperty("m_WarningMessage"); - - - Init(); - } - - public override void OnInspectorGUI() - { - bool isEditingMultipleObjects = targets.Length > 1; - - bool cullingModeChanged = false; - bool updateModeChanged = false; - - Animator firstAnimator = target as Animator; - - serializedObject.UpdateIfRequiredOrScript(); - - UpdateShowOptions(); - - EditorGUI.BeginChangeCheck(); - var controller = EditorGUILayout.ObjectField("Controller", firstAnimator.runtimeAnimatorController, typeof(RuntimeAnimatorController), false) as RuntimeAnimatorController; - if (EditorGUI.EndChangeCheck()) - { - foreach (Animator animator in targets) - { - Undo.RecordObject(animator, "Changed AnimatorController"); - animator.runtimeAnimatorController = controller; - } - AnimationWindowUtility.ControllerChanged(); - } - - EditorGUILayout.PropertyField(m_Avatar); - if (firstAnimator.supportsOnAnimatorMove && !isEditingMultipleObjects) - { - EditorGUILayout.LabelField("Apply Root Motion", "Handled by Script"); - } - else - { - EditorGUILayout.PropertyField(m_ApplyRootMotion, styles.applyRootMotion); - - // This might change between layout & repaint so we have local cached value to only update on layout - if (Event.current.type == EventType.Layout) - m_IsRootPositionOrRotationControlledByCurves = firstAnimator.isRootPositionOrRotationControlledByCurves; - - if (!m_ApplyRootMotion.boolValue && m_IsRootPositionOrRotationControlledByCurves) - { - EditorGUILayout.HelpBox("Root position or rotation are controlled by curves", MessageType.Info, true); - } - } - - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(m_UpdateMode, styles.updateMode); - updateModeChanged = EditorGUI.EndChangeCheck(); - - - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(m_CullingMode, styles.cullingMode); - cullingModeChanged = EditorGUI.EndChangeCheck(); - - - if (!isEditingMultipleObjects) - EditorGUILayout.HelpBox(firstAnimator.GetStats(), MessageType.Info, true); - - if (EditorGUILayout.BeginFadeGroup(m_ShowWarningMessage.faded)) - { - EditorGUILayout.HelpBox(WarningMessage, MessageType.Warning, true); - } - EditorGUILayout.EndFadeGroup(); - - - serializedObject.ApplyModifiedProperties(); - - foreach (Animator animator in targets) - { - if (cullingModeChanged) - animator.OnCullingModeChanged(); - - if (updateModeChanged) - animator.OnUpdateModeChanged(); - } - } - } -} diff --git a/Editor/Mono/Inspector/AnimatorOverrideControllerInspector.cs b/Editor/Mono/Inspector/AnimatorOverrideControllerInspector.cs deleted file mode 100644 index 47d131609f..0000000000 --- a/Editor/Mono/Inspector/AnimatorOverrideControllerInspector.cs +++ /dev/null @@ -1,213 +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 UnityEditor; -using UnityEditorInternal; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class AnimationClipOverrideComparer : IComparer> - { - public int Compare(KeyValuePair x, KeyValuePair y) - { - return string.Compare(x.Key.name, y.Key.name, System.StringComparison.OrdinalIgnoreCase); - } - } - - [CustomEditor(typeof(AnimatorOverrideController))] - [CanEditMultipleObjects] - internal class AnimatorOverrideControllerInspector : Editor - { - SerializedProperty m_Controller; - - private List> m_Clips; - - ReorderableList m_ClipList; - string m_Search; - - void OnEnable() - { - AnimatorOverrideController animatorOverrideController = target as AnimatorOverrideController; - - m_Controller = serializedObject.FindProperty("m_Controller"); - m_Search = ""; - - if (m_Clips == null) - m_Clips = new List>(); - - if (m_ClipList == null) - { - animatorOverrideController.GetOverrides(m_Clips); - - m_Clips.Sort(new AnimationClipOverrideComparer()); - - m_ClipList = new ReorderableList(m_Clips, typeof(KeyValuePair), false, true, false, false); - m_ClipList.drawElementCallback = DrawClipElement; - m_ClipList.drawHeaderCallback = DrawClipHeader; - m_ClipList.onSelectCallback = SelectClip; - m_ClipList.elementHeight = 16; - } - animatorOverrideController.OnOverrideControllerDirty += Repaint; - } - - void OnDisable() - { - AnimatorOverrideController animatorOverrideController = target as AnimatorOverrideController; - animatorOverrideController.OnOverrideControllerDirty -= Repaint; - } - - public override void OnInspectorGUI() - { - bool isEditingMultipleObjects = targets.Length > 1; - bool changeCheck = false; - - serializedObject.UpdateIfRequiredOrScript(); - - AnimatorOverrideController animatorOverrideController = target as AnimatorOverrideController; - RuntimeAnimatorController runtimeAnimatorController = m_Controller.hasMultipleDifferentValues ? null : animatorOverrideController.runtimeAnimatorController; - - EditorGUI.BeginChangeCheck(); - runtimeAnimatorController = EditorGUILayout.ObjectField("Controller", runtimeAnimatorController, typeof(Animations.AnimatorController), false) as RuntimeAnimatorController; - if (EditorGUI.EndChangeCheck()) - { - for (int i = 0; i < targets.Length; i++) - { - AnimatorOverrideController controller = targets[i] as AnimatorOverrideController; - controller.runtimeAnimatorController = runtimeAnimatorController; - } - - changeCheck = true; - } - - { - GUI.SetNextControlName("OverridesSearch"); - - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape && GUI.GetNameOfFocusedControl() == "OverridesSearch") - m_Search = ""; - - EditorGUI.BeginChangeCheck(); - string newSearch = EditorGUILayout.ToolbarSearchField(m_Search); - if (EditorGUI.EndChangeCheck()) - m_Search = newSearch; - } - - - using (new EditorGUI.DisabledScope(m_Controller == null || (isEditingMultipleObjects && m_Controller.hasMultipleDifferentValues) || runtimeAnimatorController == null)) - { - EditorGUI.BeginChangeCheck(); - animatorOverrideController.GetOverrides(m_Clips); - - if (m_Search.Length > 0) - FilterOverrides(); - else // If there is not filter simply sort all the list. - m_Clips.Sort(new AnimationClipOverrideComparer()); - - m_ClipList.list = m_Clips; - m_ClipList.DoLayoutList(); - if (EditorGUI.EndChangeCheck()) - { - for (int i = 0; i < targets.Length; i++) - { - AnimatorOverrideController controller = targets[i] as AnimatorOverrideController; - controller.ApplyOverrides(m_Clips); - } - changeCheck = true; - } - } - - if (changeCheck) - animatorOverrideController.PerformOverrideClipListCleanup(); - } - - private void FilterOverrides() - { - if (m_Search.Length == 0) - return; - - // Support multiple search words separated by spaces. - string[] searchWords = m_Search.ToLower().Split(' '); - - // We keep two lists. Matches that matches the start of an item always get first priority. - List> matchesStart = new List>(); - List> matchesWithin = new List>(); - foreach (KeyValuePair kvp in m_Clips) - { - string name = kvp.Key.name; - name = name.ToLower().Replace(" ", ""); - - bool didMatchAll = true; - bool didMatchStart = false; - - // See if we match ALL the search words. - for (int w = 0; w < searchWords.Length; w++) - { - string search = searchWords[w]; - if (name.Contains(search)) - { - // If the start of the item matches the first search word, make a note of that. - if (w == 0 && name.StartsWith(search)) - didMatchStart = true; - } - else - { - // As soon as any word is not matched, we disregard this item. - didMatchAll = false; - break; - } - } - // We always need to match all search words. - // If we ALSO matched the start, this item gets priority. - if (didMatchAll) - { - if (didMatchStart) - matchesStart.Add(kvp); - else - matchesWithin.Add(kvp); - } - } - - m_Clips.Clear(); - - matchesStart.Sort(new AnimationClipOverrideComparer()); - matchesWithin.Sort(new AnimationClipOverrideComparer()); - - // Add search results - m_Clips.AddRange(matchesStart); - m_Clips.AddRange(matchesWithin); - } - - private void DrawClipElement(Rect rect, int index, bool selected, bool focused) - { - AnimationClip originalClip = m_Clips[index].Key; - AnimationClip overrideClip = m_Clips[index].Value; - - rect.xMax = rect.xMax / 2.0f; - GUI.Label(rect, originalClip.name, EditorStyles.label); - rect.xMin = rect.xMax; - rect.xMax *= 2.0f; - - EditorGUI.BeginChangeCheck(); - overrideClip = EditorGUI.ObjectField(rect, "", overrideClip, typeof(AnimationClip), false) as AnimationClip; - if (EditorGUI.EndChangeCheck()) - m_Clips[index] = new KeyValuePair(originalClip, overrideClip); - } - - private void DrawClipHeader(Rect rect) - { - rect.xMax = rect.xMax / 2.0f; - GUI.Label(rect, "Original", EditorStyles.label); - rect.xMin = rect.xMax; - rect.xMax *= 2.0f; - GUI.Label(rect, "Override", EditorStyles.label); - } - - private void SelectClip(ReorderableList list) - { - if (0 <= list.index && list.index < m_Clips.Count) - EditorGUIUtility.PingObject(m_Clips[list.index].Key); - } - } -} diff --git a/Editor/Mono/Inspector/AreaEffector2DEditor.cs b/Editor/Mono/Inspector/AreaEffector2DEditor.cs deleted file mode 100644 index e202549f66..0000000000 --- a/Editor/Mono/Inspector/AreaEffector2DEditor.cs +++ /dev/null @@ -1,86 +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.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor.AnimatedValues; - -namespace UnityEditor -{ - /// - /// Prompts the end-user to add 2D colliders if non exist for 2D effector to work with. - /// - [CustomEditor(typeof(AreaEffector2D), true)] - [CanEditMultipleObjects] - internal class AreaEffector2DEditor : Effector2DEditor - { - readonly AnimBool m_ShowForceRollout = new AnimBool(); - SerializedProperty m_UseGlobalAngle; - SerializedProperty m_ForceAngle; - SerializedProperty m_ForceMagnitude; - SerializedProperty m_ForceVariation; - SerializedProperty m_ForceTarget; - - static readonly AnimBool m_ShowDampingRollout = new AnimBool(); - SerializedProperty m_Drag; - SerializedProperty m_AngularDrag; - - public override void OnEnable() - { - base.OnEnable(); - - m_ShowForceRollout.value = true; - m_ShowForceRollout.valueChanged.AddListener(Repaint); - m_UseGlobalAngle = serializedObject.FindProperty("m_UseGlobalAngle"); - m_ForceAngle = serializedObject.FindProperty("m_ForceAngle"); - m_ForceMagnitude = serializedObject.FindProperty("m_ForceMagnitude"); - m_ForceVariation = serializedObject.FindProperty("m_ForceVariation"); - m_ForceTarget = serializedObject.FindProperty("m_ForceTarget"); - - m_ShowDampingRollout.valueChanged.AddListener(Repaint); - m_Drag = serializedObject.FindProperty("m_Drag"); - m_AngularDrag = serializedObject.FindProperty("m_AngularDrag"); - } - - public override void OnDisable() - { - base.OnDisable(); - - m_ShowForceRollout.valueChanged.RemoveListener(Repaint); - m_ShowDampingRollout.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - serializedObject.Update(); - - // Force. - m_ShowForceRollout.target = EditorGUILayout.Foldout(m_ShowForceRollout.target, "Force", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowForceRollout.faded)) - { - EditorGUILayout.PropertyField(m_UseGlobalAngle); - EditorGUILayout.PropertyField(m_ForceAngle); - EditorGUILayout.PropertyField(m_ForceMagnitude); - EditorGUILayout.PropertyField(m_ForceVariation); - EditorGUILayout.PropertyField(m_ForceTarget); - EditorGUILayout.Space(); - } - EditorGUILayout.EndFadeGroup(); - - // Drag. - m_ShowDampingRollout.target = EditorGUILayout.Foldout(m_ShowDampingRollout.target, "Damping", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowDampingRollout.faded)) - { - EditorGUILayout.PropertyField(m_Drag); - EditorGUILayout.PropertyField(m_AngularDrag); - } - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/AssetBundleNameGUI.cs b/Editor/Mono/Inspector/AssetBundleNameGUI.cs deleted file mode 100644 index 783ad05505..0000000000 --- a/Editor/Mono/Inspector/AssetBundleNameGUI.cs +++ /dev/null @@ -1,225 +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 UnityEditor; -using System.Collections; -using System.Collections.Generic; -using System.Reflection; -using System.Text.RegularExpressions; -using System.Linq; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class AssetBundleNameGUI - { - static private readonly GUIContent kAssetBundleName = EditorGUIUtility.TrTextContent("AssetBundle"); - static private readonly int kAssetBundleNameFieldIdHash = "AssetBundleNameFieldHash".GetHashCode(); - - static private readonly int kAssetBundleVariantFieldIdHash = "AssetBundleVariantFieldHash".GetHashCode(); - - private class Styles - { - private static GUISkin s_DarkSkin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene); - - public static GUIStyle label = GetStyle("ControlLabel"); - public static GUIStyle popup = GetStyle("MiniPopup"); - public static GUIStyle textField = GetStyle("textField"); - - public static Color cursorColor = s_DarkSkin.settings.cursorColor; - - private static GUIStyle GetStyle(string name) - { - return new GUIStyle(s_DarkSkin.GetStyle(name)); - } - } - - private bool m_ShowAssetBundleNameTextField = false; - private bool m_ShowAssetBundleVariantTextField = false; - - public void OnAssetBundleNameGUI(IEnumerable assets) - { - EditorGUIUtility.labelWidth = 90f; - - Rect bundleRect = EditorGUILayout.GetControlRect(true, EditorGUI.kSingleLineHeight); - Rect variantRect = bundleRect; - - bundleRect.width *= 0.8f; - variantRect.xMin += bundleRect.width + EditorGUI.kSpacing; - - - int id = GUIUtility.GetControlID(kAssetBundleNameFieldIdHash, FocusType.Passive, bundleRect); - - bundleRect = EditorGUI.PrefixLabel(bundleRect, id, kAssetBundleName, Styles.label); - if (m_ShowAssetBundleNameTextField) - AssetBundleTextField(bundleRect, id, assets, false); - else - AssetBundlePopup(bundleRect, id, assets, false); - - id = GUIUtility.GetControlID(kAssetBundleVariantFieldIdHash, FocusType.Passive, variantRect); - - if (m_ShowAssetBundleVariantTextField) - AssetBundleTextField(variantRect, id, assets, true); - else - AssetBundlePopup(variantRect, id, assets, true); - } - - private void ShowNewAssetBundleField(bool isVariant) - { - m_ShowAssetBundleNameTextField = !isVariant; - m_ShowAssetBundleVariantTextField = isVariant; - - EditorGUIUtility.editingTextField = true; - } - - private void AssetBundleTextField(Rect rect, int id, IEnumerable assets, bool isVariant) - { - // CursorColor is stored at the GUISkin level, but the styles we are using don't necessarily match the GUI.skin. - // TextField assumes that the style matches the current GUI.skin, this is wrong and should be fixed. We'll workaround for now. - Color oldCursorColor = GUI.skin.settings.cursorColor; - GUI.skin.settings.cursorColor = Styles.cursorColor; - - EditorGUI.BeginChangeCheck(); - string temp = EditorGUI.DelayedTextFieldInternal(rect, id, GUIContent.none, "", null, Styles.textField); - if (EditorGUI.EndChangeCheck()) - { - SetAssetBundleForAssets(assets, temp, isVariant); - ShowAssetBundlePopup(); - } - - GUI.skin.settings.cursorColor = oldCursorColor; - - // editing was cancelled - if (EditorGUI.IsEditingTextField() == false && Event.current.type != EventType.Layout) - ShowAssetBundlePopup(); - } - - private void ShowAssetBundlePopup() - { - m_ShowAssetBundleNameTextField = false; - m_ShowAssetBundleVariantTextField = false; - } - - private void AssetBundlePopup(Rect rect, int id, IEnumerable assets, bool isVariant) - { - List displayedOptions = new List(); - displayedOptions.Add("None"); - displayedOptions.Add(""); // seperator - - // Anyway to optimize this by caching GetAssetBundleNameFromAssets() and GetAllAssetBundleNames() when they actually change? - // As we can change the assetBundle name by script, the UI needs to detect this kind of change. - bool mixedValue; - IEnumerable assetBundleFromAssets = GetAssetBundlesFromAssets(assets, isVariant, out mixedValue); - - string[] assetBundles = isVariant ? AssetDatabase.GetAllAssetBundleVariants() : AssetDatabase.GetAllAssetBundleNamesWithoutVariant(); - displayedOptions.AddRange(assetBundles); - - displayedOptions.Add(""); // seperator - int newAssetBundleIndex = displayedOptions.Count; - displayedOptions.Add("New..."); - - // These two options are invalid for variant, so skip them for variant. - int removeUnusedIndex = -1; - int filterSelectedIndex = -1; - if (!isVariant) - { - removeUnusedIndex = displayedOptions.Count; - displayedOptions.Add("Remove Unused Names"); - filterSelectedIndex = displayedOptions.Count; - if (assetBundleFromAssets.Count() != 0) - displayedOptions.Add("Filter Selected Name" + (mixedValue ? "s" : "")); - } - - int selectedIndex = 0; - string firstAssetBundle = assetBundleFromAssets.FirstOrDefault(); - if (!String.IsNullOrEmpty(firstAssetBundle)) - selectedIndex = displayedOptions.IndexOf(firstAssetBundle); - - EditorGUI.BeginChangeCheck(); - EditorGUI.showMixedValue = mixedValue; - selectedIndex = EditorGUI.DoPopup(rect, id, selectedIndex, EditorGUIUtility.TempContent(displayedOptions.ToArray()), Styles.popup); - EditorGUI.showMixedValue = false; - if (EditorGUI.EndChangeCheck()) - { - if (selectedIndex == 0) // None - SetAssetBundleForAssets(assets, null, isVariant); - else if (selectedIndex == newAssetBundleIndex) // New... - ShowNewAssetBundleField(isVariant); - else if (selectedIndex == removeUnusedIndex) // Remove Unused Names - AssetDatabase.RemoveUnusedAssetBundleNames(); - else if (selectedIndex == filterSelectedIndex) // Filter Selected Name(s) - FilterSelected(assetBundleFromAssets); - else - SetAssetBundleForAssets(assets, displayedOptions[selectedIndex], isVariant); - } - } - - private void FilterSelected(IEnumerable assetBundleNames) - { - var searchFilter = new SearchFilter(); - searchFilter.assetBundleNames = assetBundleNames.Where(name => !String.IsNullOrEmpty(name)).ToArray(); - - if (ProjectBrowser.s_LastInteractedProjectBrowser != null) - ProjectBrowser.s_LastInteractedProjectBrowser.SetSearch(searchFilter); - else - Debug.LogWarning("No Project Browser found to apply AssetBundle filter."); - } - - private IEnumerable GetAssetBundlesFromAssets(IEnumerable assets, bool isVariant, out bool isMixed) - { - var assetBundles = new HashSet(); - string lastAssetBundle = null; - isMixed = false; - - foreach (Object obj in assets) - { - if (obj is MonoScript) - continue; - - AssetImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(obj)); - if (importer == null) - continue; - - string currentAssetBundle = isVariant ? importer.assetBundleVariant : importer.assetBundleName; - - if (lastAssetBundle != null && lastAssetBundle != currentAssetBundle) - isMixed = true; - lastAssetBundle = currentAssetBundle; - - if (!String.IsNullOrEmpty(currentAssetBundle)) - assetBundles.Add(currentAssetBundle); - } - - return assetBundles; - } - - private void SetAssetBundleForAssets(IEnumerable assets, string name, bool isVariant) - { - bool assetBundleNameChanged = false; - foreach (Object obj in assets) - { - if (obj is MonoScript) - continue; - - AssetImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(obj)); - if (importer == null) - continue; - - if (isVariant) - importer.assetBundleVariant = name; - else - importer.assetBundleName = name; - - assetBundleNameChanged = true; - } - - if (assetBundleNameChanged) - { - EditorApplication.Internal_CallAssetBundleNameChanged(); - } - } - } -} diff --git a/Editor/Mono/Inspector/AudioChorusFilterEditor.cs b/Editor/Mono/Inspector/AudioChorusFilterEditor.cs deleted file mode 100644 index b43e4085df..0000000000 --- a/Editor/Mono/Inspector/AudioChorusFilterEditor.cs +++ /dev/null @@ -1,14 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioChorusFilter))] - class AudioChorusFilterEditor : Editor - { - } -} diff --git a/Editor/Mono/Inspector/AudioClipInspector.cs b/Editor/Mono/Inspector/AudioClipInspector.cs index 1ac6c24213..d4304d9698 100644 --- a/Editor/Mono/Inspector/AudioClipInspector.cs +++ b/Editor/Mono/Inspector/AudioClipInspector.cs @@ -120,29 +120,26 @@ public override void OnPreviewSettings() AudioClip clip = target as AudioClip; + bool isEditingMultipleObjects = targets.Length > 1; + using (new EditorGUI.DisabledScope(AudioUtil.IsMovieAudio(clip))) { - bool isEditingMultipleObjects = targets.Length > 1; - - using (new EditorGUI.DisabledScope(isEditingMultipleObjects)) + bool oldAutoPlay = m_bAutoPlay; + bool newAutoPlay = PreviewGUI.CycleButton(oldAutoPlay ? 1 : 0, s_AutoPlayIcons) != 0; + if (oldAutoPlay != newAutoPlay) { - bool oldAutoPlay = isEditingMultipleObjects ? false : m_bAutoPlay; - bool newAutoPlay = PreviewGUI.CycleButton(oldAutoPlay ? 1 : 0, s_AutoPlayIcons) != 0; - if (oldAutoPlay != newAutoPlay) - { - m_bAutoPlay = newAutoPlay; - InspectorWindow.RepaintAllInspectors(); - } + m_bAutoPlay = newAutoPlay; + InspectorWindow.RepaintAllInspectors(); + } - bool oldLoop = isEditingMultipleObjects ? false : m_bLoop; - bool newLoop = PreviewGUI.CycleButton(oldLoop ? 1 : 0, s_LoopIcons) != 0; - if (oldLoop != newLoop) - { - m_bLoop = newLoop; - if (playing) - AudioUtil.LoopClip(clip, newLoop); - InspectorWindow.RepaintAllInspectors(); - } + bool oldLoop = m_bLoop; + bool newLoop = PreviewGUI.CycleButton(oldLoop ? 1 : 0, s_LoopIcons) != 0; + if (oldLoop != newLoop) + { + m_bLoop = newLoop; + if (playing) + AudioUtil.LoopClip(clip, newLoop); + InspectorWindow.RepaintAllInspectors(); } using (new EditorGUI.DisabledScope(isEditingMultipleObjects && !playing && m_PlayingInspector != this)) @@ -153,8 +150,10 @@ public override void OnPreviewSettings() if (newPlaying != curPlaying) { AudioUtil.StopAllClips(); + m_PlayingClip = null; + m_PlayingInspector = null; - if (newPlaying) + if (newPlaying && !isEditingMultipleObjects) { AudioUtil.PlayClip(clip, 0, m_bLoop); m_PlayingClip = clip; @@ -163,6 +162,21 @@ public override void OnPreviewSettings() } } } + + // autoplay start? + if (m_bAutoPlay && m_PlayingClip != clip && m_PlayingInspector == this && !isEditingMultipleObjects) + { + AudioUtil.StopAllClips(); + m_PlayingClip = null; + m_PlayingInspector = null; + + if (!isEditingMultipleObjects) + { + AudioUtil.PlayClip(clip, 0, m_bLoop); + m_PlayingClip = clip; + m_PlayingInspector = this; + } + } } // Passing in clip and importer separately as we're not completely done with the asset setup at the time we're asked to generate the preview. @@ -314,16 +328,6 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) PreviewGUI.EndScrollView(); } - - // autoplay start? - if (m_bAutoPlay && m_PlayingClip != clip && m_PlayingInspector == this) - { - AudioUtil.StopAllClips(); - AudioUtil.PlayClip(clip, 0, m_bLoop); - m_PlayingClip = clip; - m_PlayingInspector = this; - } - // force update GUI if (playing) GUIView.current.Repaint(); diff --git a/Editor/Mono/Inspector/AudioDistortionFilterInspector.cs b/Editor/Mono/Inspector/AudioDistortionFilterInspector.cs deleted file mode 100644 index f3e0153897..0000000000 --- a/Editor/Mono/Inspector/AudioDistortionFilterInspector.cs +++ /dev/null @@ -1,14 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioDistortionFilter))] - class AudioDistortionFilterEditor : Editor - { - } -} diff --git a/Editor/Mono/Inspector/AudioEchoFilterInspector.cs b/Editor/Mono/Inspector/AudioEchoFilterInspector.cs deleted file mode 100644 index 0d4bde1e24..0000000000 --- a/Editor/Mono/Inspector/AudioEchoFilterInspector.cs +++ /dev/null @@ -1,14 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioEchoFilter))] - class AudioEchoFilterEditor : Editor - { - } -} diff --git a/Editor/Mono/Inspector/AudioExtensionEditor.cs b/Editor/Mono/Inspector/AudioExtensionEditor.cs deleted file mode 100644 index b64191f52e..0000000000 --- a/Editor/Mono/Inspector/AudioExtensionEditor.cs +++ /dev/null @@ -1,130 +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 System; -using System.Collections.Generic; -using System.Linq; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class AudioExtensionEditor : ScriptableObject - { - private bool foundAllExtensionProperties = false; - - public struct ExtensionPropertyInfo - { - public ExtensionPropertyInfo(string nameIn, float defaultValueIn) - { - propertyName = new PropertyName(nameIn); - defaultValue = defaultValueIn; - serializedProperty = null; - } - - public PropertyName propertyName; - public float defaultValue; - public SerializedProperty serializedProperty; - } -#pragma warning disable 649 - protected ExtensionPropertyInfo[] m_ExtensionProperties; - - public virtual void InitExtensionPropertyInfo() {} - protected virtual int GetNumSerializedExtensionProperties(Object obj) { return 0; } - - public void OnEnable() - { - InitExtensionPropertyInfo(); - } - - public int GetNumExtensionProperties() - { - return m_ExtensionProperties.Length; - } - - public PropertyName GetExtensionPropertyName(int index) - { - return m_ExtensionProperties[index].propertyName; - } - - public float GetExtensionPropertyDefaultValue(int index) - { - return m_ExtensionProperties[index].defaultValue; - } - - public bool FindAudioExtensionProperties(SerializedObject serializedObject) - { - SerializedProperty extensionPropertyValues = null; - - if (serializedObject != null) - extensionPropertyValues = serializedObject.FindProperty("m_ExtensionPropertyValues"); - - if (extensionPropertyValues == null) - { - foundAllExtensionProperties = false; - return false; - } - - int minNumSerializedExtensionProperties = extensionPropertyValues.arraySize; - if (extensionPropertyValues.hasMultipleDifferentValues) - minNumSerializedExtensionProperties = GetMinNumSerializedExtensionProperties(serializedObject); - - if ((extensionPropertyValues == null) || (minNumSerializedExtensionProperties == 0)) - { - foundAllExtensionProperties = false; - return false; - } - - if (!foundAllExtensionProperties && (serializedObject != null)) - { - int numPropertiesFound = 0; - for (int sourceIndex = 0; sourceIndex < minNumSerializedExtensionProperties; sourceIndex++) - { - SerializedProperty extensionPropertyValue = extensionPropertyValues.GetArrayElementAtIndex(sourceIndex); - - if (extensionPropertyValue == null) - continue; - - SerializedProperty propertyName = extensionPropertyValue.FindPropertyRelative("propertyName"); - for (int extensionIndex = 0; extensionIndex < m_ExtensionProperties.Length; extensionIndex++) - { - if ((m_ExtensionProperties[extensionIndex].propertyName == propertyName.stringValue) && !propertyName.hasMultipleDifferentValues) - { - m_ExtensionProperties[extensionIndex].serializedProperty = extensionPropertyValue.FindPropertyRelative("propertyValue"); - numPropertiesFound++; - } - } - } - - foundAllExtensionProperties = (numPropertiesFound == m_ExtensionProperties.Length) ? true : false; - } - - return foundAllExtensionProperties; - } - - protected static void PropertyFieldAsBool(SerializedProperty property, GUIContent title) - { - Rect rect = EditorGUILayout.GetControlRect(); - title = EditorGUI.BeginProperty(rect, title, property); - EditorGUI.BeginChangeCheck(); - bool newValue = EditorGUI.Toggle(rect, title, property.floatValue > 0.0f ? true : false); - if (EditorGUI.EndChangeCheck()) - { - property.floatValue = newValue ? 1.0f : 0.0f; - } - EditorGUI.EndProperty(); - } - - private int GetMinNumSerializedExtensionProperties(SerializedObject serializedObject) - { - Object[] targets = serializedObject.targetObjects; - int minNumSerializedExtensionProperties = (targets.Length > 0) ? int.MaxValue : 0; - - for (int i = 0; i < targets.Length; i++) - minNumSerializedExtensionProperties = Math.Min(minNumSerializedExtensionProperties, GetNumSerializedExtensionProperties(targets[i])); - - return minNumSerializedExtensionProperties; - } - } -} diff --git a/Editor/Mono/Inspector/AudioFilterGUI.cs b/Editor/Mono/Inspector/AudioFilterGUI.cs deleted file mode 100644 index 1a07d13b84..0000000000 --- a/Editor/Mono/Inspector/AudioFilterGUI.cs +++ /dev/null @@ -1,50 +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 -{ - internal class AudioFilterGUI - { - private EditorGUI.VUMeter.SmoothingData[] dataOut; - - public void DrawAudioFilterGUI(MonoBehaviour behaviour) - { - int channelCount = AudioUtil.GetCustomFilterChannelCount(behaviour); - - if (channelCount > 0) - { - if (dataOut == null) - { - dataOut = new EditorGUI.VUMeter.SmoothingData[channelCount]; - } - - double ms = (double)AudioUtil.GetCustomFilterProcessTime(behaviour) / 1000000.0; // ms - float limit = (float)ms / ((float)AudioSettings.outputSampleRate / 1024.0f / (float)channelCount); - - GUILayout.BeginHorizontal(); - GUILayout.Space(13); - GUILayout.BeginVertical(); - EditorGUILayout.Space(); - for (int c = 0; c < channelCount; ++c) - { - EditorGUILayout.VUMeterHorizontal(AudioUtil.GetCustomFilterMaxOut(behaviour, c), ref dataOut[c], GUILayout.MinWidth(50), GUILayout.Height(5)); - } - GUILayout.EndVertical(); - Color old = GUI.color; - GUI.color = new Color(limit, 1.0f - limit, 0.0f, 1.0f); - GUILayout.Box(string.Format("{0:00.00}ms", ms), GUILayout.MinWidth(40), GUILayout.Height(20)); - GUI.color = old; - - GUILayout.EndHorizontal(); - EditorGUILayout.Space(); - - // force repaint - GUIView.current.Repaint(); - } - } - } -} diff --git a/Editor/Mono/Inspector/AudioHighPassFIlterInspector.cs b/Editor/Mono/Inspector/AudioHighPassFIlterInspector.cs deleted file mode 100644 index abd6afede8..0000000000 --- a/Editor/Mono/Inspector/AudioHighPassFIlterInspector.cs +++ /dev/null @@ -1,14 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioHighPassFilter))] - class AudioHighPassFilterEditor : Editor - { - } -} diff --git a/Editor/Mono/Inspector/AudioListenerExtensionEditor.cs b/Editor/Mono/Inspector/AudioListenerExtensionEditor.cs deleted file mode 100644 index bba46d1ae1..0000000000 --- a/Editor/Mono/Inspector/AudioListenerExtensionEditor.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 UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class AudioListenerExtensionEditor : AudioExtensionEditor - { - public virtual void OnAudioListenerGUI() {} - - protected override int GetNumSerializedExtensionProperties(Object obj) - { - AudioListener listener = obj as AudioListener; - int numSerializedExtensionProperties = listener ? listener.GetNumExtensionProperties() : 0; - - return numSerializedExtensionProperties; - } - } -} diff --git a/Editor/Mono/Inspector/AudioListenerInspector.cs b/Editor/Mono/Inspector/AudioListenerInspector.cs deleted file mode 100644 index afa101e99b..0000000000 --- a/Editor/Mono/Inspector/AudioListenerInspector.cs +++ /dev/null @@ -1,206 +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 System.Collections.Generic; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioListener))] - [CanEditMultipleObjects] - class AudioListenerInspector : Editor - { - private AudioListenerExtensionEditor m_SpatializerEditor = null; - private bool m_AddSpatializerExtension = false; - private bool m_AddSpatializerExtensionMixedValues = false; - - private GUIContent addSpatializerExtensionLabel = EditorGUIUtility.TrTextContent("Override Spatializer Settings", "Override the Google spatializer's default settings."); - - void OnEnable() - { - Undo.undoRedoPerformed += UndoRedoPerformed; - - UpdateSpatializerExtensionMixedValues(); - if (m_AddSpatializerExtension) - CreateExtensionEditors(); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - bool allowExtensionEditing = (m_AddSpatializerExtension && !m_AddSpatializerExtensionMixedValues) || !serializedObject.isEditingMultipleObjects; - if (AudioExtensionManager.IsListenerSpatializerExtensionRegistered() && allowExtensionEditing) - { - EditorGUI.showMixedValue = m_AddSpatializerExtensionMixedValues; - bool addSpatializerExtensionNew = EditorGUILayout.Toggle(addSpatializerExtensionLabel, m_AddSpatializerExtension); - EditorGUI.showMixedValue = false; - - bool showExtensionProperties = false; - if (m_AddSpatializerExtension != addSpatializerExtensionNew) - { - m_AddSpatializerExtension = addSpatializerExtensionNew; - if (m_AddSpatializerExtension) - { - CreateExtensionEditors(); - - if (m_SpatializerEditor != null) - showExtensionProperties = m_SpatializerEditor.FindAudioExtensionProperties(serializedObject); - } - else - { - ClearExtensionProperties(); - DestroyExtensionEditors(); - showExtensionProperties = false; - } - } - else if (m_SpatializerEditor != null) - { - showExtensionProperties = m_SpatializerEditor.FindAudioExtensionProperties(serializedObject); - if (!showExtensionProperties) - { - m_AddSpatializerExtension = false; - ClearExtensionProperties(); - DestroyExtensionEditors(); - } - } - - if ((m_SpatializerEditor != null) && showExtensionProperties) - { - EditorGUI.indentLevel++; - m_SpatializerEditor.OnAudioListenerGUI(); - EditorGUI.indentLevel--; - - // Update AudioSourceExtension properties, if we are currently playing in Editor. - for (int i = 0; i < targets.Length; i++) - { - AudioListener listener = targets[i] as AudioListener; - if (listener != null) - { - AudioListenerExtension extension = AudioExtensionManager.GetSpatializerExtension(listener); - if (extension != null) - { - string extensionName = AudioExtensionManager.GetListenerSpatializerExtensionType().Name; - for (int j = 0; j < m_SpatializerEditor.GetNumExtensionProperties(); j++) - { - PropertyName propertyName = m_SpatializerEditor.GetExtensionPropertyName(j); - float value = 0.0f; - if (listener.ReadExtensionProperty(extensionName, propertyName, ref value)) - { - extension.WriteExtensionProperty(propertyName, value); - } - } - } - } - } - } - } - - serializedObject.ApplyModifiedProperties(); - } - - void OnDisable() - { - DestroyExtensionEditors(); - - Undo.undoRedoPerformed -= UndoRedoPerformed; - } - - private void UpdateSpatializerExtensionMixedValues() - { - m_AddSpatializerExtension = false; - - int numTargetsWithSpatializerExtensions = 0; - for (int i = 0; i < targets.Length; i++) - { - AudioListener listener = targets[i] as AudioListener; - if (listener != null) - { - System.Type spatializerExtensionType = AudioExtensionManager.GetListenerSpatializerExtensionType(); - if ((spatializerExtensionType != null) && (listener.GetNumExtensionPropertiesForThisExtension(spatializerExtensionType.Name) > 0)) - { - m_AddSpatializerExtension = true; - numTargetsWithSpatializerExtensions++; - } - } - } - - m_AddSpatializerExtensionMixedValues = ((numTargetsWithSpatializerExtensions == 0) || (numTargetsWithSpatializerExtensions == targets.Length)) ? false : true; - if (m_AddSpatializerExtensionMixedValues) - m_AddSpatializerExtension = false; - } - - // Created editors for all the enabled extensions of this AudioSource. - private void CreateExtensionEditors() - { - if (m_SpatializerEditor != null) - DestroyExtensionEditors(); - - System.Type spatializerEditorType = AudioExtensionManager.GetListenerSpatializerExtensionEditorType(); - m_SpatializerEditor = ScriptableObject.CreateInstance(spatializerEditorType) as AudioListenerExtensionEditor; - - if (m_SpatializerEditor != null) - { - for (int i = 0; i < targets.Length; i++) - { - AudioListener listener = targets[i] as AudioListener; - if (listener != null) - { - Undo.RecordObject(listener, "Add AudioListener extension properties"); - PropertyName extensionName = AudioExtensionManager.GetListenerSpatializerExtensionName(); - for (int j = 0; j < m_SpatializerEditor.GetNumExtensionProperties(); j++) - { - PropertyName propertyName = m_SpatializerEditor.GetExtensionPropertyName(j); - float value = 0.0f; - - // If the AudioListener is missing an extension property, then create it now. - if (!listener.ReadExtensionProperty(extensionName, propertyName, ref value)) - { - value = m_SpatializerEditor.GetExtensionPropertyDefaultValue(j); - listener.WriteExtensionProperty(AudioExtensionManager.GetSpatializerName(), extensionName, propertyName, value); - } - } - } - } - } - - m_AddSpatializerExtensionMixedValues = false; - } - - private void DestroyExtensionEditors() - { - DestroyImmediate(m_SpatializerEditor); - m_SpatializerEditor = null; - } - - private void ClearExtensionProperties() - { - for (int i = 0; i < targets.Length; i++) - { - AudioListener listener = targets[i] as AudioListener; - if (listener != null) - { - Undo.RecordObject(listener, "Remove AudioListener extension properties"); - listener.ClearExtensionProperties(AudioExtensionManager.GetListenerSpatializerExtensionName()); - } - } - - m_AddSpatializerExtensionMixedValues = false; - } - - private void UndoRedoPerformed() - { - DestroyExtensionEditors(); - - UpdateSpatializerExtensionMixedValues(); - if (!m_AddSpatializerExtension && !m_AddSpatializerExtensionMixedValues) - ClearExtensionProperties(); - - if (m_AddSpatializerExtension) - CreateExtensionEditors(); - - Repaint(); - } - } -} diff --git a/Editor/Mono/Inspector/AudioLowPassFilterInspector.cs b/Editor/Mono/Inspector/AudioLowPassFilterInspector.cs deleted file mode 100644 index d480a47052..0000000000 --- a/Editor/Mono/Inspector/AudioLowPassFilterInspector.cs +++ /dev/null @@ -1,37 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioLowPassFilter))] - [CanEditMultipleObjects] - internal class AudioLowPassFilterInspector : Editor - { - SerializedProperty m_LowpassResonanceQ; - SerializedProperty m_LowpassLevelCustomCurve; - - void OnEnable() - { - m_LowpassResonanceQ = serializedObject.FindProperty("m_LowpassResonanceQ"); - m_LowpassLevelCustomCurve = serializedObject.FindProperty("lowpassLevelCustomCurve"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - AudioSourceInspector.AnimProp( - EditorGUIUtility.TrTextContent("Cutoff Frequency"), - m_LowpassLevelCustomCurve, - 0.0f, AudioSourceInspector.kMaxCutoffFrequency, true); - - EditorGUILayout.PropertyField(m_LowpassResonanceQ); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/AudioMixerControllerInspector.cs b/Editor/Mono/Inspector/AudioMixerControllerInspector.cs deleted file mode 100644 index e2bc685854..0000000000 --- a/Editor/Mono/Inspector/AudioMixerControllerInspector.cs +++ /dev/null @@ -1,65 +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 UnityEditor.Audio; -using UnityEngine.Audio; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioMixerController))] - [CanEditMultipleObjects] - internal class AudioMixerControllerInspector : Editor - { - static class Texts - { - public static GUIContent m_EnableSuspendLabel = EditorGUIUtility.TrTextContent("Auto Mixer Suspend", "Enables/disables suspending of processing in order to save CPU when the RMS signal level falls under the defined threshold (in dB). Mixers resume processing when an AudioSource referencing them starts playing again."); - public static GUIContent m_SuspendThresholdLabel = EditorGUIUtility.TrTextContent(" Threshold Volume", "The level of the Master Group at which the mixer suspends processing in order to save CPU. Mixers resume processing when an AudioSource referencing them starts playing again."); - public static GUIContent m_UpdateModeLabel = EditorGUIUtility.TrTextContent("Update Mode", "Update AudioMixer transitions with game time or unscaled realtime."); - public static string dB = "dB"; - } - - SerializedProperty m_EnableSuspend; - SerializedProperty m_SuspendThreshold; - SerializedProperty m_UpdateMode; - - public void OnEnable() - { - m_SuspendThreshold = serializedObject.FindProperty("m_SuspendThreshold"); - m_EnableSuspend = serializedObject.FindProperty("m_EnableSuspend"); - m_UpdateMode = serializedObject.FindProperty("m_UpdateMode"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - EditorGUILayout.PropertyField(m_EnableSuspend, Texts.m_EnableSuspendLabel); - using (new EditorGUI.DisabledScope(!m_EnableSuspend.boolValue || m_EnableSuspend.hasMultipleDifferentValues)) - { - EditorGUI.BeginChangeCheck(); - EditorGUI.s_UnitString = Texts.dB; - float displayValue = m_SuspendThreshold.floatValue; - displayValue = EditorGUILayout.PowerSlider(Texts.m_SuspendThresholdLabel, displayValue, AudioMixerController.kMinVolume, AudioMixerController.GetMaxVolume(), 1.0f); - EditorGUI.s_UnitString = null; - if (EditorGUI.EndChangeCheck()) - m_SuspendThreshold.floatValue = displayValue; - } - EditorGUILayout.PropertyField(m_UpdateMode, Texts.m_UpdateModeLabel); - serializedObject.ApplyModifiedProperties(); - } - } - - // Here we need an inspector for runtime objects that are loaded in the editor (via asset bundles) - // We need to inform the user that such objects are not editable in the editor. - [CustomEditor(typeof(AudioMixer))] - [CanEditMultipleObjects] - internal class AudioMixerInspector : Editor - { - public override void OnInspectorGUI() - { - GUILayout.Space(10); - EditorGUILayout.HelpBox("Modification and inspection of built AudioMixer assets is disabled. Please modify the source asset and re-build.", MessageType.Info); - } - } -} diff --git a/Editor/Mono/Inspector/AudioMixerGroupEditor.cs b/Editor/Mono/Inspector/AudioMixerGroupEditor.cs deleted file mode 100644 index d73ce4a813..0000000000 --- a/Editor/Mono/Inspector/AudioMixerGroupEditor.cs +++ /dev/null @@ -1,93 +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.Security.Permissions; -using UnityEngine; -using UnityEditor.Audio; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioMixerGroupController))] - internal class AudioMixerGroupEditor : Editor - { - private AudioMixerEffectView m_EffectView = null; - private readonly TickTimerHelper m_Ticker = new TickTimerHelper(1.0 / 20.0); - public static readonly string kPrefKeyForShowCpuUsage = "AudioMixerShowCPU"; - - void OnEnable() - { - EditorApplication.update += Update; - } - - void OnDisable() - { - EditorApplication.update -= Update; - } - - public void Update() - { - if (EditorApplication.isPlaying && m_Ticker.DoTick()) - { - Repaint(); // Ensure repaint to update vu meters and effects in playmode - } - } - - public override void OnInspectorGUI() - { - AudioMixerDrawUtils.InitStyles(); - if (m_EffectView == null) - m_EffectView = new AudioMixerEffectView(); - - AudioMixerGroupController group = target as AudioMixerGroupController; - m_EffectView.OnGUI(group); - } - - public override bool UseDefaultMargins() - { - // Makes inspector be full width - return false; - } - - internal override void DrawHeaderHelpAndSettingsGUI(Rect r) - { - if (m_EffectView == null) - return; - - AudioMixerGroupController group = target as AudioMixerGroupController; - - base.DrawHeaderHelpAndSettingsGUI(r); - Rect rect = new Rect(r.x + 44f, r.yMax - 20f, r.width - 50f, 15f); - GUI.Label(rect, GUIContent.Temp(group.controller.name), EditorStyles.miniLabel); - } - - // Add item to the context menu of the AudioMixerGroupController inspector header - [MenuItem("CONTEXT/AudioMixerGroupController/Copy all effect settings to all snapshots")] - static void CopyAllEffectToSnapshots(MenuCommand command) - { - AudioMixerGroupController group = command.context as AudioMixerGroupController; - AudioMixerController controller = group.controller; - if (controller == null) - return; - - Undo.RecordObject(controller, "Copy all effect settings to all snapshots"); - controller.CopyAllSettingsToAllSnapshots(group, controller.TargetSnapshot); - } - - [MenuItem("CONTEXT/AudioMixerGroupController/Toggle CPU usage display (only available on first editor instance)")] - static void ShowCPUUsage(MenuCommand command) - { - bool value = EditorPrefs.GetBool(kPrefKeyForShowCpuUsage, false); - EditorPrefs.SetBool(kPrefKeyForShowCpuUsage, !value); - } - } - - [CustomEditor(typeof(AudioMixerSnapshotController))] - [CanEditMultipleObjects] - internal class AudioMixerSnapshotControllerInspector : Editor - { - public override void OnInspectorGUI() - { - } - } -} diff --git a/Editor/Mono/Inspector/AudioReverbFilterEditor.cs b/Editor/Mono/Inspector/AudioReverbFilterEditor.cs deleted file mode 100644 index 8273c9ae65..0000000000 --- a/Editor/Mono/Inspector/AudioReverbFilterEditor.cs +++ /dev/null @@ -1,81 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioReverbFilter))] - [CanEditMultipleObjects] - class AudioReverbFilterEditor : Editor - { - SerializedProperty m_ReverbPreset; - - SerializedProperty m_DryLevel; // room effect level (at mid frequencies) - SerializedProperty m_Room; // room effect level (at mid frequencies) - SerializedProperty m_RoomHF; // relative room effect level at high frequencies - SerializedProperty m_RoomLF; // relative room effect level at low frequencies - SerializedProperty m_DecayTime; // reverberation decay time at mid frequencies - SerializedProperty m_DecayHFRatio; // high-frequency to mid-frequency decay time ratio - SerializedProperty m_ReflectionsLevel; // early reflections level relative to room effect - SerializedProperty m_ReflectionsDelay; // initial reflection delay time - SerializedProperty m_ReverbLevel; // late reverberation level relative to room effect - SerializedProperty m_ReverbDelay; // late reverberation delay time relative to initial reflection - SerializedProperty m_HFReference; // reference high frequency (hz) - SerializedProperty m_LFReference; // reference low frequency (hz) - SerializedProperty m_Diffusion; // Value that controls the echo density in the late reverberation decay - SerializedProperty m_Density; // Value that controls the modal density in the late reverberation decay - - - void OnEnable() - { - m_ReverbPreset = serializedObject.FindProperty("m_ReverbPreset"); - m_DryLevel = serializedObject.FindProperty("m_DryLevel"); // room effect level (at mid frequencies) - m_Room = serializedObject.FindProperty("m_Room"); // room effect level (at mid frequencies) - m_RoomHF = serializedObject.FindProperty("m_RoomHF"); // relative room effect level at high frequencies - m_RoomLF = serializedObject.FindProperty("m_RoomLF"); // relative room effect level at low frequencies - m_DecayTime = serializedObject.FindProperty("m_DecayTime"); // reverberation decay time at mid frequencies - m_DecayHFRatio = serializedObject.FindProperty("m_DecayHFRatio"); // high-frequency to mid-frequency decay time ratio - m_ReflectionsLevel = serializedObject.FindProperty("m_ReflectionsLevel"); // early reflections level relative to room effect - m_ReflectionsDelay = serializedObject.FindProperty("m_ReflectionsDelay"); // initial reflection delay time - m_ReverbLevel = serializedObject.FindProperty("m_ReverbLevel"); // late reverberation level relative to room effect - m_ReverbDelay = serializedObject.FindProperty("m_ReverbDelay"); // late reverberation delay time relative to initial reflection - m_HFReference = serializedObject.FindProperty("m_HFReference"); // reference high frequency (hz) - m_LFReference = serializedObject.FindProperty("m_LFReference"); // reference low frequency (hz) - m_Diffusion = serializedObject.FindProperty("m_Diffusion"); // Value that controls the echo density in the late reverberation decay - m_Density = serializedObject.FindProperty("m_Density"); // Value that controls the modal density in the late reverberation decay - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(m_ReverbPreset); - if (EditorGUI.EndChangeCheck()) - serializedObject.SetIsDifferentCacheDirty(); - - using (new EditorGUI.DisabledScope(m_ReverbPreset.enumValueIndex != 27 || m_ReverbPreset.hasMultipleDifferentValues)) - { - EditorGUILayout.Slider(m_DryLevel, -10000, 0); - EditorGUILayout.Slider(m_Room, -10000, 0); - EditorGUILayout.Slider(m_RoomHF, -10000, 0); - EditorGUILayout.Slider(m_RoomLF, -10000, 0); - EditorGUILayout.Slider(m_DecayTime, 0.1f, 20.0f); - EditorGUILayout.Slider(m_DecayHFRatio, 0.1f, 2.0f); - EditorGUILayout.Slider(m_ReflectionsLevel, -10000, 1000); - EditorGUILayout.Slider(m_ReflectionsDelay, 0.0f, 0.3f); - EditorGUILayout.Slider(m_ReverbLevel, -10000, 2000); - EditorGUILayout.Slider(m_ReverbDelay, 0.0f, 0.1f); - EditorGUILayout.Slider(m_HFReference, 1000.0f, 20000.0f); - EditorGUILayout.Slider(m_LFReference, 20.0f, 1000.0f); - EditorGUILayout.Slider(m_Diffusion, 0.0f, 100.0f); - EditorGUILayout.Slider(m_Density, 0.0f, 100.0f); - } - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/AudioReverbZoneEditor.cs b/Editor/Mono/Inspector/AudioReverbZoneEditor.cs deleted file mode 100644 index 9041bf45ea..0000000000 --- a/Editor/Mono/Inspector/AudioReverbZoneEditor.cs +++ /dev/null @@ -1,112 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(AudioReverbZone))] - [CanEditMultipleObjects] - class AudioReverbZoneEditor : Editor - { - SerializedProperty m_MinDistance; - SerializedProperty m_MaxDistance; - SerializedProperty m_ReverbPreset; - - SerializedProperty m_Room; // room effect level (at mid frequencies) - SerializedProperty m_RoomHF; // relative room effect level at high frequencies - SerializedProperty m_RoomLF; // relative room effect level at low frequencies - SerializedProperty m_DecayTime; // reverberation decay time at mid frequencies - SerializedProperty m_DecayHFRatio; // high-frequency to mid-frequency decay time ratio - SerializedProperty m_Reflections; // early reflections level relative to room effect - SerializedProperty m_ReflectionsDelay; // initial reflection delay time - SerializedProperty m_Reverb; // late reverberation level relative to room effect - SerializedProperty m_ReverbDelay; // late reverberation delay time relative to initial reflection - SerializedProperty m_HFReference; // reference high frequency (hz) - SerializedProperty m_LFReference; // reference low frequency (hz) - SerializedProperty m_Diffusion; // Value that controls the echo density in the late reverberation decay - SerializedProperty m_Density; // Value that controls the modal density in the late reverberation decay - - void OnEnable() - { - m_MinDistance = serializedObject.FindProperty("m_MinDistance"); - m_MaxDistance = serializedObject.FindProperty("m_MaxDistance"); - m_ReverbPreset = serializedObject.FindProperty("m_ReverbPreset"); - m_Room = serializedObject.FindProperty("m_Room"); // room effect level (at mid frequencies) - m_RoomHF = serializedObject.FindProperty("m_RoomHF"); // relative room effect level at high frequencies - m_RoomLF = serializedObject.FindProperty("m_RoomLF"); // relative room effect level at low frequencies - m_DecayTime = serializedObject.FindProperty("m_DecayTime"); // reverberation decay time at mid frequencies - m_DecayHFRatio = serializedObject.FindProperty("m_DecayHFRatio"); // high-frequency to mid-frequency decay time ratio - m_Reflections = serializedObject.FindProperty("m_Reflections"); // early reflections level relative to room effect - m_ReflectionsDelay = serializedObject.FindProperty("m_ReflectionsDelay"); // initial reflection delay time - m_Reverb = serializedObject.FindProperty("m_Reverb"); // late reverberation level relative to room effect - m_ReverbDelay = serializedObject.FindProperty("m_ReverbDelay"); // late reverberation delay time relative to initial reflection - m_HFReference = serializedObject.FindProperty("m_HFReference"); // reference high frequency (hz) - m_LFReference = serializedObject.FindProperty("m_LFReference"); // reference low frequency (hz) - m_Diffusion = serializedObject.FindProperty("m_Diffusion"); // Value that controls the echo density in the late reverberation decay - m_Density = serializedObject.FindProperty("m_Density"); // Value that controls the modal density in the late reverberation decay - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_MinDistance); - EditorGUILayout.PropertyField(m_MaxDistance); - - EditorGUILayout.Space(); - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(m_ReverbPreset); - // Changing the preset changes all the other properties as well, so we need to do a full refresh afterwards - if (EditorGUI.EndChangeCheck()) - serializedObject.SetIsDifferentCacheDirty(); - - using (new EditorGUI.DisabledScope(m_ReverbPreset.enumValueIndex != 27 || m_ReverbPreset.hasMultipleDifferentValues)) - { - EditorGUILayout.IntSlider(m_Room, -10000, 0); - EditorGUILayout.IntSlider(m_RoomHF, -10000, 0); - EditorGUILayout.IntSlider(m_RoomLF, -10000, 0); - EditorGUILayout.Slider(m_DecayTime, 0.1f, 20.0f); - EditorGUILayout.Slider(m_DecayHFRatio, 0.1f, 2.0f); - EditorGUILayout.IntSlider(m_Reflections, -10000, 1000); - EditorGUILayout.Slider(m_ReflectionsDelay, 0.0f, 0.3f); - EditorGUILayout.IntSlider(m_Reverb, -10000, 2000); - EditorGUILayout.Slider(m_ReverbDelay, 0.0f, 0.1f); - EditorGUILayout.Slider(m_HFReference, 1000.0f, 20000.0f); - EditorGUILayout.Slider(m_LFReference, 20.0f, 1000.0f); - EditorGUILayout.Slider(m_Diffusion, 0.0f, 100.0f); - EditorGUILayout.Slider(m_Density, 0.0f, 100.0f); - } - - serializedObject.ApplyModifiedProperties(); - } - - void OnSceneGUI() - { - AudioReverbZone zone = (AudioReverbZone)target; - - Color tempColor = Handles.color; - if (zone.enabled) - Handles.color = new Color(0.50f, 0.70f, 1.00f, 0.5f); - else - Handles.color = new Color(0.30f, 0.40f, 0.60f, 0.5f); - - Vector3 position = zone.transform.position; - - EditorGUI.BeginChangeCheck(); - float minDistance = Handles.RadiusHandle(Quaternion.identity, position, zone.minDistance, true); - float maxDistance = Handles.RadiusHandle(Quaternion.identity, position, zone.maxDistance, true); - - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(zone, "Reverb Distance"); - zone.minDistance = minDistance; - zone.maxDistance = maxDistance; - } - - Handles.color = tempColor; - } - } -} diff --git a/Editor/Mono/Inspector/AudioSourceExtensionEditor.cs b/Editor/Mono/Inspector/AudioSourceExtensionEditor.cs deleted file mode 100644 index 8ddb9afcf1..0000000000 --- a/Editor/Mono/Inspector/AudioSourceExtensionEditor.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; -using System.Collections.Generic; -using System.Linq; - -namespace UnityEditor -{ - internal class AudioSourceExtensionEditor : AudioExtensionEditor - { - public virtual void OnAudioSourceGUI() {} - public virtual void OnAudioSourceSceneGUI(AudioSource source) {} - - protected override int GetNumSerializedExtensionProperties(Object obj) - { - AudioSource source = obj as AudioSource; - int numSerializedExtensionProperties = source ? source.GetNumExtensionProperties() : 0; - - return numSerializedExtensionProperties; - } - } -} diff --git a/Editor/Mono/Inspector/Avatar/AvatarBipedMapper.cs b/Editor/Mono/Inspector/Avatar/AvatarBipedMapper.cs deleted file mode 100644 index 8938e5a8a3..0000000000 --- a/Editor/Mono/Inspector/Avatar/AvatarBipedMapper.cs +++ /dev/null @@ -1,282 +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 UnityEditor; -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEditorInternal; -using System.Linq; - -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class AvatarBipedMapper - { - private struct BipedBone - { - public string name; - public int index; - - public BipedBone(string name, int index) - { - this.name = name; - this.index = index; - } - } - - private static BipedBone[] s_BipedBones = new BipedBone[] - { - // body - new BipedBone("Pelvis", (int)HumanBodyBones.Hips), - new BipedBone("L Thigh", (int)HumanBodyBones.LeftUpperLeg), - new BipedBone("R Thigh", (int)HumanBodyBones.RightUpperLeg), - new BipedBone("L Calf", (int)HumanBodyBones.LeftLowerLeg), - new BipedBone("R Calf", (int)HumanBodyBones.RightLowerLeg), - new BipedBone("L Foot", (int)HumanBodyBones.LeftFoot), - new BipedBone("R Foot", (int)HumanBodyBones.RightFoot), - new BipedBone("Spine", (int)HumanBodyBones.Spine), - new BipedBone("Spine1", (int)HumanBodyBones.Chest), - new BipedBone("Spine2", (int)HumanBodyBones.UpperChest), - new BipedBone("Neck", (int)HumanBodyBones.Neck), - new BipedBone("Head", (int)HumanBodyBones.Head), - new BipedBone("L Clavicle", (int)HumanBodyBones.LeftShoulder), - new BipedBone("R Clavicle", (int)HumanBodyBones.RightShoulder), - new BipedBone("L UpperArm", (int)HumanBodyBones.LeftUpperArm), - new BipedBone("R UpperArm", (int)HumanBodyBones.RightUpperArm), - new BipedBone("L Forearm", (int)HumanBodyBones.LeftLowerArm), - new BipedBone("R Forearm", (int)HumanBodyBones.RightLowerArm), - new BipedBone("L Hand", (int)HumanBodyBones.LeftHand), - new BipedBone("R Hand", (int)HumanBodyBones.RightHand), - new BipedBone("L Toe0", (int)HumanBodyBones.LeftToes), - new BipedBone("R Toe0", (int)HumanBodyBones.RightToes), - // Left Hand - new BipedBone("L Finger0", (int)HumanBodyBones.LeftThumbProximal), - new BipedBone("L Finger01", (int)HumanBodyBones.LeftThumbIntermediate), - new BipedBone("L Finger02", (int)HumanBodyBones.LeftThumbDistal), - new BipedBone("L Finger1", (int)HumanBodyBones.LeftIndexProximal), - new BipedBone("L Finger11", (int)HumanBodyBones.LeftIndexIntermediate), - new BipedBone("L Finger12", (int)HumanBodyBones.LeftIndexDistal), - new BipedBone("L Finger2", (int)HumanBodyBones.LeftMiddleProximal), - new BipedBone("L Finger21", (int)HumanBodyBones.LeftMiddleIntermediate), - new BipedBone("L Finger22", (int)HumanBodyBones.LeftMiddleDistal), - new BipedBone("L Finger3", (int)HumanBodyBones.LeftRingProximal), - new BipedBone("L Finger31", (int)HumanBodyBones.LeftRingIntermediate), - new BipedBone("L Finger32", (int)HumanBodyBones.LeftRingDistal), - new BipedBone("L Finger4", (int)HumanBodyBones.LeftLittleProximal), - new BipedBone("L Finger41", (int)HumanBodyBones.LeftLittleIntermediate), - new BipedBone("L Finger42", (int)HumanBodyBones.LeftLittleDistal), - // Right Hand - new BipedBone("R Finger0", (int)HumanBodyBones.RightThumbProximal), - new BipedBone("R Finger01", (int)HumanBodyBones.RightThumbIntermediate), - new BipedBone("R Finger02", (int)HumanBodyBones.RightThumbDistal), - new BipedBone("R Finger1", (int)HumanBodyBones.RightIndexProximal), - new BipedBone("R Finger11", (int)HumanBodyBones.RightIndexIntermediate), - new BipedBone("R Finger12", (int)HumanBodyBones.RightIndexDistal), - new BipedBone("R Finger2", (int)HumanBodyBones.RightMiddleProximal), - new BipedBone("R Finger21", (int)HumanBodyBones.RightMiddleIntermediate), - new BipedBone("R Finger22", (int)HumanBodyBones.RightMiddleDistal), - new BipedBone("R Finger3", (int)HumanBodyBones.RightRingProximal), - new BipedBone("R Finger31", (int)HumanBodyBones.RightRingIntermediate), - new BipedBone("R Finger32", (int)HumanBodyBones.RightRingDistal), - new BipedBone("R Finger4", (int)HumanBodyBones.RightLittleProximal), - new BipedBone("R Finger41", (int)HumanBodyBones.RightLittleIntermediate), - new BipedBone("R Finger42", (int)HumanBodyBones.RightLittleDistal) - }; - - public static bool IsBiped(Transform root, List report) - { - if (report != null) - { - report.Clear(); - } - - Transform[] humanToTransform = new Transform[HumanTrait.BoneCount]; - return MapBipedBones(root, ref humanToTransform, report); - } - - public static Dictionary MapBones(Transform root) - { - Dictionary ret = new Dictionary(); - - Transform[] humanToTransform = new Transform[HumanTrait.BoneCount]; - - if (MapBipedBones(root, ref humanToTransform, null)) - { - for (int boneIter = 0; boneIter < HumanTrait.BoneCount; boneIter++) - { - if (humanToTransform[boneIter] != null) - { - ret.Add(boneIter, humanToTransform[boneIter]); - } - } - } - - // Move upper chest to chest if no chest was found - if (!ret.ContainsKey((int)HumanBodyBones.Chest) && - ret.ContainsKey((int)HumanBodyBones.UpperChest)) - { - ret.Add((int)HumanBodyBones.Chest, ret[(int)HumanBodyBones.UpperChest]); - ret.Remove((int)HumanBodyBones.UpperChest); - } - - return ret; - } - - private static bool MapBipedBones(Transform root, ref Transform[] humanToTransform, List report) - { - for (int bipedBoneIter = 0; bipedBoneIter < s_BipedBones.Length; bipedBoneIter++) - { - int boneIndex = s_BipedBones[bipedBoneIter].index; - - int parentIndex = HumanTrait.GetParentBone(boneIndex); - - bool required = HumanTrait.RequiredBone(boneIndex); - bool parentRequired = parentIndex != -1 ? HumanTrait.RequiredBone(parentIndex) : true; - - Transform parentTransform = parentIndex != -1 ? humanToTransform[parentIndex] : root; - - if (parentTransform == null && !parentRequired) - { - parentIndex = HumanTrait.GetParentBone(parentIndex); - parentRequired = parentIndex != -1 ? HumanTrait.RequiredBone(parentIndex) : true; - parentTransform = parentIndex != -1 ? humanToTransform[parentIndex] : null; - - if (parentTransform == null && !parentRequired) - { - parentIndex = HumanTrait.GetParentBone(parentIndex); - parentTransform = parentIndex != -1 ? humanToTransform[parentIndex] : null; - } - } - - humanToTransform[boneIndex] = MapBipedBone(bipedBoneIter, parentTransform, parentTransform, report); - - if (humanToTransform[boneIndex] == null && required) - { - return false; - } - } - - return true; - } - - private static Transform MapBipedBone(int bipedBoneIndex, Transform transform, Transform parentTransform, List report) - { - Transform ret = null; - - if (transform != null) - { - int childCount = transform.childCount; - - for (int childIter = 0; ret == null && childIter < childCount; childIter++) - { - string boneName = s_BipedBones[bipedBoneIndex].name; - int boneIndex = s_BipedBones[bipedBoneIndex].index; - - if (transform.GetChild(childIter).name.EndsWith(boneName)) - { - ret = transform.GetChild(childIter); - - if (ret != null && report != null && boneIndex != (int)HumanBodyBones.Hips && transform != parentTransform) - { - string current = "- Invalid parent for " + ret.name + ". Expected " + parentTransform.name + ", but found " + transform.name + "."; - - if (boneIndex == (int)HumanBodyBones.LeftUpperLeg || boneIndex == (int)HumanBodyBones.RightUpperLeg) - { - current += " Disable Triangle Pelvis"; - } - else if (boneIndex == (int)HumanBodyBones.LeftShoulder || boneIndex == (int)HumanBodyBones.RightShoulder) - { - current += " Enable Triangle Neck"; - } - else if (boneIndex == (int)HumanBodyBones.Neck) - { - current += " Preferred is three Spine Links"; - } - else if (boneIndex == (int)HumanBodyBones.Head) - { - current += " Preferred is one Neck Links"; - } - - current += "\n"; - - report.Add(current); - } - } - } - - for (int childIter = 0; ret == null && childIter < childCount; childIter++) - { - ret = MapBipedBone(bipedBoneIndex, transform.GetChild(childIter), parentTransform, report); - } - } - - return ret; - } - - internal static void BipedPose(GameObject go, AvatarSetupTool.BoneWrapper[] bones) - { - BipedPose(go.transform, true); - - // Orient Biped - Quaternion rot = AvatarSetupTool.AvatarComputeOrientation(bones); - go.transform.rotation = Quaternion.Inverse(rot) * go.transform.rotation; - - // Move Biped feet to ground plane - AvatarSetupTool.MakeCharacterPositionValid(bones); - } - - private static void BipedPose(Transform t, bool ignore) - { - if (t.name.EndsWith("Pelvis")) - { - t.localRotation = Quaternion.Euler(270, 90, 0); - ignore = false; - } - else if (t.name.EndsWith("Thigh")) - { - t.localRotation = Quaternion.Euler(0, 180, 0); - } - else if (t.name.EndsWith("Toe0")) - { - t.localRotation = Quaternion.Euler(0, 0, 270); - } - else if (t.name.EndsWith("L Clavicle")) - { - t.localRotation = Quaternion.Euler(0, 270, 180); - } - else if (t.name.EndsWith("R Clavicle")) - { - t.localRotation = Quaternion.Euler(0, 90, 180); - } - else if (t.name.EndsWith("L Hand")) - { - t.localRotation = Quaternion.Euler(270, 0, 0); - } - else if (t.name.EndsWith("R Hand")) - { - t.localRotation = Quaternion.Euler(90, 0, 0); - } - else if (t.name.EndsWith("L Finger0")) - { - t.localRotation = Quaternion.Euler(0, 315, 0); - } - else if (t.name.EndsWith("R Finger0")) - { - t.localRotation = Quaternion.Euler(0, 45, 0); - } - else if (!ignore) - { - t.localRotation = Quaternion.identity; - } - - foreach (Transform child in t) - { - BipedPose(child, ignore); - } - } - } -} diff --git a/Editor/Mono/Inspector/Avatar/AvatarControl.cs b/Editor/Mono/Inspector/Avatar/AvatarControl.cs deleted file mode 100644 index c95dfa60de..0000000000 --- a/Editor/Mono/Inspector/Avatar/AvatarControl.cs +++ /dev/null @@ -1,283 +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 System; -using System.Collections.Generic; - -namespace UnityEditor -{ - public enum BodyPart - { - None = -1, - Avatar = 0, - Body, - Head, - LeftArm, - LeftFingers, - RightArm, - RightFingers, - LeftLeg, - RightLeg, - Last - } - - internal class AvatarControl - { - class Styles - { - // IF you change the order of this array, please update: - // BodyPartMapping - // m_BodyPartHumanBone - // BodyPart - - public GUIContent[] Silhouettes = - { - EditorGUIUtility.IconContent("AvatarInspector/BodySilhouette"), - EditorGUIUtility.IconContent("AvatarInspector/HeadZoomSilhouette"), - EditorGUIUtility.IconContent("AvatarInspector/LeftHandZoomSilhouette"), - EditorGUIUtility.IconContent("AvatarInspector/RightHandZoomSilhouette") - }; - - public GUIContent[,] BodyPart = - { - { - null, - EditorGUIUtility.IconContent("AvatarInspector/Torso"), - EditorGUIUtility.IconContent("AvatarInspector/Head"), - EditorGUIUtility.IconContent("AvatarInspector/LeftArm"), - EditorGUIUtility.IconContent("AvatarInspector/LeftFingers"), - EditorGUIUtility.IconContent("AvatarInspector/RightArm"), - EditorGUIUtility.IconContent("AvatarInspector/RightFingers"), - EditorGUIUtility.IconContent("AvatarInspector/LeftLeg"), - EditorGUIUtility.IconContent("AvatarInspector/RightLeg") - }, - { - null, - null, - EditorGUIUtility.IconContent("AvatarInspector/HeadZoom"), - null, - null, - null, - null, - null, - null - }, - { - null, - null, - null, - null, - EditorGUIUtility.IconContent("AvatarInspector/LeftHandZoom"), - null, - null, - null, - null - }, - { - null, - null, - null, - null, - null, - null, - EditorGUIUtility.IconContent("AvatarInspector/RightHandZoom"), - null, - null - }, - }; - } - - static Styles styles { get { if (s_Styles == null) s_Styles = new Styles(); return s_Styles; } } - static Styles s_Styles; - - public enum BodyPartColor - { - Off = 0x00, - Green = 0x01 << 0, - Red = 0x01 << 1, - IKGreen = 0x01 << 2, - IKRed = 0x01 << 3, - } - - public delegate BodyPartColor BodyPartFeedback(BodyPart bodyPart); - - static public int ShowBoneMapping(int shownBodyView, BodyPartFeedback bodyPartCallback, AvatarSetupTool.BoneWrapper[] bones, SerializedObject serializedObject, AvatarMappingEditor editor) - { - GUILayout.BeginHorizontal(); - { - GUILayout.FlexibleSpace(); - - if (styles.Silhouettes[shownBodyView].image) - { - Rect rect = GUILayoutUtility.GetRect(styles.Silhouettes[shownBodyView], GUIStyle.none, GUILayout.MaxWidth(styles.Silhouettes[shownBodyView].image.width)); - DrawBodyParts(rect, shownBodyView, bodyPartCallback); - - for (int i = 0; i < bones.Length; i++) - DrawBone(shownBodyView, i, rect, bones[i], serializedObject, editor); - } - else - GUILayout.Label("texture missing,\nfix me!"); - - GUILayout.FlexibleSpace(); - } - GUILayout.EndHorizontal(); - - // Body view buttons - Rect buttonsRect = GUILayoutUtility.GetLastRect(); - const float buttonHeight = 16; - string[] labels = new string[] { "Body", "Head", "Left Hand", "Right Hand"}; - buttonsRect.x += 5; - buttonsRect.width = 70; - buttonsRect.yMin = buttonsRect.yMax - (buttonHeight * 4 + 5); - buttonsRect.height = buttonHeight; - for (int i = 0; i < labels.Length; i++) - { - if (GUI.Toggle(buttonsRect, shownBodyView == i, labels[i], EditorStyles.miniButton)) - shownBodyView = i; - buttonsRect.y += buttonHeight; - } - - return shownBodyView; - } - - static public void DrawBodyParts(Rect rect, int shownBodyView, BodyPartFeedback bodyPartCallback) - { - GUI.color = new Color(0.2f, 0.2f, 0.2f, 1.0f); - if (styles.Silhouettes[shownBodyView] != null) - GUI.DrawTexture(rect, styles.Silhouettes[shownBodyView].image); - for (int i = 1; i < (int)BodyPart.Last; i++) - DrawBodyPart(shownBodyView, i, rect, bodyPartCallback((BodyPart)i)); - } - - static protected void DrawBodyPart(int shownBodyView, int i, Rect rect, BodyPartColor bodyPartColor) - { - if (styles.BodyPart[shownBodyView, i] != null && styles.BodyPart[shownBodyView, i].image != null) - { - if ((bodyPartColor & BodyPartColor.Green) == BodyPartColor.Green) - GUI.color = Color.green; - else if ((bodyPartColor & BodyPartColor.Red) == BodyPartColor.Red) - GUI.color = Color.red; - else - GUI.color = Color.gray; - GUI.DrawTexture(rect, styles.BodyPart[shownBodyView, i].image); - GUI.color = Color.white; - } - } - - static Vector2[,] s_BonePositions = new Vector2[4, HumanTrait.BoneCount]; - - public static List GetViewsThatContainBone(int bone) - { - List views = new List(); - - if (bone < 0 || bone >= HumanTrait.BoneCount) - return views; - - for (int i = 0; i < 4; i++) - { - if (s_BonePositions[i, bone] != Vector2.zero) - views.Add(i); - } - return views; - } - - static AvatarControl() - { - // Body view - int view = 0; - // hips - s_BonePositions[view, (int)HumanBodyBones.Hips] = new Vector2(0.00f, 0.08f); - - // upper leg - s_BonePositions[view, (int)HumanBodyBones.LeftUpperLeg] = new Vector2(0.16f, 0.01f); - s_BonePositions[view, (int)HumanBodyBones.RightUpperLeg] = new Vector2(-0.16f, 0.01f); - - // lower leg - s_BonePositions[view, (int)HumanBodyBones.LeftLowerLeg] = new Vector2(0.21f, -0.40f); - s_BonePositions[view, (int)HumanBodyBones.RightLowerLeg] = new Vector2(-0.21f, -0.40f); - - // foot - s_BonePositions[view, (int)HumanBodyBones.LeftFoot] = new Vector2(0.23f, -0.80f); - s_BonePositions[view, (int)HumanBodyBones.RightFoot] = new Vector2(-0.23f, -0.80f); - - // spine - head - s_BonePositions[view, (int)HumanBodyBones.Spine] = new Vector2(0.00f, 0.20f); - s_BonePositions[view, (int)HumanBodyBones.Chest] = new Vector2(0.00f, 0.35f); - s_BonePositions[view, (int)HumanBodyBones.UpperChest] = new Vector2(0.00f, 0.50f); - s_BonePositions[view, (int)HumanBodyBones.Neck] = new Vector2(0.00f, 0.66f); - s_BonePositions[view, (int)HumanBodyBones.Head] = new Vector2(0.00f, 0.76f); - - // shoulder - s_BonePositions[view, (int)HumanBodyBones.LeftShoulder] = new Vector2(0.14f, 0.60f); - s_BonePositions[view, (int)HumanBodyBones.RightShoulder] = new Vector2(-0.14f, 0.60f); - - // upper arm - s_BonePositions[view, (int)HumanBodyBones.LeftUpperArm] = new Vector2(0.30f, 0.57f); - s_BonePositions[view, (int)HumanBodyBones.RightUpperArm] = new Vector2(-0.30f, 0.57f); - - // lower arm - s_BonePositions[view, (int)HumanBodyBones.LeftLowerArm] = new Vector2(0.48f, 0.30f); - s_BonePositions[view, (int)HumanBodyBones.RightLowerArm] = new Vector2(-0.48f, 0.30f); - - // hand - s_BonePositions[view, (int)HumanBodyBones.LeftHand] = new Vector2(0.66f, 0.03f); - s_BonePositions[view, (int)HumanBodyBones.RightHand] = new Vector2(-0.66f, 0.03f); - - // toe - s_BonePositions[view, (int)HumanBodyBones.LeftToes] = new Vector2(0.25f, -0.89f); - s_BonePositions[view, (int)HumanBodyBones.RightToes] = new Vector2(-0.25f, -0.89f); - - // Head view - view = 1; - // neck - head - s_BonePositions[view, (int)HumanBodyBones.Neck] = new Vector2(-0.20f, -0.62f); - s_BonePositions[view, (int)HumanBodyBones.Head] = new Vector2(-0.15f, -0.30f); - // left, right eye - s_BonePositions[view, (int)HumanBodyBones.LeftEye] = new Vector2(0.63f, 0.16f); - s_BonePositions[view, (int)HumanBodyBones.RightEye] = new Vector2(0.15f, 0.16f); - // jaw - s_BonePositions[view, (int)HumanBodyBones.Jaw] = new Vector2(0.45f, -0.40f); - - // Left hand view - view = 2; - // finger bases, thumb - little - s_BonePositions[view, (int)HumanBodyBones.LeftThumbProximal] = new Vector2(-0.35f, 0.11f); - s_BonePositions[view, (int)HumanBodyBones.LeftIndexProximal] = new Vector2(0.19f, 0.11f); - s_BonePositions[view, (int)HumanBodyBones.LeftMiddleProximal] = new Vector2(0.22f, 0.00f); - s_BonePositions[view, (int)HumanBodyBones.LeftRingProximal] = new Vector2(0.16f, -0.12f); - s_BonePositions[view, (int)HumanBodyBones.LeftLittleProximal] = new Vector2(0.09f, -0.23f); - - // finger tips, thumb - little - s_BonePositions[view, (int)HumanBodyBones.LeftThumbDistal] = new Vector2(-0.03f, 0.33f); - s_BonePositions[view, (int)HumanBodyBones.LeftIndexDistal] = new Vector2(0.65f, 0.16f); - s_BonePositions[view, (int)HumanBodyBones.LeftMiddleDistal] = new Vector2(0.74f, 0.00f); - s_BonePositions[view, (int)HumanBodyBones.LeftRingDistal] = new Vector2(0.66f, -0.14f); - s_BonePositions[view, (int)HumanBodyBones.LeftLittleDistal] = new Vector2(0.45f, -0.25f); - - // finger middles, thumb - little - for (int i = 0; i < 5; i++) - s_BonePositions[view, (int)HumanBodyBones.LeftThumbIntermediate + i * 3] = Vector2.Lerp(s_BonePositions[view, (int)HumanBodyBones.LeftThumbProximal + i * 3], s_BonePositions[view, (int)HumanBodyBones.LeftThumbDistal + i * 3], 0.58f); - - // Right hand view - view = 3; - for (int i = 0; i < 15; i++) - s_BonePositions[view, (int)HumanBodyBones.LeftThumbProximal + i + 15] = Vector2.Scale(s_BonePositions[view - 1, (int)HumanBodyBones.LeftThumbProximal + i], new Vector2(-1, 1)); - } - - static protected void DrawBone(int shownBodyView, int i, Rect rect, AvatarSetupTool.BoneWrapper bone, SerializedObject serializedObject, AvatarMappingEditor editor) - { - if (s_BonePositions[shownBodyView, i] == Vector2.zero) - return; - - Vector2 pos = s_BonePositions[shownBodyView, i]; - pos.y *= -1; // because higher values should be up - pos.Scale(new Vector2(rect.width * 0.5f, rect.height * 0.5f)); - pos = rect.center + pos; - int kIconSize = AvatarSetupTool.BoneWrapper.kIconSize; - Rect r = new Rect(pos.x - kIconSize * 0.5f, pos.y - kIconSize * 0.5f, kIconSize, kIconSize); - bone.BoneDotGUI(r, r, i, true, true, true, serializedObject, editor); - } - } -} diff --git a/Editor/Mono/Inspector/Avatar/AvatarMappingEditor.cs b/Editor/Mono/Inspector/Avatar/AvatarMappingEditor.cs index 50ceac4111..9cf9bfb61a 100644 --- a/Editor/Mono/Inspector/Avatar/AvatarMappingEditor.cs +++ b/Editor/Mono/Inspector/Avatar/AvatarMappingEditor.cs @@ -251,15 +251,27 @@ private void HandleBodyView(int bodyView) Vector2 m_FoldoutScroll = Vector2.zero; - public override void OnInspectorGUI() + private void SetupInternalProperties() + { + m_HumanBoneArray = serializedObject.FindProperty("m_HumanDescription.m_Human"); + m_Skeleton = serializedObject.FindProperty("m_HumanDescription.m_Skeleton"); + } + + private void HandleUndoPerformed() { if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == EventCommandNames.UndoRedoPerformed) { + SetupInternalProperties(); + AvatarSetupTool.TransferPoseToDescription(m_Skeleton, root); for (int i = 0; i < m_Bones.Length; i++) m_Bones[i].Serialize(m_HumanBoneArray); } + } + public override void OnInspectorGUI() + { + HandleUndoPerformed(); UpdateSelectedBone(); // case 837655. GUI.keyboardControl is overriden when changing scene selection. diff --git a/Editor/Mono/Inspector/AvatarMaskUtility.cs b/Editor/Mono/Inspector/AvatarMaskUtility.cs deleted file mode 100644 index cab122c203..0000000000 --- a/Editor/Mono/Inspector/AvatarMaskUtility.cs +++ /dev/null @@ -1,163 +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 System.Collections; -using UnityEditor; -using System.Collections.Generic; -using System.Linq; - -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class AvatarMaskUtility - { - private static string sHuman = "m_HumanDescription.m_Human"; - private static string sBoneName = "m_BoneName"; - - static public string[] GetAvatarHumanTransform(SerializedObject so, string[] refTransformsPath) - { - SerializedProperty humanBoneArray = so.FindProperty(sHuman); - if (humanBoneArray == null || !humanBoneArray.isArray) - return null; - - List humanTransforms = new List(); - for (int i = 0; i < humanBoneArray.arraySize; i++) - { - SerializedProperty transformNameP = humanBoneArray.GetArrayElementAtIndex(i).FindPropertyRelative(sBoneName); - humanTransforms.Add(transformNameP.stringValue); - } - - return TokeniseHumanTransformsPath(refTransformsPath, humanTransforms.ToArray()); - } - - static public string[] GetAvatarHumanAndActiveExtraTransforms(SerializedObject so, SerializedProperty transformMaskProperty, string[] refTransformsPath) - { - SerializedProperty humanBoneArray = so.FindProperty(sHuman); - if (humanBoneArray == null || !humanBoneArray.isArray) - return null; - - List humanTransforms = new List(); - for (int i = 0; i < humanBoneArray.arraySize; i++) - { - SerializedProperty transformNameP = humanBoneArray.GetArrayElementAtIndex(i).FindPropertyRelative(sBoneName); - humanTransforms.Add(transformNameP.stringValue); - } - - List values = new List(TokeniseHumanTransformsPath(refTransformsPath, humanTransforms.ToArray())); - - for (int i = 0; i < transformMaskProperty.arraySize; i++) - { - float weight = transformMaskProperty.GetArrayElementAtIndex(i).FindPropertyRelative("m_Weight").floatValue; - string transformName = transformMaskProperty.GetArrayElementAtIndex(i).FindPropertyRelative("m_Path").stringValue; - - if (weight > 0.0f && !values.Contains(transformName)) - { - values.Add(transformName); - } - } - - return values.ToArray(); - } - - static public string[] GetAvatarInactiveTransformMaskPaths(SerializedProperty transformMaskProperty) - { - if (transformMaskProperty == null || !transformMaskProperty.isArray) - return null; - - List transformPaths = new List(); - for (int i = 0; i < transformMaskProperty.arraySize; i++) - { - SerializedProperty weight = transformMaskProperty.GetArrayElementAtIndex(i).FindPropertyRelative("m_Weight"); - if (weight.floatValue < 0.5f) - { - SerializedProperty transformNameP = transformMaskProperty.GetArrayElementAtIndex(i).FindPropertyRelative("m_Path"); - transformPaths.Add(transformNameP.stringValue); - } - } - - return transformPaths.ToArray(); - } - - static public void UpdateTransformMask(AvatarMask mask, string[] refTransformsPath, string[] humanTransforms) - { - mask.transformCount = refTransformsPath.Length; - for (int i = 0; i < refTransformsPath.Length; i++) - { - mask.SetTransformPath(i, refTransformsPath[i]); - - bool isActiveTransform = humanTransforms == null - ? true - : ArrayUtility.FindIndex(humanTransforms, s => refTransformsPath[i] == s) != -1; - mask.SetTransformActive(i, isActiveTransform); - } - } - - static public void UpdateTransformMask(SerializedProperty transformMask, string[] refTransformsPath, string[] currentPaths, bool areActivePaths = true) - { - // if areActivePaths=true, currentPaths is treated as the list of active transform paths - // else, currentPaths is treated as the list of inactive transform paths - AvatarMask refMask = new AvatarMask(); - - refMask.transformCount = refTransformsPath.Length; - - for (int i = 0; i < refTransformsPath.Length; i++) - { - bool isActiveTransform; - if (currentPaths == null) - isActiveTransform = true; - else if (areActivePaths) - isActiveTransform = ArrayUtility.FindIndex(currentPaths, s => refTransformsPath[i] == s) != -1; - else - isActiveTransform = ArrayUtility.FindIndex(currentPaths, s => refTransformsPath[i] == s) == -1; - - refMask.SetTransformPath(i, refTransformsPath[i]); - refMask.SetTransformActive(i, isActiveTransform); - } - ModelImporter.UpdateTransformMask(refMask, transformMask); - } - - static public void SetActiveHumanTransforms(AvatarMask mask, string[] humanTransforms) - { - for (int i = 0; i < mask.transformCount; i++) - { - string path = mask.GetTransformPath(i); - if (ArrayUtility.FindIndex(humanTransforms, s => path == s) != -1) - mask.SetTransformActive(i, true); - } - } - - static private string[] TokeniseHumanTransformsPath(string[] refTransformsPath, string[] humanTransforms) - { - if (humanTransforms == null) - return null; - - // all list must always include the string "" which is the root game object - string[] tokeniseTransformsPath = new string[] {""}; - - for (int i = 0; i < humanTransforms.Length; i++) - { - int index1 = ArrayUtility.FindIndex(refTransformsPath, s => humanTransforms[i] == FileUtil.GetLastPathNameComponent(s)); - if (index1 != -1) - { - int insertIndex = tokeniseTransformsPath.Length; - - string path = refTransformsPath[index1]; - while (path.Length > 0) - { - int index2 = ArrayUtility.FindIndex(tokeniseTransformsPath, s => path == s); - if (index2 == -1) - ArrayUtility.Insert(ref tokeniseTransformsPath, insertIndex, path); - - int lastIndex = path.LastIndexOf('/'); - path = path.Substring(0, lastIndex != -1 ? lastIndex : 0); - } - } - } - - return tokeniseTransformsPath; - } - } -} diff --git a/Editor/Mono/Inspector/AvatarPreviewSelection.cs b/Editor/Mono/Inspector/AvatarPreviewSelection.cs deleted file mode 100644 index cafd672df1..0000000000 --- a/Editor/Mono/Inspector/AvatarPreviewSelection.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 UnityEditor; -using UnityEditorInternal; -using System.Reflection; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class AvatarPreviewSelection : ScriptableSingleton - { - [SerializeField] - GameObject[] m_PreviewModels; - - void Awake() - { - int length = (int)ModelImporterAnimationType.Human + 1; - if (m_PreviewModels == null || m_PreviewModels.Length != length) - m_PreviewModels = new GameObject[length]; - } - - static public void SetPreview(ModelImporterAnimationType type, GameObject go) - { - if (!System.Enum.IsDefined(typeof(ModelImporterAnimationType), type)) - return; - - if (instance.m_PreviewModels[(int)type] != go) - { - instance.m_PreviewModels[(int)type] = go; - instance.Save(false); - } - } - - static public GameObject GetPreview(ModelImporterAnimationType type) - { - if (!System.Enum.IsDefined(typeof(ModelImporterAnimationType), type)) - return null; - - return instance.m_PreviewModels[(int)type]; - } - } // class AvatarPreviewSelection -} // namespace UnityEditor diff --git a/Editor/Mono/Inspector/BillboardRendererInspector.cs b/Editor/Mono/Inspector/BillboardRendererInspector.cs deleted file mode 100644 index 870db1fa13..0000000000 --- a/Editor/Mono/Inspector/BillboardRendererInspector.cs +++ /dev/null @@ -1,44 +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.Collections.Generic; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(BillboardRenderer))] - [CanEditMultipleObjects] - internal class BillboardRendererInspector : RendererEditorBase - { - private string[] m_ExcludedProperties; - - public override void OnEnable() - { - base.OnEnable(); - InitializeProbeFields(); - - List excludedProperties = new List(); - excludedProperties.AddRange(new[] - { - "m_Materials", - "m_LightmapParameters" - }); - excludedProperties.AddRange(Probes.GetFieldsStringArray()); - m_ExcludedProperties = excludedProperties.ToArray(); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - DrawPropertiesExcluding(serializedObject, m_ExcludedProperties); - - m_Probes.OnGUI(targets, (Renderer)target, false); - - RenderRenderingLayer(); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/BoxCollider2DEditor.cs b/Editor/Mono/Inspector/BoxCollider2DEditor.cs deleted file mode 100644 index b7dff110bd..0000000000 --- a/Editor/Mono/Inspector/BoxCollider2DEditor.cs +++ /dev/null @@ -1,120 +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.IMGUI.Controls; -using UnityEditor.AnimatedValues; -using UnityEngine; -using UnityEditorInternal; - -namespace UnityEditor -{ - [CustomEditor(typeof(BoxCollider2D))] - [CanEditMultipleObjects] - internal class BoxCollider2DEditor : Collider2DEditorBase - { - private SerializedProperty m_Size; - private SerializedProperty m_EdgeRadius; - private SerializedProperty m_UsedByComposite; - private readonly AnimBool m_ShowCompositeRedundants = new AnimBool(); - private readonly BoxBoundsHandle m_BoundsHandle = new BoxBoundsHandle(); - - protected override GUIContent editModeButton { get { return PrimitiveBoundsHandle.editModeButton; } } - - public override void OnEnable() - { - base.OnEnable(); - - m_Size = serializedObject.FindProperty("m_Size"); - m_EdgeRadius = serializedObject.FindProperty("m_EdgeRadius"); - m_BoundsHandle.axes = BoxBoundsHandle.Axes.X | BoxBoundsHandle.Axes.Y; - m_UsedByComposite = serializedObject.FindProperty("m_UsedByComposite"); - m_AutoTiling = serializedObject.FindProperty("m_AutoTiling"); - m_ShowCompositeRedundants.value = !m_UsedByComposite.boolValue; - m_ShowCompositeRedundants.valueChanged.AddListener(Repaint); - } - - public override void OnDisable() - { - base.OnDisable(); - - m_ShowCompositeRedundants.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - bool disableEditCollider = !CanEditCollider(); - if (disableEditCollider) - { - EditorGUILayout.HelpBox(Styles.s_ColliderEditDisableHelp.text, MessageType.Info); - if (editingCollider) - EditMode.QuitEditMode(); - } - else - InspectorEditButtonGUI(); - - base.OnInspectorGUI(); - - EditorGUILayout.PropertyField(m_Size); - - m_ShowCompositeRedundants.target = !m_UsedByComposite.boolValue; - if (EditorGUILayout.BeginFadeGroup(m_ShowCompositeRedundants.faded)) - EditorGUILayout.PropertyField(m_EdgeRadius); - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - - FinalizeInspectorGUI(); - } - - protected virtual void OnSceneGUI() - { - if (!editingCollider) - return; - - BoxCollider2D collider = (BoxCollider2D)target; - - if (Mathf.Approximately(collider.transform.lossyScale.sqrMagnitude, 0f)) - return; - - // collider matrix is 2d projection of transform's rotation onto x/y plane about transform's origin - Matrix4x4 handleMatrix = collider.transform.localToWorldMatrix; - handleMatrix.SetRow(0, Vector4.Scale(handleMatrix.GetRow(0), new Vector4(1f, 1f, 0f, 1f))); - handleMatrix.SetRow(1, Vector4.Scale(handleMatrix.GetRow(1), new Vector4(1f, 1f, 0f, 1f))); - handleMatrix.SetRow(2, new Vector4(0f, 0f, 1f, collider.transform.position.z)); - if (collider.usedByComposite && collider.composite != null) - { - // composite offset is rotated by composite's transformation matrix and projected back onto 2D plane - var compositeOffset = collider.composite.transform.rotation * collider.composite.offset; - compositeOffset.z = 0f; - handleMatrix = Matrix4x4.TRS(compositeOffset, Quaternion.identity, Vector3.one) * handleMatrix; - } - using (new Handles.DrawingScope(handleMatrix)) - { - m_BoundsHandle.center = collider.offset; - m_BoundsHandle.size = collider.size; - - m_BoundsHandle.SetColor(collider.enabled ? Handles.s_ColliderHandleColor : Handles.s_ColliderHandleColorDisabled); - EditorGUI.BeginChangeCheck(); - m_BoundsHandle.DrawHandle(); - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(collider, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); - - // test for size change after using property setter in case input data was sanitized - Vector2 oldSize = collider.size; - collider.size = m_BoundsHandle.size; - - // because projection of offset is a lossy operation, only do it if the size has actually changed - // this check prevents drifting while dragging handle when size is zero (case 863949) - if (collider.size != oldSize) - { - collider.offset = m_BoundsHandle.center; - } - } - } - } - } -} diff --git a/Editor/Mono/Inspector/BoxColliderEditor.cs b/Editor/Mono/Inspector/BoxColliderEditor.cs deleted file mode 100644 index f799393a69..0000000000 --- a/Editor/Mono/Inspector/BoxColliderEditor.cs +++ /dev/null @@ -1,61 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(BoxCollider))] - [CanEditMultipleObjects] - internal class BoxColliderEditor : PrimitiveCollider3DEditor - { - SerializedProperty m_Center; - SerializedProperty m_Size; - private readonly BoxBoundsHandle m_BoundsHandle = new BoxBoundsHandle(); - - protected GUIContent centerContent = EditorGUIUtility.TrTextContent("Center", "The position of the Collider in the object’s local space."); - protected GUIContent sizeContent = EditorGUIUtility.TrTextContent("Size", "The size of the Collider in the X, Y, Z directions."); - - - public override void OnEnable() - { - base.OnEnable(); - - m_Center = serializedObject.FindProperty("m_Center"); - m_Size = serializedObject.FindProperty("m_Size"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - InspectorEditButtonGUI(); - EditorGUILayout.PropertyField(m_IsTrigger, triggerContent); - EditorGUILayout.PropertyField(m_Material, materialContent); - EditorGUILayout.PropertyField(m_Center, centerContent); - EditorGUILayout.PropertyField(m_Size, sizeContent); - - serializedObject.ApplyModifiedProperties(); - } - - protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } - - protected override void CopyColliderPropertiesToHandle() - { - BoxCollider collider = (BoxCollider)target; - m_BoundsHandle.center = TransformColliderCenterToHandleSpace(collider.transform, collider.center); - m_BoundsHandle.size = Vector3.Scale(collider.size, collider.transform.lossyScale); - } - - protected override void CopyHandlePropertiesToCollider() - { - BoxCollider collider = (BoxCollider)target; - collider.center = TransformHandleCenterToColliderSpace(collider.transform, m_BoundsHandle.center); - Vector3 size = Vector3.Scale(m_BoundsHandle.size, InvertScaleVector(collider.transform.lossyScale)); - size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z)); - collider.size = size; - } - } -} diff --git a/Editor/Mono/Inspector/BuoyancyEffector2DEditor.cs b/Editor/Mono/Inspector/BuoyancyEffector2DEditor.cs deleted file mode 100644 index 02391f5c48..0000000000 --- a/Editor/Mono/Inspector/BuoyancyEffector2DEditor.cs +++ /dev/null @@ -1,143 +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.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor.AnimatedValues; - -namespace UnityEditor -{ - /// - /// Prompts the end-user to add 2D colliders if non exist for 2D effector to work with. - /// - [CustomEditor(typeof(BuoyancyEffector2D), true)] - [CanEditMultipleObjects] - internal class BuoyancyEffector2DEditor : Effector2DEditor - { - SerializedProperty m_Density; - SerializedProperty m_SurfaceLevel; - - static readonly AnimBool m_ShowDampingRollout = new AnimBool(); - SerializedProperty m_LinearDrag; - SerializedProperty m_AngularDrag; - - static readonly AnimBool m_ShowFlowRollout = new AnimBool(); - SerializedProperty m_FlowAngle; - SerializedProperty m_FlowMagnitude; - SerializedProperty m_FlowVariation; - - public override void OnEnable() - { - base.OnEnable(); - - m_Density = serializedObject.FindProperty("m_Density"); - m_SurfaceLevel = serializedObject.FindProperty("m_SurfaceLevel"); - - m_ShowDampingRollout.valueChanged.AddListener(Repaint); - m_LinearDrag = serializedObject.FindProperty("m_LinearDrag"); - m_AngularDrag = serializedObject.FindProperty("m_AngularDrag"); - - m_ShowFlowRollout.valueChanged.AddListener(Repaint); - m_FlowAngle = serializedObject.FindProperty("m_FlowAngle"); - m_FlowMagnitude = serializedObject.FindProperty("m_FlowMagnitude"); - m_FlowVariation = serializedObject.FindProperty("m_FlowVariation"); - } - - public override void OnDisable() - { - base.OnDisable(); - - m_ShowDampingRollout.valueChanged.RemoveListener(Repaint); - m_ShowFlowRollout.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_Density); - EditorGUILayout.PropertyField(m_SurfaceLevel); - - // Drag. - m_ShowDampingRollout.target = EditorGUILayout.Foldout(m_ShowDampingRollout.target, "Damping", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowDampingRollout.faded)) - { - EditorGUILayout.PropertyField(m_LinearDrag); - EditorGUILayout.PropertyField(m_AngularDrag); - EditorGUILayout.Space(); - } - EditorGUILayout.EndFadeGroup(); - - // Flow. - m_ShowFlowRollout.target = EditorGUILayout.Foldout(m_ShowFlowRollout.target, "Flow", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowFlowRollout.faded)) - { - EditorGUILayout.PropertyField(m_FlowAngle); - EditorGUILayout.PropertyField(m_FlowMagnitude); - EditorGUILayout.PropertyField(m_FlowVariation); - } - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - } - - public void OnSceneGUI() - { - var effector = (BuoyancyEffector2D)target; - - // Ignore disabled effector. - if (!effector.enabled) - return; - - - var effectorPosition = effector.transform.position; - var surfaceY = effectorPosition.y + (effector.transform.lossyScale.y * effector.surfaceLevel); - - var intersections = new List(); - var farLeft = float.NegativeInfinity; - var farRight = farLeft; - - // Fetch all the effector-collider bounds. - foreach (var c in effector.gameObject.GetComponents().Where(c => c.enabled && c.usedByEffector)) - { - var b = c.bounds; - var left = b.min.x; - var right = b.max.x; - if (float.IsNegativeInfinity(farLeft)) - { - farLeft = left; - farRight = right; - } - else - { - if (left < farLeft) - farLeft = left; - - if (right > farRight) - farRight = right; - } - - var start = new Vector3(left, surfaceY, 0.0f); - var end = new Vector3(right, surfaceY, 0.0f); - - intersections.Add(start); - intersections.Add(end); - } - - // Draw the overall surface. - Handles.color = Color.red; - Handles.DrawAAPolyLine(new Vector3[] { new Vector3(farLeft, surfaceY, 0.0f), new Vector3(farRight, surfaceY, 0.0f) }); - - // Draw the collider intersections. - Handles.color = Color.cyan; - for (var i = 0; i < intersections.Count - 1; i = i + 2) - { - Handles.DrawAAPolyLine(intersections[i], intersections[i + 1]); - } - } - } -} diff --git a/Editor/Mono/Inspector/CameraEditor.cs b/Editor/Mono/Inspector/CameraEditor.cs index 1cd244ae15..81e164090d 100644 --- a/Editor/Mono/Inspector/CameraEditor.cs +++ b/Editor/Mono/Inspector/CameraEditor.cs @@ -213,7 +213,7 @@ public void DrawProjection() GUIContent content = EditorGUI.BeginProperty(EditorGUILayout.BeginHorizontal(), Styles.fieldOfView, fieldOfView); EditorGUI.BeginDisabled(projectionMatrixMode.hasMultipleDifferentValues || isPhysicalCamera && (focalLength.hasMultipleDifferentValues || sensorSize.hasMultipleDifferentValues)); EditorGUI.BeginChangeCheck(); - float fovNewValue = EditorGUILayout.Slider(content, fieldOfView.floatValue, 1f, 179f); + float fovNewValue = EditorGUILayout.Slider(content, fieldOfView.floatValue, 0.00001f, 179f); bool fovChanged = EditorGUI.EndChangeCheck(); EditorGUI.EndDisabled(); EditorGUILayout.EndHorizontal(); diff --git a/Editor/Mono/Inspector/CapsuleCollider2DEditor.cs b/Editor/Mono/Inspector/CapsuleCollider2DEditor.cs deleted file mode 100644 index 574808d67d..0000000000 --- a/Editor/Mono/Inspector/CapsuleCollider2DEditor.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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(CapsuleCollider2D))] - [CanEditMultipleObjects] - internal class CapsuleCollider2DEditor : PrimitiveCollider2DEditor - { - private SerializedProperty m_Size; - private SerializedProperty m_Direction; - private readonly CapsuleBoundsHandle m_BoundsHandle = new CapsuleBoundsHandle(); - - public override void OnEnable() - { - base.OnEnable(); - - m_Size = serializedObject.FindProperty("m_Size"); - m_Direction = serializedObject.FindProperty("m_Direction"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - InspectorEditButtonGUI(); - - base.OnInspectorGUI(); - - EditorGUILayout.PropertyField(m_Size); - EditorGUILayout.PropertyField(m_Direction); - - serializedObject.ApplyModifiedProperties(); - - FinalizeInspectorGUI(); - } - - protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } - - protected override void CopyColliderSizeToHandle() - { - CapsuleCollider2D collider = (CapsuleCollider2D)target; - Vector3 handleHeightAxis, handleRadiusAxis; - GetHandleVectorsInWorldSpace(collider, out handleHeightAxis, out handleRadiusAxis); - m_BoundsHandle.height = m_BoundsHandle.radius = 0f; - m_BoundsHandle.height = handleHeightAxis.magnitude; - m_BoundsHandle.radius = handleRadiusAxis.magnitude * 0.5f; - } - - protected override bool CopyHandleSizeToCollider() - { - CapsuleCollider2D collider = (CapsuleCollider2D)target; - - // transform handle axes into world space - Vector3 localDiameterAxis, localHeightAxis; - if (collider.direction == CapsuleDirection2D.Horizontal) - { - localDiameterAxis = Vector3.up; - localHeightAxis = Vector3.right; - } - else - { - localDiameterAxis = Vector3.right; - localHeightAxis = Vector3.up; - } - Vector3 worldHeight = Handles.matrix * (localHeightAxis * m_BoundsHandle.height); - Vector3 worldDiameter = Handles.matrix * (localDiameterAxis * m_BoundsHandle.radius * 2f); - - // project collider's diameter and height axes onto world x/y plane and scale by handle values - Matrix4x4 colliderTransformMatrix = collider.transform.localToWorldMatrix; - Vector3 projectedDiameter = ProjectOntoWorldPlane(colliderTransformMatrix * localDiameterAxis).normalized * worldDiameter.magnitude; - Vector3 projectedHeight = ProjectOntoWorldPlane(colliderTransformMatrix * localHeightAxis).normalized * worldHeight.magnitude; - - // project results back in collider's local space - projectedDiameter = ProjectOntoColliderPlane(projectedDiameter, colliderTransformMatrix); - projectedHeight = ProjectOntoColliderPlane(projectedHeight, colliderTransformMatrix); - Vector2 oldSize = collider.size; - collider.size = colliderTransformMatrix.inverse * (projectedDiameter + projectedHeight); - - // test for size change after using property setter in case input data was sanitized - return collider.size != oldSize; - } - - protected override Quaternion GetHandleRotation() - { - Vector3 diameterVector, heightVector; - GetHandleVectorsInWorldSpace(target as CapsuleCollider2D, out heightVector, out diameterVector); - return Quaternion.LookRotation(Vector3.forward, heightVector); - } - - private void GetHandleVectorsInWorldSpace(CapsuleCollider2D collider, out Vector3 handleHeightVector, out Vector3 handleDiameterVector) - { - Matrix4x4 colliderTransformMatrix = collider.transform.localToWorldMatrix; - Vector3 x = ProjectOntoWorldPlane(colliderTransformMatrix * (Vector3.right * collider.size.x)); - Vector3 y = ProjectOntoWorldPlane(colliderTransformMatrix * (Vector3.up * collider.size.y)); - if (collider.direction == CapsuleDirection2D.Horizontal) - { - handleDiameterVector = y; - handleHeightVector = x; - } - else - { - handleDiameterVector = x; - handleHeightVector = y; - } - } - } -} diff --git a/Editor/Mono/Inspector/CapsuleColliderEditor.cs b/Editor/Mono/Inspector/CapsuleColliderEditor.cs deleted file mode 100644 index 2161128bd6..0000000000 --- a/Editor/Mono/Inspector/CapsuleColliderEditor.cs +++ /dev/null @@ -1,129 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(CapsuleCollider))] - [CanEditMultipleObjects] - internal class CapsuleColliderEditor : PrimitiveCollider3DEditor - { - SerializedProperty m_Center; - SerializedProperty m_Radius; - SerializedProperty m_Height; - SerializedProperty m_Direction; - - private readonly CapsuleBoundsHandle m_BoundsHandle = new CapsuleBoundsHandle(); - - public override void OnEnable() - { - base.OnEnable(); - - m_Center = serializedObject.FindProperty("m_Center"); - m_Radius = serializedObject.FindProperty("m_Radius"); - m_Height = serializedObject.FindProperty("m_Height"); - m_Direction = serializedObject.FindProperty("m_Direction"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - InspectorEditButtonGUI(); - EditorGUILayout.PropertyField(m_IsTrigger); - EditorGUILayout.PropertyField(m_Material); - EditorGUILayout.PropertyField(m_Center); - EditorGUILayout.PropertyField(m_Radius); - EditorGUILayout.PropertyField(m_Height); - EditorGUILayout.PropertyField(m_Direction); - - serializedObject.ApplyModifiedProperties(); - } - - protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } - - protected override void CopyColliderPropertiesToHandle() - { - CapsuleCollider collider = (CapsuleCollider)target; - m_BoundsHandle.center = TransformColliderCenterToHandleSpace(collider.transform, collider.center); - float radiusScaleFactor; - Vector3 sizeScale = - GetCapsuleColliderHandleScale(collider.transform.lossyScale, collider.direction, out radiusScaleFactor); - m_BoundsHandle.height = m_BoundsHandle.radius = 0f; - m_BoundsHandle.height = collider.height * Mathf.Abs(sizeScale[collider.direction]); - m_BoundsHandle.radius = collider.radius * radiusScaleFactor; - switch (collider.direction) - { - case 0: - m_BoundsHandle.heightAxis = CapsuleBoundsHandle.HeightAxis.X; - break; - case 1: - m_BoundsHandle.heightAxis = CapsuleBoundsHandle.HeightAxis.Y; - break; - case 2: - m_BoundsHandle.heightAxis = CapsuleBoundsHandle.HeightAxis.Z; - break; - } - } - - protected override void CopyHandlePropertiesToCollider() - { - CapsuleCollider collider = (CapsuleCollider)target; - collider.center = TransformHandleCenterToColliderSpace(collider.transform, m_BoundsHandle.center); - float radiusScaleFactor; - Vector3 sizeScale = - GetCapsuleColliderHandleScale(collider.transform.lossyScale, collider.direction, out radiusScaleFactor); - sizeScale = InvertScaleVector(sizeScale); - // only apply changes to collider radius/height if scale factor from transform is non-zero - if (radiusScaleFactor != 0f) - collider.radius = m_BoundsHandle.radius / radiusScaleFactor; - if (sizeScale[collider.direction] != 0f) - collider.height = m_BoundsHandle.height * Mathf.Abs(sizeScale[collider.direction]); - } - - protected override void OnSceneGUI() - { - // prevent possibility that user increases height if radius scale is zero and user drags (non-moving) radius handles to exceed height extents - CapsuleCollider collider = (CapsuleCollider)target; - float radiusScaleFactor; - GetCapsuleColliderHandleScale(collider.transform.lossyScale, collider.direction, out radiusScaleFactor); - boundsHandle.axes = PrimitiveBoundsHandle.Axes.All; - if (radiusScaleFactor == 0f) - { - switch (collider.direction) - { - case 0: - boundsHandle.axes = PrimitiveBoundsHandle.Axes.X; - break; - case 1: - boundsHandle.axes = PrimitiveBoundsHandle.Axes.Y; - break; - case 2: - boundsHandle.axes = PrimitiveBoundsHandle.Axes.Z; - break; - } - } - - base.OnSceneGUI(); - } - - private Vector3 GetCapsuleColliderHandleScale(Vector3 lossyScale, int capsuleDirection, out float radiusScaleFactor) - { - radiusScaleFactor = 0f; - for (int axis = 0; axis < 3; ++axis) - { - if (axis != capsuleDirection) - radiusScaleFactor = Mathf.Max(radiusScaleFactor, Mathf.Abs(lossyScale[axis])); - } - for (int axis = 0; axis < 3; ++axis) - { - if (axis != capsuleDirection) - lossyScale[axis] = Mathf.Sign(lossyScale[axis]) * radiusScaleFactor; - } - return lossyScale; - } - } -} diff --git a/Editor/Mono/Inspector/CharacterControllerEditor.cs b/Editor/Mono/Inspector/CharacterControllerEditor.cs deleted file mode 100644 index a300b6ab98..0000000000 --- a/Editor/Mono/Inspector/CharacterControllerEditor.cs +++ /dev/null @@ -1,165 +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; - -namespace UnityEditor -{ - [CustomEditor(typeof(CharacterController))] - [CanEditMultipleObjects] - internal class CharacterControllerEditor : Editor - { - SerializedProperty m_Height; - SerializedProperty m_Radius; - SerializedProperty m_SlopeLimit; - SerializedProperty m_StepOffset; - SerializedProperty m_SkinWidth; - SerializedProperty m_MinMoveDistance; - SerializedProperty m_Center; - - private int m_HandleControlID; - - public void OnEnable() - { - m_Height = serializedObject.FindProperty("m_Height"); - m_Radius = serializedObject.FindProperty("m_Radius"); - m_SlopeLimit = serializedObject.FindProperty("m_SlopeLimit"); - m_StepOffset = serializedObject.FindProperty("m_StepOffset"); - m_SkinWidth = serializedObject.FindProperty("m_SkinWidth"); - m_MinMoveDistance = serializedObject.FindProperty("m_MinMoveDistance"); - m_Center = serializedObject.FindProperty("m_Center"); - - m_HandleControlID = -1; - } - - public void OnDisable() - { - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_SlopeLimit); - EditorGUILayout.PropertyField(m_StepOffset); - EditorGUILayout.PropertyField(m_SkinWidth); - EditorGUILayout.PropertyField(m_MinMoveDistance); - - EditorGUILayout.PropertyField(m_Center); - EditorGUILayout.PropertyField(m_Radius); - EditorGUILayout.PropertyField(m_Height); - - serializedObject.ApplyModifiedProperties(); - } - - public void OnSceneGUI() - { - bool dragging = GUIUtility.hotControl == m_HandleControlID; - - CharacterController cc = (CharacterController)target; - - // Use our own color for handles - Color tempColor = Handles.color; - if (cc.enabled) - Handles.color = Handles.s_ColliderHandleColor; - else - Handles.color = Handles.s_ColliderHandleColorDisabled; - - bool orgGuiEnabled = GUI.enabled; - if (!Event.current.shift && !dragging) - { - GUI.enabled = false; - Handles.color = new Color(1, 0, 0, .001f); - } - - float height = cc.height * cc.transform.lossyScale.y; - float radius = cc.radius * Mathf.Max(cc.transform.lossyScale.x, cc.transform.lossyScale.z); - height = Mathf.Max(height, radius * 2); - - Matrix4x4 matrix = Matrix4x4.TRS(cc.transform.TransformPoint(cc.center), Quaternion.identity, Vector3.one); - - int prevHotControl = GUIUtility.hotControl; - - // Height (two handles) - Vector3 halfHeight = Vector3.up * height * 0.5f; - float adjusted = SizeHandle(halfHeight, Vector3.up, matrix, true); - if (!GUI.changed) - adjusted = SizeHandle(-halfHeight, Vector3.down, matrix, true); - if (GUI.changed) - { - Undo.RecordObject(cc, "Character Controller Resize"); - float heightScale = height / cc.height; - cc.height += adjusted / heightScale; - } - - // Radius (four handles) - adjusted = SizeHandle(Vector3.left * radius, Vector3.left, matrix, true); - if (!GUI.changed) - adjusted = SizeHandle(-Vector3.left * radius, -Vector3.left, matrix, true); - if (!GUI.changed) - adjusted = SizeHandle(Vector3.forward * radius, Vector3.forward, matrix, true); - if (!GUI.changed) - adjusted = SizeHandle(-Vector3.forward * radius, -Vector3.forward, matrix, true); - if (GUI.changed) - { - Undo.RecordObject(cc, "Character Controller Resize"); - float radiusScale = radius / cc.radius; - cc.radius += adjusted / radiusScale; - } - - // Detect if any of our handles got hotcontrol - if (prevHotControl != GUIUtility.hotControl && GUIUtility.hotControl != 0) - m_HandleControlID = GUIUtility.hotControl; - - if (GUI.changed) - { - const float minValue = 0.00001f; - cc.radius = Mathf.Max(cc.radius, minValue); - cc.height = Mathf.Max(cc.height, minValue); - } - - // Reset original color - Handles.color = tempColor; - GUI.enabled = orgGuiEnabled; - } - - private static float SizeHandle(Vector3 localPos, Vector3 localPullDir, Matrix4x4 matrix, bool isEdgeHandle) - { - Vector3 worldDir = matrix.MultiplyVector(localPullDir); - Vector3 worldPos = matrix.MultiplyPoint(localPos); - - float handleSize = HandleUtility.GetHandleSize(worldPos); - bool orgGUIchanged = GUI.changed; - GUI.changed = false; - Color tempColor = Handles.color; - - // Adjust color of handle if in background - float displayThreshold = 0.0f; - if (isEdgeHandle) - displayThreshold = Mathf.Cos(Mathf.PI * 0.25f); - float cosV; - if (Camera.current.orthographic) - cosV = Vector3.Dot(-Camera.current.transform.forward, worldDir); - else - cosV = Vector3.Dot((Camera.current.transform.position - worldPos).normalized, worldDir); - if (cosV < -displayThreshold) - Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * Handles.backfaceAlphaMultiplier); - - // Now do handle - Vector3 newWorldPos = Handles.Slider(worldPos, worldDir, handleSize * 0.03f, Handles.DotHandleCap, 0f); - float adjust = 0.0f; - if (GUI.changed) - { - // Project newWorldPos to worldDir (the sign of the return value indicates if we growing or shrinking) - adjust = HandleUtility.PointOnLineParameter(newWorldPos, worldPos, worldDir); - } - - // Reset states - GUI.changed |= orgGUIchanged; - Handles.color = tempColor; - - return adjust; - } - } -} diff --git a/Editor/Mono/Inspector/CharacterJointEditor.cs b/Editor/Mono/Inspector/CharacterJointEditor.cs deleted file mode 100644 index 739a17d697..0000000000 --- a/Editor/Mono/Inspector/CharacterJointEditor.cs +++ /dev/null @@ -1,64 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(CharacterJoint)), CanEditMultipleObjects] - class CharacterJointEditor : JointEditor - { - protected override void DoAngularLimitHandles(CharacterJoint joint) - { - base.DoAngularLimitHandles(joint); - - angularLimitHandle.xMotion = ConfigurableJointMotion.Limited; - angularLimitHandle.yMotion = ConfigurableJointMotion.Limited; - angularLimitHandle.zMotion = ConfigurableJointMotion.Limited; - - SoftJointLimit limit; - - limit = joint.lowTwistLimit; - angularLimitHandle.xMin = limit.limit; - - limit = joint.highTwistLimit; - angularLimitHandle.xMax = limit.limit; - - limit = joint.swing1Limit; - angularLimitHandle.yMax = limit.limit; - angularLimitHandle.yMin = -limit.limit; - - limit = joint.swing2Limit; - angularLimitHandle.zMax = limit.limit; - angularLimitHandle.zMin = -limit.limit; - - EditorGUI.BeginChangeCheck(); - - angularLimitHandle.radius = GetAngularLimitHandleSize(Vector3.zero); - angularLimitHandle.DrawHandle(); - - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(joint, Styles.editAngularLimitsUndoMessage); - - limit = joint.lowTwistLimit; - limit.limit = angularLimitHandle.xMin; - joint.lowTwistLimit = limit; - - limit = joint.highTwistLimit; - limit.limit = angularLimitHandle.xMax; - joint.highTwistLimit = limit; - - limit = joint.swing1Limit; - limit.limit = angularLimitHandle.yMax == limit.limit ? -angularLimitHandle.yMin : angularLimitHandle.yMax; - joint.swing1Limit = limit; - - limit = joint.swing2Limit; - limit.limit = angularLimitHandle.zMax == limit.limit ? -angularLimitHandle.zMin : angularLimitHandle.zMax; - joint.swing2Limit = limit; - } - } - } -} diff --git a/Editor/Mono/Inspector/CircleCollider2DEditor.cs b/Editor/Mono/Inspector/CircleCollider2DEditor.cs deleted file mode 100644 index fa374e02c7..0000000000 --- a/Editor/Mono/Inspector/CircleCollider2DEditor.cs +++ /dev/null @@ -1,66 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(CircleCollider2D))] - [CanEditMultipleObjects] - internal class CircleCollider2DEditor : PrimitiveCollider2DEditor - { - private SerializedProperty m_Radius; - private readonly SphereBoundsHandle m_BoundsHandle = new SphereBoundsHandle(); - - public override void OnEnable() - { - base.OnEnable(); - - m_Radius = serializedObject.FindProperty("m_Radius"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - InspectorEditButtonGUI(); - - base.OnInspectorGUI(); - - EditorGUILayout.PropertyField(m_Radius); - - serializedObject.ApplyModifiedProperties(); - - FinalizeInspectorGUI(); - } - - protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } - - protected override void CopyColliderSizeToHandle() - { - CircleCollider2D collider = (CircleCollider2D)target; - m_BoundsHandle.radius = collider.radius * GetRadiusScaleFactor(); - } - - protected override bool CopyHandleSizeToCollider() - { - CircleCollider2D collider = (CircleCollider2D)target; - - float oldRadius = collider.radius; - float scaleFactor = GetRadiusScaleFactor(); - collider.radius = - Mathf.Approximately(scaleFactor, 0f) ? 0f : m_BoundsHandle.radius / GetRadiusScaleFactor(); - - // test for size change after using property setter in case input data was sanitized - return collider.radius != oldRadius; - } - - private float GetRadiusScaleFactor() - { - Vector3 lossyScale = ((Component)target).transform.lossyScale; - return Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.y)); - } - } -} diff --git a/Editor/Mono/Inspector/Collider3DEditorBase.cs b/Editor/Mono/Inspector/Collider3DEditorBase.cs deleted file mode 100644 index 79fb55a870..0000000000 --- a/Editor/Mono/Inspector/Collider3DEditorBase.cs +++ /dev/null @@ -1,34 +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; - -namespace UnityEditor -{ - internal class Collider3DEditorBase : ColliderEditorBase - { - protected SerializedProperty m_Material; - protected SerializedProperty m_IsTrigger; - - protected GUIContent materialContent = EditorGUIUtility.TrTextContent("Material", "Reference to the Physic Material that determines how this Collider interacts with others."); - protected GUIContent triggerContent = EditorGUIUtility.TrTextContent("Is Trigger", "If enabled, this Collider is used for triggering events and is ignored by the physics engine."); - - public override void OnEnable() - { - base.OnEnable(); - m_Material = serializedObject.FindProperty("m_Material"); - m_IsTrigger = serializedObject.FindProperty("m_IsTrigger"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_IsTrigger, triggerContent); - EditorGUILayout.PropertyField(m_Material, materialContent); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/ComputeShaderInspector.cs b/Editor/Mono/Inspector/ComputeShaderInspector.cs deleted file mode 100644 index 23d7b1c800..0000000000 --- a/Editor/Mono/Inspector/ComputeShaderInspector.cs +++ /dev/null @@ -1,108 +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.Rendering; -using System.Collections.Generic; -using System.Globalization; - -namespace UnityEditor -{ - [CustomEditor(typeof(ComputeShader))] - internal class ComputeShaderInspector : Editor - { - private const float kSpace = 5f; - Vector2 m_ScrollPosition = Vector2.zero; - - // Compute kernel information is stored split by platform, then by kernels; - // but for the inspector we want to show kernels, then platforms they are in. - class KernelInfo - { - internal string name; - internal string platforms; - }; - - internal class Styles - { - public static GUIContent showCompiled = EditorGUIUtility.TrTextContent("Show compiled code"); - public static GUIContent kernelsHeading = EditorGUIUtility.TrTextContent("Kernels:"); - } - - static List GetKernelDisplayInfo(ComputeShader cs) - { - var kernelInfo = new List(); - var platformCount = ShaderUtil.GetComputeShaderPlatformCount(cs); - for (var i = 0; i < platformCount; ++i) - { - var platform = ShaderUtil.GetComputeShaderPlatformType(cs, i); - var kernelCount = ShaderUtil.GetComputeShaderPlatformKernelCount(cs, i); - for (var j = 0; j < kernelCount; ++j) - { - var kernelName = ShaderUtil.GetComputeShaderPlatformKernelName(cs, i, j); - var found = false; - foreach (var ki in kernelInfo) - { - if (ki.name == kernelName) - { - ki.platforms += ' '; - ki.platforms += platform.ToString(); - found = true; - } - } - if (!found) - { - var ki = new KernelInfo(); - ki.name = kernelName; - ki.platforms = platform.ToString(); - kernelInfo.Add(ki); - } - } - } - return kernelInfo; - } - - public override void OnInspectorGUI() - { - var cs = target as ComputeShader; - if (cs == null) - return; - - GUI.enabled = true; - - EditorGUI.indentLevel = 0; - - ShowKernelInfoSection(cs); - ShowCompiledCodeSection(cs); - ShowShaderErrors(cs); - } - - private void ShowKernelInfoSection(ComputeShader cs) - { - GUILayout.Label(Styles.kernelsHeading, EditorStyles.boldLabel); - var kernelInfo = GetKernelDisplayInfo(cs); - foreach (var ki in kernelInfo) - { - EditorGUILayout.LabelField(ki.name, ki.platforms); - } - } - - private void ShowCompiledCodeSection(ComputeShader cs) - { - GUILayout.Space(kSpace); - if (GUILayout.Button(Styles.showCompiled, EditorStyles.miniButton, GUILayout.ExpandWidth(false))) - { - ShaderUtil.OpenCompiledComputeShader(cs, true); - GUIUtility.ExitGUI(); - } - } - - private void ShowShaderErrors(ComputeShader s) - { - int n = ShaderUtil.GetComputeShaderErrorCount(s); - if (n < 1) - return; - ShaderInspector.ShaderErrorListUI(s, ShaderUtil.GetComputeShaderErrors(s), ref m_ScrollPosition); - } - } -} diff --git a/Editor/Mono/Inspector/CubemapPreview.cs b/Editor/Mono/Inspector/CubemapPreview.cs deleted file mode 100644 index 0b2a878a4b..0000000000 --- a/Editor/Mono/Inspector/CubemapPreview.cs +++ /dev/null @@ -1,208 +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.Globalization; -using UnityEngine; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class CubemapPreview - { - private enum PreviewType - { - RGB = 0, - Alpha = 1 - } - // Preview settings - [SerializeField] - private PreviewType m_PreviewType = PreviewType.RGB; - [SerializeField] - float m_MipLevel = 0.0F; - private float m_Intensity = 1.0f; - - // Cached preview data - private PreviewRenderUtility m_PreviewUtility; - private Mesh m_Mesh; - public Vector2 m_PreviewDir = new Vector2(0, 0); - - static class Styles - { - public static GUIStyle preButton = "preButton"; - public static GUIStyle preSlider = "preSlider"; - public static GUIStyle preSliderThumb = "preSliderThumb"; - public static GUIStyle preLabel = "preLabel"; - public static GUIContent smallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); - public static GUIContent largeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); - public static GUIContent alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); - public static GUIContent RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); - } - - public void OnDisable() - { - if (m_PreviewUtility != null) - { - m_PreviewUtility.Cleanup(); - m_PreviewUtility = null; - } - } - - public float mipLevel { get { return m_MipLevel; } set { m_MipLevel = value; } } - - // For mip maps we render by default with mipLevel 0 but allow for - public float GetMipLevelForRendering(Texture texture) - { - return Mathf.Min(m_MipLevel, TextureUtil.GetMipmapCount(texture)); - } - - public void SetIntensity(float intensity) - { - m_Intensity = intensity; - } - - void InitPreview() - { - // Initialized? - if (m_PreviewUtility != null) - return; - - m_PreviewUtility = new PreviewRenderUtility(); - m_PreviewUtility.camera.fieldOfView = 15f; - m_Mesh = PreviewRenderUtility.GetPreviewSphere(); - } - - public void OnPreviewSettings(Object[] targets) - { - if (!ShaderUtil.hardwareSupportsRectRenderTexture) - return; - GUI.enabled = true; - InitPreview(); - - bool showMode = true; - bool alphaOnly = true; - //@TODO: Share some code with texture inspector??? - bool hasAlpha = false; - int mipCount = 8; - foreach (Texture t2 in targets) - { - mipCount = Mathf.Max(mipCount, TextureUtil.GetMipmapCount(t2)); - - Cubemap cubemap = t2 as Cubemap; - if (cubemap) - { - TextureFormat format = cubemap.format; - if (!TextureUtil.IsAlphaOnlyTextureFormat(format)) - alphaOnly = false; - if (TextureUtil.HasAlphaTextureFormat(format)) - { - TextureUsageMode mode = TextureUtil.GetUsageMode(t2); - if (mode == TextureUsageMode.Default) // all other texture usage modes don't displayable alpha - hasAlpha = true; - } - } - else - { - hasAlpha = true; - alphaOnly = false; - } - } - - if (alphaOnly) - { - m_PreviewType = PreviewType.Alpha; - showMode = false; - } - else if (!hasAlpha) - { - m_PreviewType = PreviewType.RGB; - showMode = false; - } - - if (showMode) - { - GUIContent[] kPreviewIcons = { Styles.RGBIcon, Styles.alphaIcon }; - int index = (int)m_PreviewType; - if (GUILayout.Button(kPreviewIcons[index], Styles.preButton)) - m_PreviewType = (PreviewType)(++index % kPreviewIcons.Length); - } - - GUI.enabled = (mipCount != 1); - GUILayout.Box(Styles.smallZoom, Styles.preLabel); - GUI.changed = false; - m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(m_MipLevel, mipCount - 1, 0, Styles.preSlider, Styles.preSliderThumb, GUILayout.MaxWidth(64))); - GUILayout.Box(Styles.largeZoom, Styles.preLabel); - GUI.enabled = true; - } - - public void OnPreviewGUI(Texture t, Rect r, GUIStyle background) - { - if (t == null) - return; - - if (!ShaderUtil.hardwareSupportsRectRenderTexture) - { - if (Event.current.type == EventType.Repaint) - EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40), "Cubemap preview requires\nrender texture support"); - return; - } - - m_PreviewDir = PreviewGUI.Drag2D(m_PreviewDir, r); - - if (Event.current.type != EventType.Repaint) - return; - - InitPreview(); - m_PreviewUtility.BeginPreview(r, background); - const float previewDistance = 6.0f; - - RenderCubemap(t, m_PreviewDir, previewDistance); - - Texture renderedTexture = m_PreviewUtility.EndPreview(); - GUI.DrawTexture(r, renderedTexture, ScaleMode.StretchToFill, false); - - if (mipLevel != 0) - EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20), "Mip " + mipLevel); - } - - public Texture2D RenderStaticPreview(Texture t, int width, int height) - { - if (!ShaderUtil.hardwareSupportsRectRenderTexture) - return null; - - InitPreview(); - m_PreviewUtility.BeginStaticPreview(new Rect(0, 0, width, height)); - const float previewDistance = 5.3f; - Vector2 previewDirection = new Vector2(0, 0); - - // When rendering the cubemap preview we don't need lighting so we provide a custom list with no lights. - // If we don't do this and we are generating the preview for a point light cookie, if a light uses this cookie it will try to bind it which result in internal assert in AssetDatabase due to using the texture while building it. - m_PreviewUtility.ambientColor = Color.black; - - RenderCubemap(t, previewDirection, previewDistance); - - return m_PreviewUtility.EndStaticPreview(); - } - - private void RenderCubemap(Texture t, Vector2 previewDir, float previewDistance) - { - m_PreviewUtility.camera.transform.position = -Vector3.forward * previewDistance; - m_PreviewUtility.camera.transform.rotation = Quaternion.identity; - Quaternion rot = Quaternion.Euler(previewDir.y, 0, 0) * Quaternion.Euler(0, previewDir.x, 0); - - var mat = EditorGUIUtility.LoadRequired("Previews/PreviewCubemapMaterial.mat") as Material; - mat.mainTexture = t; - - mat.SetMatrix("_CubemapRotation", Matrix4x4.TRS(Vector3.zero, rot, Vector3.one)); - - // -1 indicates "use regular sampling"; mips 0 and larger sample only that mip level for preview - float mipLevel = GetMipLevelForRendering(t); - mat.SetFloat("_Mip", mipLevel); - mat.SetFloat("_Alpha", (m_PreviewType == PreviewType.Alpha) ? 1.0f : 0.0f); - mat.SetFloat("_Intensity", m_Intensity); - - m_PreviewUtility.DrawMesh(m_Mesh, Vector3.zero, rot, mat, 0); - m_PreviewUtility.Render(); - } - } -} diff --git a/Editor/Mono/Inspector/CustomPreviewAttribute.cs b/Editor/Mono/Inspector/CustomPreviewAttribute.cs deleted file mode 100644 index 37e365e08a..0000000000 --- a/Editor/Mono/Inspector/CustomPreviewAttribute.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 -{ - // Tells a custom [[IPreviewable]] which run-time [[Serializable]] class or [[PropertyAttribute]] it's a drawer for. - [System.AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] - public sealed class CustomPreviewAttribute : Attribute - { - internal Type m_Type; - - // Tells a PropertyDrawer class which run-time class or attribute it's a drawer for. - public CustomPreviewAttribute(Type type) - { - m_Type = type; - } - } -} diff --git a/Editor/Mono/Inspector/DistanceJoint2DEditor.cs b/Editor/Mono/Inspector/DistanceJoint2DEditor.cs deleted file mode 100644 index 8ee81b7cc4..0000000000 --- a/Editor/Mono/Inspector/DistanceJoint2DEditor.cs +++ /dev/null @@ -1,35 +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 -{ - [CustomEditor(typeof(DistanceJoint2D))] - [CanEditMultipleObjects] - internal class DistanceJoint2DEditor : AnchoredJoint2DEditor - { - new public void OnSceneGUI() - { - var distanceJoint2D = (DistanceJoint2D)target; - - // Ignore disabled joint. - if (!distanceJoint2D.enabled) - return; - - // Start and end points for distance gizmo - Vector3 anchor = TransformPoint(distanceJoint2D.transform, distanceJoint2D.anchor); - Vector3 connectedAnchor = distanceJoint2D.connectedAnchor; - - // If connectedBody present, convert the position to match that - if (distanceJoint2D.connectedBody) - connectedAnchor = TransformPoint(distanceJoint2D.connectedBody.transform, connectedAnchor); - - DrawDistanceGizmo(anchor, connectedAnchor, distanceJoint2D.distance); - - base.OnSceneGUI(); - } - } -} diff --git a/Editor/Mono/Inspector/DoubleCurvePresetLibraryInspector.cs b/Editor/Mono/Inspector/DoubleCurvePresetLibraryInspector.cs deleted file mode 100644 index 4c17a55e18..0000000000 --- a/Editor/Mono/Inspector/DoubleCurvePresetLibraryInspector.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 System; -using System.IO; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(DoubleCurvePresetLibrary))] - internal class DoubleCurvePresetLibraryEditor : Editor - { - private GenericPresetLibraryInspector m_GenericPresetLibraryInspector; - - public void OnEnable() - { - m_GenericPresetLibraryInspector = new GenericPresetLibraryInspector(target, GetHeader(), null); - m_GenericPresetLibraryInspector.presetSize = new Vector2(72, 20); - m_GenericPresetLibraryInspector.lineSpacing = 5f; - } - - private string GetHeader() - { - return "Particle Curve Preset Library"; - } - - public void OnDestroy() - { - if (m_GenericPresetLibraryInspector != null) - m_GenericPresetLibraryInspector.OnDestroy(); - } - - public override void OnInspectorGUI() - { - if (m_GenericPresetLibraryInspector != null) - m_GenericPresetLibraryInspector.OnInspectorGUI(); - } - } -} // namespace diff --git a/Editor/Mono/Inspector/EdgeCollider2DEditor.cs b/Editor/Mono/Inspector/EdgeCollider2DEditor.cs deleted file mode 100644 index 1819ae59fd..0000000000 --- a/Editor/Mono/Inspector/EdgeCollider2DEditor.cs +++ /dev/null @@ -1,65 +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 System; - -namespace UnityEditor -{ - [CustomEditor(typeof(EdgeCollider2D))] - [CanEditMultipleObjects] - internal class EdgeCollider2DEditor : Collider2DEditorBase - { - private PolygonEditorUtility m_PolyUtility = new PolygonEditorUtility(); - - private SerializedProperty m_EdgeRadius; - private SerializedProperty m_Points; - - public override void OnEnable() - { - base.OnEnable(); - - m_EdgeRadius = serializedObject.FindProperty("m_EdgeRadius"); - m_Points = serializedObject.FindProperty("m_Points"); - m_Points.isExpanded = false; - } - - public override void OnInspectorGUI() - { - BeginColliderInspector(); - base.OnInspectorGUI(); - - EditorGUILayout.PropertyField(m_EdgeRadius); - - if (targets.Length == 1) - { - EditorGUI.BeginDisabledGroup(editingCollider); - EditorGUILayout.PropertyField(m_Points, true); - EditorGUI.EndDisabledGroup(); - } - - EndColliderInspector(); - - FinalizeInspectorGUI(); - } - - protected override void OnEditStart() - { - m_PolyUtility.StartEditing(target as Collider2D); - } - - protected override void OnEditEnd() - { - m_PolyUtility.StopEditing(); - } - - public void OnSceneGUI() - { - if (!editingCollider) - return; - - m_PolyUtility.OnSceneGUI(); - } - } -} diff --git a/Editor/Mono/Inspector/Effector2DEditor.cs b/Editor/Mono/Inspector/Effector2DEditor.cs deleted file mode 100644 index 47e495d96e..0000000000 --- a/Editor/Mono/Inspector/Effector2DEditor.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 System.Linq; -using UnityEditor.AnimatedValues; -using UnityEngine; - -namespace UnityEditor -{ - /// - /// Prompts the end-user to add 2D colliders if non exist for 2D effector to work with. - /// - [CustomEditor(typeof(Effector2D), true)] - [CanEditMultipleObjects] - internal class Effector2DEditor : Editor - { - SerializedProperty m_UseColliderMask; - SerializedProperty m_ColliderMask; - readonly AnimBool m_ShowColliderMask = new AnimBool(); - - public virtual void OnEnable() - { - m_UseColliderMask = serializedObject.FindProperty("m_UseColliderMask"); - m_ColliderMask = serializedObject.FindProperty("m_ColliderMask"); - - m_ShowColliderMask.value = (target as Effector2D).useColliderMask; - m_ShowColliderMask.valueChanged.AddListener(Repaint); - } - - public virtual void OnDisable() - { - m_ShowColliderMask.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - // Fetch the effector. - var effector = target as Effector2D; - - // Update collider-mask fade-group. - m_ShowColliderMask.target = effector.useColliderMask; - - EditorGUILayout.PropertyField(m_UseColliderMask); - if (EditorGUILayout.BeginFadeGroup(m_ShowColliderMask.faded)) - EditorGUILayout.PropertyField(m_ColliderMask); - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - - // Finish if any enabled 2D colliders used by the effector exist. - if (effector.GetComponents().Any(collider => collider.enabled && collider.usedByEffector)) - return; - - // Show appropriate feedback. - if (effector.requiresCollider) - EditorGUILayout.HelpBox("This effector will not function until there is at least one enabled 2D collider with 'Used by Effector' checked on this GameObject.", MessageType.Warning); - else - EditorGUILayout.HelpBox("This effector can optionally work without a 2D collider.", MessageType.Info); - } - - /// - /// Checks collider types for compatibility warnings. - /// - /// - public static void CheckEffectorWarnings(Collider2D collider) - { - // Finish if the collider is not used by the effector. - if (!collider.usedByEffector || collider.usedByComposite) - return; - - // Fetch the effector. - var effector = collider.GetComponent(); - - // Warning if there's no effector or it's not enabled. - if (effector == null || !effector.enabled) - { - // Show warning. - EditorGUILayout.HelpBox("This collider will not function with an effector until there is at least one enabled 2D effector on this GameObject.", MessageType.Warning); - - // Finish if there was no effector. - if (effector == null) - return; - } - - // Handle collision/trigger effector preferences. - if (effector.designedForNonTrigger && collider.isTrigger) - { - // Show warning. - EditorGUILayout.HelpBox("This collider has 'Is Trigger' checked but this should be unchecked when used with the '" + effector.GetType().Name + "' component which is designed to work with collisions.", MessageType.Warning); - } - else if (effector.designedForTrigger && !collider.isTrigger) - { - // Show warning. - EditorGUILayout.HelpBox("This collider has 'Is Trigger' unchecked but this should be checked when used with the '" + effector.GetType().Name + "' component which is designed to work with triggers.", MessageType.Warning); - } - } - } -} diff --git a/Editor/Mono/Inspector/FontInspector.cs b/Editor/Mono/Inspector/FontInspector.cs deleted file mode 100644 index 359735a891..0000000000 --- a/Editor/Mono/Inspector/FontInspector.cs +++ /dev/null @@ -1,30 +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 UnityEditor; - - -namespace UnityEditor -{ - [CustomEditor(typeof(Font))] - [CanEditMultipleObjects] - internal class FontInspector : Editor - { - public override void OnInspectorGUI() - { - foreach (Object o in targets) - { - // Dont draw the default inspector for imported font assets. - // It can be very slow when there is a lot of embedded font data, - // and the presented information is not useful to the user anyways. - // We still need it for editable, "Custom Font" assets, though. - if (o.hideFlags == HideFlags.NotEditable) - return; - } - - DrawDefaultInspector(); - } - } -} diff --git a/Editor/Mono/Inspector/GameObjectInspector.cs b/Editor/Mono/Inspector/GameObjectInspector.cs index bb5d9782ce..ef7ccf6d4f 100644 --- a/Editor/Mono/Inspector/GameObjectInspector.cs +++ b/Editor/Mono/Inspector/GameObjectInspector.cs @@ -131,11 +131,14 @@ public void Dispose() Dictionary m_PreviewInstances = new Dictionary(); + bool m_PlayModeObjects; bool m_IsAsset; bool m_ImmutableSelf; bool m_ImmutableSourceAsset; - bool m_IsPrefabInstanceAnyRoot = false; - bool m_IsPrefabInstanceOutermostRoot = false; + bool m_IsDisconnected; + bool m_IsMissing; + bool m_IsPrefabInstanceAnyRoot; + bool m_IsPrefabInstanceOutermostRoot; bool m_AllOfSamePrefabType = true; public void OnEnable() @@ -157,8 +160,14 @@ public void OnEnable() void CalculatePrefabStatus() { - m_IsPrefabInstanceAnyRoot = false; + m_PlayModeObjects = false; m_IsAsset = false; + m_ImmutableSelf = false; + m_ImmutableSourceAsset = false; + m_IsDisconnected = false; + m_IsMissing = false; + m_IsPrefabInstanceAnyRoot = true; + m_IsPrefabInstanceOutermostRoot = true; m_AllOfSamePrefabType = true; PrefabAssetType firstType = PrefabUtility.GetPrefabAssetType(targets[0]); PrefabInstanceStatus firstStatus = PrefabUtility.GetPrefabInstanceStatus(targets[0]); @@ -170,17 +179,23 @@ void CalculatePrefabStatus() if (type != firstType || status != firstStatus) m_AllOfSamePrefabType = false; - if (PrefabUtility.IsAnyPrefabInstanceRoot(go)) - m_IsPrefabInstanceAnyRoot = true; - if (m_IsPrefabInstanceAnyRoot) - m_IsPrefabInstanceOutermostRoot = PrefabUtility.IsOutermostPrefabInstanceRoot(go); + if (Application.IsPlaying(go)) + m_PlayModeObjects = true; + if (!PrefabUtility.IsAnyPrefabInstanceRoot(go)) + m_IsPrefabInstanceAnyRoot = false; // Conservative is false if any is false + if (!m_IsPrefabInstanceAnyRoot || !PrefabUtility.IsOutermostPrefabInstanceRoot(go)) + m_IsPrefabInstanceOutermostRoot = false; // Conservative is false if any is false if (PrefabUtility.IsPartOfPrefabAsset(go)) - m_IsAsset = true; + m_IsAsset = true; // Conservative is true if any is true if (m_IsAsset && PrefabUtility.IsPartOfImmutablePrefab(go)) - m_ImmutableSelf = true; + m_ImmutableSelf = true; // Conservative is true if any is true GameObject originalSourceOrVariant = PrefabUtility.GetOriginalSourceOrVariantRoot(go); if (originalSourceOrVariant != null && PrefabUtility.IsPartOfImmutablePrefab(originalSourceOrVariant)) - m_ImmutableSourceAsset = true; + m_ImmutableSourceAsset = true; // Conservative is true if any is true + if (PrefabUtility.IsDisconnectedFromPrefabAsset(go)) + m_IsDisconnected = true; + if (PrefabUtility.IsPrefabAssetMissing(go)) + m_IsMissing = true; } } @@ -298,7 +313,7 @@ internal bool DrawInspector() // Prefab Toolbar if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None) { - DoPrefabButtons(go); + DoPrefabButtons(); } serializedObject.ApplyModifiedProperties(); @@ -306,19 +321,18 @@ internal bool DrawInspector() return true; } - private void DoPrefabButtons(GameObject go) + private void DoPrefabButtons() { - // @TODO: If/when we support multi-editing of prefab/model instances, - // handle it here. Only show prefab bar if all are same type? - if (!m_IsPrefabInstanceAnyRoot) return; + if (!m_IsPrefabInstanceAnyRoot) + return; - using (new EditorGUI.DisabledScope(EditorApplication.isPlayingOrWillChangePlaymode && PrefabStageUtility.GetPrefabStage(go) == null)) + using (new EditorGUI.DisabledScope(m_PlayModeObjects)) { EditorGUILayout.BeginHorizontal(s_Styles.prefabButtonsHorizontalLayout); // Prefab information - PrefabAssetType prefabType = PrefabUtility.GetPrefabAssetType(go); - PrefabInstanceStatus instanceStatus = PrefabUtility.GetPrefabInstanceStatus(go); + PrefabAssetType singlePrefabType = PrefabUtility.GetPrefabAssetType(target); + PrefabInstanceStatus singleInstanceStatus = PrefabUtility.GetPrefabInstanceStatus(target); GUIContent prefixLabel; if (targets.Length > 1) { @@ -326,14 +340,14 @@ private void DoPrefabButtons(GameObject go) } else { - prefixLabel = s_Styles.goTypeLabel[(int)prefabType, (int)instanceStatus]; + prefixLabel = s_Styles.goTypeLabel[(int)singlePrefabType, (int)singleInstanceStatus]; } if (prefixLabel != null) { EditorGUILayout.BeginHorizontal(GUILayout.Width(kIconSize + s_Styles.tagFieldWidth)); GUILayout.FlexibleSpace(); - if (PrefabUtility.IsDisconnectedFromPrefabAsset(go) || PrefabUtility.IsPrefabAssetMissing(go)) + if (m_IsDisconnected || m_IsMissing) { GUI.contentColor = GUI.skin.GetStyle("CN StatusWarn").normal.textColor; GUILayout.Label(prefixLabel, EditorStyles.whiteLabel, GUILayout.ExpandWidth(false)); @@ -344,13 +358,11 @@ private void DoPrefabButtons(GameObject go) EditorGUILayout.EndHorizontal(); } - if (targets.Length > 1) - GUILayout.Label("Instance Management Disabled", s_Styles.instanceManagementInfo); - else + if (!m_IsMissing) { - if (!PrefabUtility.IsPrefabAssetMissing(go)) + using (new EditorGUI.DisabledScope(targets.Length > 1)) { - if (prefabType == PrefabAssetType.Model) + if (singlePrefabType == PrefabAssetType.Model) { // Open Model Prefab if (GUILayout.Button("Open", "MiniButtonLeft")) @@ -373,11 +385,15 @@ private void DoPrefabButtons(GameObject go) } } } + } - // Select prefab - if (GUILayout.Button("Select", "MiniButtonRight")) + // Select prefab + if (GUILayout.Button("Select", "MiniButtonRight")) + { + HashSet selectedAssets = new HashSet(); + for (int i = 0; i < targets.Length; i++) { - Selection.activeObject = PrefabUtility.GetOriginalSourceOrVariantRoot(target); + GameObject prefabGo = PrefabUtility.GetOriginalSourceOrVariantRoot(targets[i]); // Because of legacy prefab references we have to have this extra step // to make sure we ping the prefab asset correctly. @@ -385,25 +401,30 @@ private void DoPrefabButtons(GameObject go) // will reference prefabs as if they are serialized assets. Those references // works fine but we are not able to ping objects loaded directly from the asset // file, so we have to make sure we ping the metadata version of the prefab. - var assetPath = AssetDatabase.GetAssetPath(Selection.activeObject); - Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(assetPath); + var assetPath = AssetDatabase.GetAssetPath(prefabGo); + selectedAssets.Add((GameObject)AssetDatabase.LoadMainAssetAtPath(assetPath)); + } + Selection.objects = selectedAssets.ToArray(); + if (Selection.gameObjects.Length == 1) EditorGUIUtility.PingObject(Selection.activeObject); - } + } - // Should be EditorGUILayout.Space, except it does not have ExpandWidth set to false. - // Maybe we can change that? - GUILayoutUtility.GetRect(6, 6, GUILayout.ExpandWidth(false)); + // Should be EditorGUILayout.Space, except it does not have ExpandWidth set to false. + // Maybe we can change that? + GUILayoutUtility.GetRect(6, 6, GUILayout.ExpandWidth(false)); - // Reserve space regardless of whether the button is there or not to avoid jumps in button sizes. - Rect rect = GUILayoutUtility.GetRect(s_Styles.overridesContent, s_Styles.overridesDropdown); - if (m_IsPrefabInstanceOutermostRoot) + // Reserve space regardless of whether the button is there or not to avoid jumps in button sizes. + Rect rect = GUILayoutUtility.GetRect(s_Styles.overridesContent, s_Styles.overridesDropdown); + if (m_IsPrefabInstanceOutermostRoot) + { + if (EditorGUI.DropdownButton(rect, s_Styles.overridesContent, FocusType.Passive)) { - if (EditorGUI.DropdownButton(rect, s_Styles.overridesContent, FocusType.Passive)) - { - PopupWindow.Show(rect, new PrefabOverridesWindow(go)); - GUIUtility.ExitGUI(); - } + if (targets.Length > 1) + PopupWindow.Show(rect, new PrefabOverridesWindow(targets.Select(e => (GameObject)e).ToArray())); + else + PopupWindow.Show(rect, new PrefabOverridesWindow((GameObject)target)); + GUIUtility.ExitGUI(); } } } diff --git a/Editor/Mono/Inspector/GenericPresetLibraryInspector.cs b/Editor/Mono/Inspector/GenericPresetLibraryInspector.cs deleted file mode 100644 index 89e175dda2..0000000000 --- a/Editor/Mono/Inspector/GenericPresetLibraryInspector.cs +++ /dev/null @@ -1,172 +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.IO; -using UnityEngine; - -namespace UnityEditor -{ - class GenericPresetLibraryInspector where T : ScriptableObject - { - readonly ScriptableObjectSaveLoadHelper m_SaveLoadHelper; - readonly UnityEngine.Object m_Target; - readonly string m_Header; - readonly VerticalGrid m_Grid; - readonly Action m_EditButtonClickedCallback; - private static GUIStyle s_EditButtonStyle; - private float m_LastRepaintedWidth = -1f; - - // Configure - public int maxShowNumPresets { get; set; } - public Vector2 presetSize { get; set; } - public float lineSpacing { get; set; } - public string extension { get { return m_SaveLoadHelper.fileExtensionWithoutDot; } } - public bool useOnePixelOverlappedGrid { get; set; } - public RectOffset marginsForList { get; set; } - public RectOffset marginsForGrid { get; set; } - public PresetLibraryEditorState.ItemViewMode itemViewMode { get; set; } - - public GenericPresetLibraryInspector(UnityEngine.Object target, string header, Action editButtonClicked) - { - m_Target = target; - m_Header = header; - m_EditButtonClickedCallback = editButtonClicked; - - string assetPath = AssetDatabase.GetAssetPath(m_Target.GetInstanceID()); - string extension = Path.GetExtension(assetPath); - if (!string.IsNullOrEmpty(extension)) - extension = extension.TrimStart('.'); - m_SaveLoadHelper = new ScriptableObjectSaveLoadHelper(extension, SaveType.Text); - m_Grid = new VerticalGrid(); - - // Default configuration - maxShowNumPresets = 49; // We clear some preview caches when they reach 50 (See AnimationCurvePreviewCache and GradientPreviewCache) - presetSize = new Vector2(14, 14); - lineSpacing = 1f; - useOnePixelOverlappedGrid = false; - marginsForList = new RectOffset(10, 10, 5, 5); - marginsForGrid = new RectOffset(10, 10, 5, 5); - itemViewMode = PresetLibraryEditorState.ItemViewMode.List; - } - - public void OnDestroy() - { - PresetLibraryManager.instance.UnloadAllLibrariesFor(m_SaveLoadHelper); - } - - public void OnInspectorGUI() - { - if (s_EditButtonStyle == null) - { - s_EditButtonStyle = new GUIStyle(EditorStyles.miniButton); - s_EditButtonStyle.margin.top = 7; - } - - string assetPath = AssetDatabase.GetAssetPath(m_Target.GetInstanceID()); - string libraryPath = Path.ChangeExtension(assetPath, null); - bool isInAnEditorFolder = libraryPath.Contains("/Editor/"); - - GUILayout.BeginHorizontal(); - GUILayout.Label(m_Header, EditorStyles.boldLabel); - GUILayout.FlexibleSpace(); - if (isInAnEditorFolder && m_EditButtonClickedCallback != null && GUILayout.Button("Edit...", s_EditButtonStyle)) - { - if (m_EditButtonClickedCallback != null) - m_EditButtonClickedCallback(libraryPath); - } - GUILayout.EndHorizontal(); - - GUILayout.Space(6); - - if (!isInAnEditorFolder) - { - GUIContent c = EditorGUIUtility.TrTextContent("Preset libraries should be placed in an 'Editor' folder.", EditorGUIUtility.warningIcon); - GUILayout.Label(c, EditorStyles.helpBox); - } - - DrawPresets(libraryPath); - } - - private void DrawPresets(string libraryPath) - { - if (GUIClip.visibleRect.width > 0) - m_LastRepaintedWidth = GUIClip.visibleRect.width; - - if (m_LastRepaintedWidth < 0) - { - GUILayoutUtility.GetRect(1, 1); // Ensure consistent call - HandleUtility.Repaint(); // Wait until we have a proper width - return; - } - - PresetLibrary lib = PresetLibraryManager.instance.GetLibrary(m_SaveLoadHelper, libraryPath) as PresetLibrary; - if (lib == null) - { - Debug.Log("Could not load preset library '" + libraryPath + "'"); - return; - } - - SetupGrid(m_LastRepaintedWidth, lib.Count(), itemViewMode); - - - int showNumPresets = Mathf.Min(lib.Count(), maxShowNumPresets); - int hiddenNumPresets = lib.Count() - showNumPresets; - float contentHeight = m_Grid.CalcRect(showNumPresets - 1, 0f).yMax + (hiddenNumPresets > 0 ? 20f : 0f); - - Rect reservedRect = GUILayoutUtility.GetRect(1, contentHeight); - - float spaceBetweenPresetAndText = presetSize.x + 6f; - for (int index = 0; index < showNumPresets; ++index) - { - Rect r = m_Grid.CalcRect(index, reservedRect.y); - Rect presetRect = new Rect(r.x, r.y, presetSize.x, presetSize.y); - lib.Draw(presetRect, index); - if (itemViewMode == PresetLibraryEditorState.ItemViewMode.List) - { - Rect nameRect = new Rect(r.x + spaceBetweenPresetAndText, r.y, r.width - spaceBetweenPresetAndText, r.height); - string name = lib.GetName(index); - GUI.Label(nameRect, name); - } - } - if (hiddenNumPresets > 0) - { - Rect textRect = new Rect(m_Grid.CalcRect(0, 0).x, reservedRect.y + contentHeight - 20f, reservedRect.width, 20f); - GUI.Label(textRect, string.Format("+ {0} more...", hiddenNumPresets)); - } - } - - void SetupGrid(float availableWidth, int itemCount, PresetLibraryEditorState.ItemViewMode presetsViewMode) - { - m_Grid.useFixedHorizontalSpacing = useOnePixelOverlappedGrid; - m_Grid.fixedHorizontalSpacing = useOnePixelOverlappedGrid ? -1 : 0; - - switch (presetsViewMode) - { - case PresetLibraryEditorState.ItemViewMode.Grid: - m_Grid.fixedWidth = availableWidth; - m_Grid.topMargin = marginsForGrid.top; - m_Grid.bottomMargin = marginsForGrid.bottom; - m_Grid.leftMargin = marginsForGrid.left; - m_Grid.rightMargin = marginsForGrid.right; - m_Grid.verticalSpacing = useOnePixelOverlappedGrid ? -1 : lineSpacing; - m_Grid.minHorizontalSpacing = 8f; - m_Grid.itemSize = presetSize; // no text - m_Grid.InitNumRowsAndColumns(itemCount, int.MaxValue); - break; - case PresetLibraryEditorState.ItemViewMode.List: - m_Grid.fixedWidth = availableWidth; - m_Grid.topMargin = marginsForList.top; - m_Grid.bottomMargin = marginsForList.bottom; - m_Grid.leftMargin = marginsForList.left; - m_Grid.rightMargin = marginsForList.right; - m_Grid.verticalSpacing = lineSpacing; - m_Grid.minHorizontalSpacing = 0f; - m_Grid.itemSize = new Vector2(availableWidth - m_Grid.leftMargin, presetSize.y); - m_Grid.InitNumRowsAndColumns(itemCount, int.MaxValue); - break; - } - } - } -} diff --git a/Editor/Mono/Inspector/GradientPresetLibraryInspector.cs b/Editor/Mono/Inspector/GradientPresetLibraryInspector.cs deleted file mode 100644 index 9618f7b627..0000000000 --- a/Editor/Mono/Inspector/GradientPresetLibraryInspector.cs +++ /dev/null @@ -1,42 +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.IO; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(GradientPresetLibrary))] - internal class GradientPresetLibraryEditor : Editor - { - private GenericPresetLibraryInspector m_GenericPresetLibraryInspector; - - public void OnEnable() - { - m_GenericPresetLibraryInspector = new GenericPresetLibraryInspector(target, "Gradient Preset Library", OnEditButtonClicked); - m_GenericPresetLibraryInspector.presetSize = new Vector2(72, 16); - m_GenericPresetLibraryInspector.lineSpacing = 4f; - } - - public void OnDestroy() - { - if (m_GenericPresetLibraryInspector != null) - m_GenericPresetLibraryInspector.OnDestroy(); - } - - public override void OnInspectorGUI() - { - m_GenericPresetLibraryInspector.itemViewMode = PresetLibraryEditorState.GetItemViewMode("Gradient"); // ensure in-sync - if (m_GenericPresetLibraryInspector != null) - m_GenericPresetLibraryInspector.OnInspectorGUI(); - } - - private void OnEditButtonClicked(string libraryPath) - { - GradientPicker.Show(new Gradient(), true); - GradientPicker.instance.currentPresetLibrary = libraryPath; - } - } -} // namespace diff --git a/Editor/Mono/Inspector/InspectorWindow.cs b/Editor/Mono/Inspector/InspectorWindow.cs index 9c685ac9ae..ba33875f25 100644 --- a/Editor/Mono/Inspector/InspectorWindow.cs +++ b/Editor/Mono/Inspector/InspectorWindow.cs @@ -511,7 +511,8 @@ protected virtual void OnGUI() if (tracker.activeEditors.Length > 0) { - DrawVCSShortInfo(); + Editor assetEditor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors); + DrawVCSShortInfo(this, assetEditor); } } @@ -904,14 +905,13 @@ private void DetachPreview() GUIUtility.ExitGUI(); } - protected virtual void DrawVCSSticky(float offset) + private static void DrawVCSSticky(EditorWindow hostWindow, Editor assetEditor, float offset) { string message = ""; - Editor assetEditor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors); bool hasRemovedSticky = EditorPrefs.GetBool("vcssticky"); if (!hasRemovedSticky && !Editor.IsAppropriateFileOpenForEdit(assetEditor.target, out message)) { - var rect = new Rect(10, position.height - 94, position.width - 20, 80); + var rect = new Rect(10, hostWindow.position.height - 94, hostWindow.position.width - 20, 80); rect.y -= offset; if (Event.current.type == EventType.Repaint) { @@ -932,14 +932,13 @@ protected virtual void DrawVCSSticky(float offset) } } - private void DrawVCSShortInfo() + internal static void DrawVCSShortInfo(EditorWindow hostWindow, Editor assetEditor) { if (Provider.enabled && EditorSettings.externalVersionControl != ExternalVersionControl.Disabled && EditorSettings.externalVersionControl != ExternalVersionControl.AutoDetect && EditorSettings.externalVersionControl != ExternalVersionControl.Generic) { - Editor assetEditor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors); string assetPath = AssetDatabase.GetAssetPath(assetEditor.target); Asset asset = Provider.GetAssetByPath(assetPath); if (asset == null || !(asset.path.StartsWith("Assets") || asset.path.StartsWith("ProjectSettings"))) @@ -1005,15 +1004,15 @@ private void DrawVCSShortInfo() // TODO: Retrieve default CheckoutMode from VC settings (depends on asset type; native vs. imported) Task task = Provider.Checkout(assetEditor.targets, CheckoutMode.Both); task.Wait(); - Repaint(); + hostWindow.Repaint(); } } - DrawVCSSticky(rect.height / 2); + DrawVCSSticky(hostWindow, assetEditor, rect.height / 2); } } } - protected string BuildTooltip(Asset asset, Asset metaAsset) + protected static string BuildTooltip(Asset asset, Asset metaAsset) { var sb = new StringBuilder(); if (asset != null) @@ -1029,7 +1028,7 @@ protected string BuildTooltip(Asset asset, Asset metaAsset) return sb.ToString(); } - protected void DrawVCSShortInfoAsset(Asset asset, string tooltip, Rect rect, Texture2D icon, string currentState) + protected static void DrawVCSShortInfoAsset(Asset asset, string tooltip, Rect rect, Texture2D icon, string currentState) { Rect overlayRect = new Rect(rect.x, rect.y, 28, 16); Rect iconRect = overlayRect; @@ -1241,7 +1240,7 @@ private void DrawEditor(Editor[] editors, int editorIndex, bool rebuildOptimized Rect contentRect = new Rect(); bool excludedClass = ModuleMetadata.GetModuleIncludeSettingForObject(target) == ModuleIncludeSetting.ForceExclude; if (excludedClass) - EditorGUILayout.HelpBox("The built-in package which implements this component type has been disabled in Package Manager. This object will be removed in play mode and from any builds you make.", MessageType.Warning); + EditorGUILayout.HelpBox("The built-in package '" + ModuleMetadata.GetExcludingModuleForObject(target) + "', which is required this component type has been disabled in Package Manager. This object will be removed in play mode and from any builds you make.", MessageType.Warning); using (new EditorGUI.DisabledScope(!editor.IsEnabled() || excludedClass)) { diff --git a/Editor/Mono/Inspector/LabelGUI.cs b/Editor/Mono/Inspector/LabelGUI.cs index c7b69c305f..7ef70781c2 100644 --- a/Editor/Mono/Inspector/LabelGUI.cs +++ b/Editor/Mono/Inspector/LabelGUI.cs @@ -189,7 +189,7 @@ public void OnLabelGUI(Object[] assets) r.x = widthProbeRect.xMax + labelButton.margin.left; if (EditorGUI.DropdownButton(r, GUIContent.none, FocusType.Passive, labelButton)) { - PopupWindow.Show(r, new PopupList(m_AssetLabels), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(r, new PopupList(m_AssetLabels)); } EditorGUILayout.EndHorizontal(); @@ -209,7 +209,7 @@ private void DrawLabelList(bool partiallySelected, float xMax) { evt.Use(); rt.x = xMax; - PopupWindow.Show(rt, new PopupList(m_AssetLabels, content.text), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(rt, new PopupList(m_AssetLabels, content.text)); } } } diff --git a/Editor/Mono/Inspector/LegacyIlluminShaderGUI.cs b/Editor/Mono/Inspector/LegacyIlluminShaderGUI.cs deleted file mode 100644 index 0bdb9e2700..0000000000 --- a/Editor/Mono/Inspector/LegacyIlluminShaderGUI.cs +++ /dev/null @@ -1,23 +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 -{ - internal class LegacyIlluminShaderGUI : ShaderGUI - { - public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) - { - base.OnGUI(materialEditor, props); - - materialEditor.LightmapEmissionProperty(0); - - // We assume that illumin shader always has emission - foreach (Material material in materialEditor.targets) - material.globalIlluminationFlags &= ~MaterialGlobalIlluminationFlags.EmissiveIsBlack; - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/Inspector/LightProbesInspector.cs b/Editor/Mono/Inspector/LightProbesInspector.cs deleted file mode 100644 index 820e7cb4b3..0000000000 --- a/Editor/Mono/Inspector/LightProbesInspector.cs +++ /dev/null @@ -1,23 +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; - - -namespace UnityEditor -{ - [CustomEditor(typeof(LightProbes))] - class LightProbesInspector : Editor - { - public override void OnInspectorGUI() - { - GUILayout.BeginVertical(EditorStyles.helpBox); - var lp = target as LightProbes; - GUIStyle labelStyle = EditorStyles.wordWrappedMiniLabel; - GUILayout.Label("Light probe count: " + lp.count, labelStyle); - GUILayout.Label("Cell count: " + lp.cellCount, labelStyle); - GUILayout.EndVertical(); - } - } -} diff --git a/Editor/Mono/Inspector/LightingSettingsInspector.cs b/Editor/Mono/Inspector/LightingSettingsInspector.cs index afe116b735..0f27dbf8aa 100644 --- a/Editor/Mono/Inspector/LightingSettingsInspector.cs +++ b/Editor/Mono/Inspector/LightingSettingsInspector.cs @@ -56,18 +56,25 @@ static class Styles public static readonly GUIContent CastShadows = EditorGUIUtility.TrTextContent("Cast Shadows", "Specifies whether a geometry creates shadows or not when a shadow-casting Light shines on it."); public static readonly GUIContent ReceiveShadows = EditorGUIUtility.TrTextContent("Receive Shadows", "When enabled, any shadows cast from other objects are drawn on the geometry."); public static readonly GUIContent MotionVectors = EditorGUIUtility.TrTextContent("Motion Vectors", "Specifies whether the Mesh renders 'Per Object Motion', 'Camera Motion', or 'No Motion' vectors to the Camera Motion Vector Texture."); - public static readonly GUIContent LightmapInfoBox = EditorGUIUtility.TrTextContent("To enable generation of lightmaps for this Mesh Renderer, please enable the 'Lightmap Static' property."); public static readonly GUIContent TerrainLightmapInfoBox = EditorGUIUtility.TrTextContent("To enable generation of lightmaps for this Mesh Renderer, please enable the 'Lightmap Static' property."); public static readonly GUIContent ResolutionTooHighWarning = EditorGUIUtility.TrTextContent("Precompute/indirect resolution for this terrain is probably too high. Use a lower realtime/indirect resolution setting in the Lighting window or assign LightmapParameters that use a lower resolution setting. Otherwise it may take a very long time to bake and memory consumption during and after the bake may be very high."); public static readonly GUIContent ResolutionTooLowWarning = EditorGUIUtility.TrTextContent("Precompute/indirect resolution for this terrain is probably too low. If the Clustering stage takes a long time, try using a higher realtime/indirect resolution setting in the Lighting window or assign LightmapParameters that use a higher resolution setting."); public static readonly GUIContent GINotEnabledInfo = EditorGUIUtility.TrTextContent("Lightmapping settings are currently disabled. Enable Baked Global Illumination or Realtime Global Illumination to display these settings."); + public static readonly GUIContent CastShadowsProgressiveGPUWarning = EditorGUIUtility.TrTextContent("Cast Shadows is forced to 'On' when using the GPU lightmapper (Preview), it will be supported in a later version. Use the CPU lightmapper instead if you need this functionality."); + public static readonly GUIContent ReceiveShadowsProgressiveGPUWarning = EditorGUIUtility.TrTextContent("Receive Shadows is forced to 'On' when using the GPU lightmapper (Preview), it will be supported in a later version. Use the CPU lightmapper instead if you need this functionality."); + public static readonly GUIContent OpenPreview = EditorGUIUtility.TrTextContent("Open Preview"); + + public static readonly GUIStyle OpenPreviewStyle = EditorStyles.objectFieldThumb.name + "LightmapPreviewOverlay"; + + public static readonly int PreviewPadding = 30; + public static readonly int PreviewWidth = 104; } bool m_ShowChartingSettings = true; bool m_ShowLightmapSettings = true; - bool m_ShowBakedLM = false; - bool m_ShowRealtimeLM = false; + bool m_ShowBakedLM = true; + bool m_ShowRealtimeLM = true; SerializedObject m_SerializedObject; SerializedObject m_GameObjectsSerializedObject; @@ -157,13 +164,25 @@ public void RenderMeshSettings(bool showLightmapSettings) m_GameObjectsSerializedObject.Update(); m_LightmapSettings.Update(); - EditorGUILayout.PropertyField(m_CastShadows, Styles.CastShadows, true); + // TODO(RadeonRays): remove scope for GPU lightmapper once the feature has been implemented. + using (new EditorGUI.DisabledScope(LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU)) + { + EditorGUILayout.PropertyField(m_CastShadows, Styles.CastShadows, true); + } + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + EditorGUILayout.HelpBox(Styles.CastShadowsProgressiveGPUWarning.text, MessageType.Info); + bool isDeferredRenderingPath = SceneView.IsUsingDeferredRenderingPath(); if (SupportedRenderingFeatures.active.rendererSupportsReceiveShadows) { - using (new EditorGUI.DisabledScope(isDeferredRenderingPath)) + // TODO(RadeonRays): remove scope for GPU lightmapper once the feature has been implemented. + using (new EditorGUI.DisabledScope(isDeferredRenderingPath || LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU)) + { EditorGUILayout.PropertyField(m_ReceiveShadows, Styles.ReceiveShadows, true); + } + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + EditorGUILayout.HelpBox(Styles.ReceiveShadowsProgressiveGPUWarning.text, MessageType.Info); } if (SupportedRenderingFeatures.active.rendererSupportsMotionVectors) @@ -227,13 +246,8 @@ public void RenderMeshSettings(bool showLightmapSettings) { EditorGUI.indentLevel += 1; - m_ShowBakedLM = EditorGUILayout.Foldout(m_ShowBakedLM, Styles.Atlas, true); - if (m_ShowBakedLM) - ShowAtlasGUI(m_Renderers[0].GetInstanceID()); - - m_ShowRealtimeLM = EditorGUILayout.Foldout(m_ShowRealtimeLM, Styles.RealtimeLM, true); - if (m_ShowRealtimeLM) - ShowRealtimeLMGUI(m_Renderers[0]); + ShowAtlasGUI(m_Renderers[0].GetInstanceID()); + ShowRealtimeLMGUI(m_Renderers[0]); EditorGUI.indentLevel -= 1; } @@ -299,13 +313,8 @@ public void RenderTerrainSettings() if (GUI.enabled && m_Terrains.Length == 1 && m_Terrains[0].terrainData != null) ShowBakePerformanceWarning(m_Terrains[0]); - m_ShowBakedLM = EditorGUILayout.Foldout(m_ShowBakedLM, Styles.Atlas, true); - if (m_ShowBakedLM) - ShowAtlasGUI(m_Terrains[0].GetInstanceID()); - - m_ShowRealtimeLM = EditorGUILayout.Foldout(m_ShowRealtimeLM, Styles.RealtimeLM, true); - if (m_ShowRealtimeLM) - ShowRealtimeLMGUI(m_Terrains[0]); + ShowAtlasGUI(m_Terrains[0].GetInstanceID()); + ShowRealtimeLMGUI(m_Terrains[0]); m_SerializedObject.ApplyModifiedProperties(); } @@ -400,44 +409,29 @@ void ShowAtlasGUI(int instanceID) if (m_CachedBakedTexture.texture == null) return; - EditorGUI.indentLevel += 1; - - GUILayout.BeginHorizontal(); - GUILayout.Space(30); + m_ShowBakedLM = EditorGUILayout.Foldout(m_ShowBakedLM, Styles.Atlas, true); - Rect rect = GUILayoutUtility.GetRect(100, 100, EditorStyles.objectField); + if (!m_ShowBakedLM) + return; - EditorGUI.Toggle(rect, false, EditorStyles.objectFieldThumb); + EditorGUI.indentLevel += 1; - if (rect.Contains(Event.current.mousePosition)) - { - Object actualTargetObject = m_CachedBakedTexture.texture; - Component com = actualTargetObject as Component; + GUILayout.BeginHorizontal(); - if (com) - actualTargetObject = com.gameObject; + DrawLightmapPreview(m_CachedBakedTexture.texture, false, instanceID); - if (Event.current.clickCount == 2) - LightmapPreviewWindow.CreateLightmapPreviewWindow(m_Renderers[0].GetInstanceID(), false, false); - else if (Event.current.clickCount == 1) - EditorGUI.PingObjectOrShowPreviewOnClick(actualTargetObject, GUILayoutUtility.GetLastRect()); - } + GUILayout.BeginVertical(); - if (Event.current.type == EventType.Repaint) - { - rect = EditorStyles.objectFieldThumb.padding.Remove(rect); - EditorGUI.DrawPreviewTexture(rect, m_CachedBakedTexture.texture); - } + GUILayout.Label(Styles.AtlasIndex.text + ": " + m_LightmapIndex.intValue.ToString()); + GUILayout.Label(Styles.AtlasTilingX.text + ": " + m_LightmapTilingOffsetX.floatValue.ToString()); + GUILayout.Label(Styles.AtlasTilingY.text + ": " + m_LightmapTilingOffsetY.floatValue.ToString()); + GUILayout.Label(Styles.AtlasOffsetX.text + ": " + m_LightmapTilingOffsetZ.floatValue.ToString()); + GUILayout.Label(Styles.AtlasOffsetY.text + ": " + m_LightmapTilingOffsetW.floatValue.ToString()); + GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); - EditorGUILayout.LabelField(Styles.AtlasIndex, GUIContent.Temp(m_LightmapIndex.intValue.ToString())); - EditorGUILayout.LabelField(Styles.AtlasTilingX, GUIContent.Temp(m_LightmapTilingOffsetX.floatValue.ToString())); - EditorGUILayout.LabelField(Styles.AtlasTilingY, GUIContent.Temp(m_LightmapTilingOffsetY.floatValue.ToString())); - EditorGUILayout.LabelField(Styles.AtlasOffsetX, GUIContent.Temp(m_LightmapTilingOffsetZ.floatValue.ToString())); - EditorGUILayout.LabelField(Styles.AtlasOffsetY, GUIContent.Temp(m_LightmapTilingOffsetW.floatValue.ToString())); - bool showProgressiveInfo = isPrefabAsset || (m_EnabledBakedGI.boolValue && LightmapEditorSettings.lightmapper != LightmapEditorSettings.Lightmapper.Enlighten); if (showProgressiveInfo && Unsupported.IsDeveloperMode()) @@ -454,19 +448,32 @@ void ShowAtlasGUI(int instanceID) LightmapEditorSettings.GetPVRAtlasInstanceOffset(instanceID, out atlasInstanceOffset); EditorGUILayout.LabelField(Styles.PVRAtlasInstanceOffset, GUIContent.Temp(atlasInstanceOffset.ToString())); } - EditorGUI.indentLevel -= 1; + + GUILayout.Space(5); } void ShowRealtimeLMGUI(Terrain terrain) { + Hash128 inputSystemHash; + if (terrain == null || !LightmapEditorSettings.GetInputSystemHash(terrain.GetInstanceID(), out inputSystemHash) || inputSystemHash == new Hash128()) + return; // early return since we don't have any lightmaps for it + + if (!UpdateRealtimeTexture(inputSystemHash, terrain.GetInstanceID())) + return; + + m_ShowRealtimeLM = EditorGUILayout.Foldout(m_ShowRealtimeLM, Styles.RealtimeLM, true); + + if (!m_ShowRealtimeLM) + return; + EditorGUI.indentLevel += 1; - Hash128 inputSystemHash; - if (terrain != null && LightmapEditorSettings.GetInputSystemHash(terrain.GetInstanceID(), out inputSystemHash)) - { - ShowRealtimeLightmapPreview(inputSystemHash); - } + GUILayout.BeginHorizontal(); + + DrawLightmapPreview(m_CachedRealtimeTexture.texture, true, terrain.GetInstanceID()); + + GUILayout.BeginVertical(); // Resolution of the system. int width, height; @@ -476,34 +483,56 @@ void ShowRealtimeLMGUI(Terrain terrain) var str = width.ToString() + "x" + height.ToString(); if (numChunksInX > 1 || numChunksInY > 1) str += string.Format(" ({0}x{1} chunks)", numChunksInX, numChunksInY); - EditorGUILayout.LabelField(Styles.RealtimeLMResolution, GUIContent.Temp(str)); + GUILayout.Label(Styles.RealtimeLMResolution.text + ": " + str); } + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + EditorGUI.indentLevel -= 1; + + GUILayout.Space(5); } void ShowRealtimeLMGUI(Renderer renderer) { + Hash128 inputSystemHash; + if (renderer == null || !LightmapEditorSettings.GetInputSystemHash(renderer.GetInstanceID(), out inputSystemHash) || inputSystemHash == new Hash128()) + return; // early return since we don't have any lightmaps for it + + if (!UpdateRealtimeTexture(inputSystemHash, renderer.GetInstanceID())) + return; + + m_ShowRealtimeLM = EditorGUILayout.Foldout(m_ShowRealtimeLM, Styles.RealtimeLM, true); + + if (!m_ShowRealtimeLM) + return; + EditorGUI.indentLevel += 1; - Hash128 inputSystemHash = new Hash128(); - if (renderer != null && LightmapEditorSettings.GetInputSystemHash(renderer.GetInstanceID(), out inputSystemHash)) - { - ShowRealtimeLightmapPreview(inputSystemHash); - } + GUILayout.BeginHorizontal(); + + DrawLightmapPreview(m_CachedRealtimeTexture.texture, true, renderer.GetInstanceID()); + + GUILayout.BeginVertical(); int instWidth, instHeight; if (LightmapEditorSettings.GetInstanceResolution(renderer, out instWidth, out instHeight)) { - EditorGUILayout.LabelField(Styles.RealtimeLMInstanceResolution, GUIContent.Temp(instWidth.ToString() + "x" + instHeight.ToString())); + GUILayout.Label(Styles.RealtimeLMInstanceResolution.text + ": " + instWidth.ToString() + "x" + instHeight.ToString()); } int width, height; if (LightmapEditorSettings.GetSystemResolution(renderer, out width, out height)) { - EditorGUILayout.LabelField(Styles.RealtimeLMResolution, GUIContent.Temp(width.ToString() + "x" + height.ToString())); + GUILayout.Label(Styles.RealtimeLMResolution.text + ": " + width.ToString() + "x" + height.ToString()); } + GUILayout.EndVertical(); + GUILayout.FlexibleSpace(); + GUILayout.EndHorizontal(); + if (Unsupported.IsDeveloperMode()) { Hash128 instanceHash; @@ -522,12 +551,14 @@ void ShowRealtimeLMGUI(Renderer renderer) } EditorGUI.indentLevel -= 1; + + GUILayout.Space(5); } - void ShowRealtimeLightmapPreview(Hash128 inputSystemHash) + bool UpdateRealtimeTexture(Hash128 inputSystemHash, int instanceId) { if (inputSystemHash == new Hash128()) - return; + return false; Hash128 contentHash = LightmapVisualizationUtility.GetRealtimeGITextureHash(inputSystemHash, GITextureType.Irradiance); @@ -536,35 +567,51 @@ void ShowRealtimeLightmapPreview(Hash128 inputSystemHash) m_CachedRealtimeTexture = LightmapVisualizationUtility.GetRealtimeGITexture(inputSystemHash, GITextureType.Irradiance); if (m_CachedRealtimeTexture.texture == null) - return; + return false; - GUILayout.BeginHorizontal(); - GUILayout.Space(30); + return true; + } + + private void DrawLightmapPreview(Texture2D texture, bool realtimeLightmap, int instanceId) + { + GUILayout.Space(Styles.PreviewPadding); - Rect rect = GUILayoutUtility.GetRect(100, 100, EditorStyles.objectField); + int previewWidth = Styles.PreviewWidth - 4; // padding - EditorGUI.Toggle(rect, false, EditorStyles.objectFieldThumb); + Rect rect = GUILayoutUtility.GetRect(previewWidth, previewWidth, EditorStyles.objectField); + Rect buttonRect = new Rect(rect.xMax - 70, rect.yMax - 14, 70, 14); - if (rect.Contains(Event.current.mousePosition)) + if (Event.current.type == EventType.MouseDown) { - Object actualTargetObject = m_CachedRealtimeTexture.texture; - Component com = actualTargetObject as Component; + if ((buttonRect.Contains(Event.current.mousePosition) && Event.current.clickCount == 1) || + (rect.Contains(Event.current.mousePosition) && Event.current.clickCount == 2)) + { + LightmapPreviewWindow.CreateLightmapPreviewWindow(instanceId, realtimeLightmap, false); + } + else if (rect.Contains(Event.current.mousePosition) && Event.current.clickCount == 1) + { + Object actualTargetObject = texture; + Component com = actualTargetObject as Component; - if (com) - actualTargetObject = com.gameObject; + if (com) + actualTargetObject = com.gameObject; - if (Event.current.clickCount == 2) - LightmapPreviewWindow.CreateLightmapPreviewWindow(m_Renderers[0].GetInstanceID(), true, false); + EditorGUI.PingObjectOrShowPreviewOnClick(actualTargetObject, rect); + } } + EditorGUI.Toggle(rect, false, EditorStyles.objectFieldThumb); + if (Event.current.type == EventType.Repaint) { rect = EditorStyles.objectFieldThumb.padding.Remove(rect); - EditorGUI.DrawPreviewTexture(rect, m_CachedRealtimeTexture.texture); + EditorGUI.DrawPreviewTexture(rect, texture); + + Styles.OpenPreviewStyle.Draw(rect, Styles.OpenPreview, false, false, false, false); } - GUILayout.FlexibleSpace(); - GUILayout.EndHorizontal(); + float spacing = Mathf.Max(5.0f, EditorGUIUtility.labelWidth - Styles.PreviewPadding - Styles.PreviewWidth); + GUILayout.Space(spacing); } static bool HasNormals(Renderer renderer) diff --git a/Editor/Mono/Inspector/MaterialEditor.cs b/Editor/Mono/Inspector/MaterialEditor.cs index ad6c71cf1f..30628d6d4f 100644 --- a/Editor/Mono/Inspector/MaterialEditor.cs +++ b/Editor/Mono/Inspector/MaterialEditor.cs @@ -60,6 +60,7 @@ private static class Styles public static readonly GUIContent enableInstancingLabel = EditorGUIUtility.TrTextContent("Enable GPU Instancing"); public static readonly GUIContent doubleSidedGILabel = EditorGUIUtility.TrTextContent("Double Sided Global Illumination", "When enabled, the lightmapper accounts for both sides of the geometry when calculating Global Illumination. Backfaces are not rendered or added to lightmaps, but get treated as valid when seen from other objects. When using the Progressive Lightmapper backfaces bounce light using the same emission and albedo as frontfaces."); public static readonly GUIContent emissionLabel = EditorGUIUtility.TrTextContent("Emission"); + public static readonly GUIContent ProgressiveGPUWarning = EditorGUIUtility.TrTextContent("The Double Sided Global Illumination feature is not implemented in the Progressive GPU lightmapper yet. Use the CPU lightmapper instead if you need this functionality."); } private static readonly List s_MaterialEditors = new List(4); diff --git a/Editor/Mono/Inspector/MaterialEditorGUIHelpers.cs b/Editor/Mono/Inspector/MaterialEditorGUIHelpers.cs index 77dcd09308..6ff78840fe 100644 --- a/Editor/Mono/Inspector/MaterialEditorGUIHelpers.cs +++ b/Editor/Mono/Inspector/MaterialEditorGUIHelpers.cs @@ -163,8 +163,13 @@ public bool DoubleSidedGIField() } else { + // TODO(RadeonRays): change this to (lightmapper == Enlighten) once Double Sided GI works with GPU lightmapper. using (new EditorGUI.DisabledScope(LightmapEditorSettings.lightmapper != LightmapEditorSettings.Lightmapper.ProgressiveCPU)) EditorGUI.Toggle(r, Styles.doubleSidedGILabel, false); + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + { + EditorGUILayout.HelpBox(Styles.ProgressiveGPUWarning.text, MessageType.Info); + } } return false; } diff --git a/Editor/Mono/Inspector/NavMeshObstacleInspector.cs b/Editor/Mono/Inspector/NavMeshObstacleInspector.cs deleted file mode 100644 index fa566680af..0000000000 --- a/Editor/Mono/Inspector/NavMeshObstacleInspector.cs +++ /dev/null @@ -1,85 +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.AI; - -namespace UnityEditor -{ - [CanEditMultipleObjects] - [CustomEditor(typeof(NavMeshObstacle))] - internal class NavMeshObstacleInspector : Editor - { - private SerializedProperty m_Shape; - private SerializedProperty m_Center; - private SerializedProperty m_Extents; - private SerializedProperty m_Carve; - private SerializedProperty m_MoveThreshold; - private SerializedProperty m_TimeToStationary; - private SerializedProperty m_CarveOnlyStationary; - - void OnEnable() - { - m_Shape = serializedObject.FindProperty("m_Shape"); - m_Center = serializedObject.FindProperty("m_Center"); - m_Extents = serializedObject.FindProperty("m_Extents"); - m_Carve = serializedObject.FindProperty("m_Carve"); - m_MoveThreshold = serializedObject.FindProperty("m_MoveThreshold"); - m_TimeToStationary = serializedObject.FindProperty("m_TimeToStationary"); - m_CarveOnlyStationary = serializedObject.FindProperty("m_CarveOnlyStationary"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(m_Shape); - if (EditorGUI.EndChangeCheck()) - { - serializedObject.ApplyModifiedProperties(); - (target as NavMeshObstacle).FitExtents(); - serializedObject.Update(); - } - - EditorGUILayout.PropertyField(m_Center); - - if (m_Shape.enumValueIndex == 0) - { - // NavMeshObstacleShape : kObstacleShapeCapsule - EditorGUI.BeginChangeCheck(); - float radius = EditorGUILayout.FloatField("Radius", m_Extents.vector3Value.x); - float height = EditorGUILayout.FloatField("Height", m_Extents.vector3Value.y * 2.0f); - if (EditorGUI.EndChangeCheck()) - { - m_Extents.vector3Value = new Vector3(radius, height / 2.0f, radius); - } - } - else if (m_Shape.enumValueIndex == 1) - { - // NavMeshObstacleShape : kObstacleShapeBox - EditorGUI.BeginChangeCheck(); - Vector3 size = m_Extents.vector3Value * 2.0f; - size = EditorGUILayout.Vector3Field("Size", size); - if (EditorGUI.EndChangeCheck()) - { - m_Extents.vector3Value = size / 2.0f; - } - } - - EditorGUILayout.PropertyField(m_Carve); - - if (m_Carve.boolValue) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(m_MoveThreshold); - EditorGUILayout.PropertyField(m_TimeToStationary); - EditorGUILayout.PropertyField(m_CarveOnlyStationary); - EditorGUI.indentLevel--; - } - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/OcclusionAreaEditor.cs b/Editor/Mono/Inspector/OcclusionAreaEditor.cs deleted file mode 100644 index 60ab6c25ae..0000000000 --- a/Editor/Mono/Inspector/OcclusionAreaEditor.cs +++ /dev/null @@ -1,98 +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 UnityEditor; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(OcclusionArea))] - class OcclusionAreaEditor : Editor - { - SerializedObject m_Object; - SerializedProperty m_Size; - SerializedProperty m_Center; - - void OnEnable() - { - m_Object = new SerializedObject(target); - m_Size = serializedObject.FindProperty("m_Size"); - m_Center = serializedObject.FindProperty("m_Center"); - } - - void OnDisable() - { - m_Object.Dispose(); - m_Object = null; - } - - void OnSceneGUI() - { - m_Object.Update(); - - OcclusionArea area = (OcclusionArea)target; - - - Color tempColor = Handles.color; - Handles.color = new Color(145f, 244f, 139f, 255f) / 255; - - Vector3 offset = area.transform.TransformPoint(m_Center.vector3Value); - - // Get min and max extends from center and size - Vector3 min = m_Size.vector3Value * 0.5f; - Vector3 max = m_Size.vector3Value * 0.5f; - - // Yes, it's weird to use lossyScale here, but that's what the occlusion volumes do - Vector3 scale = area.transform.lossyScale; - Vector3 inverseScale = new Vector3(1 / scale.x, 1 / scale.y, 1 / scale.z); - min = Vector3.Scale(min, scale); - max = Vector3.Scale(max, scale); - - // Handles - bool temp = GUI.changed; - min.x = SizeSlider(offset, -Vector3.right, min.x); - min.y = SizeSlider(offset, -Vector3.up, min.y); - min.z = SizeSlider(offset, -Vector3.forward, min.z); - max.x = SizeSlider(offset, Vector3.right, max.x); - max.y = SizeSlider(offset, Vector3.up, max.y); - max.z = SizeSlider(offset, Vector3.forward, max.z); - - // Apply cahnges if there were any - if (GUI.changed) - { - // Occlusion volumes can't be rotated but the center is still affected by rotation, so - // we need to rotate the offset (and apply the inverse lossyScale AFTER that) - m_Center.vector3Value = m_Center.vector3Value + Vector3.Scale(Quaternion.Inverse(area.transform.rotation) * (max - min) * 0.5f, inverseScale); - min = Vector3.Scale(min, inverseScale); - max = Vector3.Scale(max, inverseScale); - m_Size.vector3Value = (max + min); - - serializedObject.ApplyModifiedProperties(); - } - GUI.changed |= temp; - - Handles.color = tempColor; - } - - float SizeSlider(Vector3 p, Vector3 d, float r) - { - Vector3 position = p + d * r; - Color tempColor = Handles.color; - - if (Vector3.Dot((position - Camera.current.transform.position), d) >= 0) - Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, Handles.color.a * Handles.backfaceAlphaMultiplier); - - float size = HandleUtility.GetHandleSize(position); - bool temp = GUI.changed; - GUI.changed = false; - position = Handles.Slider(position, d, size * 0.1f, Handles.CylinderHandleCap, 0f); - if (GUI.changed) - r = Vector3.Dot(position - p, d); - GUI.changed |= temp; - - Handles.color = tempColor; - return r; - } - } -} diff --git a/Editor/Mono/Inspector/OffMeshLinkInspector.cs b/Editor/Mono/Inspector/OffMeshLinkInspector.cs deleted file mode 100644 index cbc2a3f577..0000000000 --- a/Editor/Mono/Inspector/OffMeshLinkInspector.cs +++ /dev/null @@ -1,78 +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.AI; - - -namespace UnityEditor -{ - [CanEditMultipleObjects] - [CustomEditor(typeof(OffMeshLink))] - internal class OffMeshLinkInspector : Editor - { - private SerializedProperty m_AreaIndex; - private SerializedProperty m_Start; - private SerializedProperty m_End; - private SerializedProperty m_CostOverride; - private SerializedProperty m_BiDirectional; - private SerializedProperty m_Activated; - private SerializedProperty m_AutoUpdatePositions; - - void OnEnable() - { - m_AreaIndex = serializedObject.FindProperty("m_AreaIndex"); - m_Start = serializedObject.FindProperty("m_Start"); - m_End = serializedObject.FindProperty("m_End"); - m_CostOverride = serializedObject.FindProperty("m_CostOverride"); - m_BiDirectional = serializedObject.FindProperty("m_BiDirectional"); - m_Activated = serializedObject.FindProperty("m_Activated"); - m_AutoUpdatePositions = serializedObject.FindProperty("m_AutoUpdatePositions"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_Start); - EditorGUILayout.PropertyField(m_End); - EditorGUILayout.PropertyField(m_CostOverride); - EditorGUILayout.PropertyField(m_BiDirectional); - EditorGUILayout.PropertyField(m_Activated); - EditorGUILayout.PropertyField(m_AutoUpdatePositions); - - SelectNavMeshArea(); - - serializedObject.ApplyModifiedProperties(); - } - - private void SelectNavMeshArea() - { - EditorGUI.BeginChangeCheck(); - EditorGUI.showMixedValue = m_AreaIndex.hasMultipleDifferentValues; - var areaNames = GameObjectUtility.GetNavMeshAreaNames(); - var currentAbsoluteIndex = m_AreaIndex.intValue; - var areaIndex = -1; - - //Need to find the index as the list of names will compress out empty layers - for (var i = 0; i < areaNames.Length; i++) - { - if (GameObjectUtility.GetNavMeshAreaFromName(areaNames[i]) == currentAbsoluteIndex) - { - areaIndex = i; - break; - } - } - - var area = EditorGUILayout.Popup("Navigation Area", areaIndex, areaNames); - EditorGUI.showMixedValue = false; - - if (EditorGUI.EndChangeCheck()) - { - var newAreaIndex = GameObjectUtility.GetNavMeshAreaFromName(areaNames[area]); - m_AreaIndex.intValue = newAreaIndex; - } - } - } -} diff --git a/Editor/Mono/Inspector/PlatformEffector2DEditor.cs b/Editor/Mono/Inspector/PlatformEffector2DEditor.cs deleted file mode 100644 index fc886be8da..0000000000 --- a/Editor/Mono/Inspector/PlatformEffector2DEditor.cs +++ /dev/null @@ -1,187 +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.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor.AnimatedValues; - -namespace UnityEditor -{ - /// - /// An editor for the Platform Effector. - /// - [CustomEditor(typeof(PlatformEffector2D), true)] - [CanEditMultipleObjects] - internal class PlatformEffector2DEditor : Effector2DEditor - { - SerializedProperty m_RotationalOffset; - - readonly AnimBool m_ShowOneWayRollout = new AnimBool(); - SerializedProperty m_UseOneWay; - SerializedProperty m_UseOneWayGrouping; - SerializedProperty m_SurfaceArc; - - static readonly AnimBool m_ShowSidesRollout = new AnimBool(); - SerializedProperty m_UseSideFriction; - SerializedProperty m_UseSideBounce; - SerializedProperty m_SideArc; - - public override void OnEnable() - { - base.OnEnable(); - - m_RotationalOffset = serializedObject.FindProperty("m_RotationalOffset"); - - m_ShowOneWayRollout.value = true; - m_ShowOneWayRollout.valueChanged.AddListener(Repaint); - m_UseOneWay = serializedObject.FindProperty("m_UseOneWay"); - m_UseOneWayGrouping = serializedObject.FindProperty("m_UseOneWayGrouping"); - m_SurfaceArc = serializedObject.FindProperty("m_SurfaceArc"); - - m_ShowSidesRollout.valueChanged.AddListener(Repaint); - m_UseSideFriction = serializedObject.FindProperty("m_UseSideFriction"); - m_UseSideBounce = serializedObject.FindProperty("m_UseSideBounce"); - m_SideArc = serializedObject.FindProperty("m_SideArc"); - } - - public override void OnDisable() - { - base.OnDisable(); - - m_ShowOneWayRollout.valueChanged.RemoveListener(Repaint); - m_ShowSidesRollout.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_RotationalOffset); - - // One-Way. - m_ShowOneWayRollout.target = EditorGUILayout.Foldout(m_ShowOneWayRollout.target, "One Way", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowOneWayRollout.faded)) - { - EditorGUILayout.PropertyField(m_UseOneWay); - EditorGUILayout.PropertyField(m_UseOneWayGrouping); - EditorGUILayout.PropertyField(m_SurfaceArc); - EditorGUILayout.Space(); - } - EditorGUILayout.EndFadeGroup(); - - // Sides. - m_ShowSidesRollout.target = EditorGUILayout.Foldout(m_ShowSidesRollout.target, "Sides", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowSidesRollout.faded)) - { - EditorGUILayout.PropertyField(m_UseSideFriction); - EditorGUILayout.PropertyField(m_UseSideBounce); - EditorGUILayout.PropertyField(m_SideArc); - } - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - } - - public void OnSceneGUI() - { - var effector = (PlatformEffector2D)target; - - // Ignore disabled effector. - if (!effector.enabled) - return; - - if (effector.useOneWay) - DrawSurfaceArc(effector); - - if (!effector.useSideBounce || !effector.useSideFriction) - DrawSideArc(effector); - } - - private static void DrawSurfaceArc(PlatformEffector2D effector) - { - // Calculate the surface angle in local-space. - var rotation = -Mathf.Deg2Rad * effector.rotationalOffset; - var localUp = effector.transform.TransformVector(new Vector3(Mathf.Sin(rotation), Mathf.Cos(rotation), 0.0f)).normalized; - - // If the transform has created a degenerate local then we cannot draw the gizmo! - if (localUp.sqrMagnitude < Mathf.Epsilon) - return; - - // Calculate the surface angle. - var surfaceAngle = Mathf.Atan2(localUp.x, localUp.y); - - // Fetch the surface arc. - var surfaceArc = Mathf.Clamp(effector.surfaceArc, 0.5f, 360.0f); - var halfSurfaceArcRadians = surfaceArc * 0.5f * Mathf.Deg2Rad; - - var fromAngle = new Vector3(Mathf.Sin(surfaceAngle - halfSurfaceArcRadians), Mathf.Cos(surfaceAngle - halfSurfaceArcRadians), 0.0f); - var toAngle = new Vector3(Mathf.Sin(surfaceAngle + halfSurfaceArcRadians), Mathf.Cos(surfaceAngle + halfSurfaceArcRadians), 0.0f); - - // Fetch all the effector-collider bounds. - foreach (var collider in effector.gameObject.GetComponents().Where(collider => collider.enabled && collider.usedByEffector)) - { - var center = collider.bounds.center; - var arcRadius = HandleUtility.GetHandleSize(center); - - // arc background - Handles.color = new Color(0, 1, 1, 0.07f); - Handles.DrawSolidArc(center, Vector3.back, fromAngle, surfaceArc, arcRadius); - - // arc frame - Handles.color = new Color(0, 1, 1, 0.7f); - Handles.DrawWireArc(center, Vector3.back, fromAngle, surfaceArc, arcRadius); - Handles.DrawDottedLine(center, center + fromAngle * arcRadius, 5.0f); - Handles.DrawDottedLine(center, center + toAngle * arcRadius, 5.0f); - } - } - - private static void DrawSideArc(PlatformEffector2D effector) - { - // Calculate the surface angle in local-space. - var rotation = -Mathf.Deg2Rad * (90.0f + effector.rotationalOffset); - var localSide = effector.transform.TransformVector(new Vector3(Mathf.Sin(rotation), Mathf.Cos(rotation), 0.0f)).normalized; - - // If the transform has created a degenerate local then we cannot draw the gizmo! - if (localSide.sqrMagnitude < Mathf.Epsilon) - return; - - // Calculate the side angles. - var sideAngleLeft = Mathf.Atan2(localSide.x, localSide.y); - var sideAngleRight = sideAngleLeft + Mathf.PI; - - // Fetch the side arc. - var sideArc = Mathf.Clamp(effector.sideArc, 0.5f, 180.0f); - var halfSideArcRadians = sideArc * 0.5f * Mathf.Deg2Rad; - - var fromAngleLeft = new Vector3(Mathf.Sin(sideAngleLeft - halfSideArcRadians), Mathf.Cos(sideAngleLeft - halfSideArcRadians), 0.0f); - var toAngleLeft = new Vector3(Mathf.Sin(sideAngleLeft + halfSideArcRadians), Mathf.Cos(sideAngleLeft + halfSideArcRadians), 0.0f); - var fromAngleRight = new Vector3(Mathf.Sin(sideAngleRight - halfSideArcRadians), Mathf.Cos(sideAngleRight - halfSideArcRadians), 0.0f); - var toAngleRight = new Vector3(Mathf.Sin(sideAngleRight + halfSideArcRadians), Mathf.Cos(sideAngleRight + halfSideArcRadians), 0.0f); - - // Fetch all the effector-collider bounds. - foreach (var collider in effector.gameObject.GetComponents().Where(collider => collider.enabled && collider.usedByEffector)) - { - var center = collider.bounds.center; - var arcRadius = HandleUtility.GetHandleSize(center) * 0.8f; - - // arc background - Handles.color = new Color(0, 1, 0.7f, 0.07f); - Handles.DrawSolidArc(center, Vector3.back, fromAngleLeft, sideArc, arcRadius); - Handles.DrawSolidArc(center, Vector3.back, fromAngleRight, sideArc, arcRadius); - - // arc frame - Handles.color = new Color(0, 1, 0.7f, 0.7f); - Handles.DrawWireArc(center, Vector3.back, fromAngleLeft, sideArc, arcRadius); - Handles.DrawWireArc(center, Vector3.back, fromAngleRight, sideArc, arcRadius); - Handles.DrawDottedLine(center, center + fromAngleLeft * arcRadius, 5.0f); - Handles.DrawDottedLine(center, center + toAngleLeft * arcRadius, 5.0f); - Handles.DrawDottedLine(center, center + fromAngleRight * arcRadius, 5.0f); - Handles.DrawDottedLine(center, center + toAngleRight * arcRadius, 5.0f); - } - } - } -} diff --git a/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsEditor.cs b/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsEditor.cs index 2c022b45dc..370285f953 100644 --- a/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsEditor.cs +++ b/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsEditor.cs @@ -142,9 +142,9 @@ class SettingsContent public static readonly GUIContent appleDeveloperTeamID = EditorGUIUtility.TrTextContent("iOS Developer Team ID", "Developers can retrieve their Team ID by visiting the Apple Developer site under Account > Membership."); public static readonly GUIContent useOnDemandResources = EditorGUIUtility.TrTextContent("Use on demand resources*"); public static readonly GUIContent accelerometerFrequency = EditorGUIUtility.TrTextContent("Accelerometer Frequency*"); - public static readonly GUIContent cameraUsageDescription = EditorGUIUtility.TrTextContent("Camera Usage Description*"); - public static readonly GUIContent locationUsageDescription = EditorGUIUtility.TrTextContent("Location Usage Description*"); - public static readonly GUIContent microphoneUsageDescription = EditorGUIUtility.TrTextContent("Microphone Usage Description*"); + public static readonly GUIContent cameraUsageDescription = EditorGUIUtility.TrTextContent("Camera Usage Description*", "String shown to the user when requesting permission to use the device camera. Written to the NSCameraUsageDescription field in Xcode project's info.plist file"); + public static readonly GUIContent locationUsageDescription = EditorGUIUtility.TrTextContent("Location Usage Description*", "String shown to the user when requesting permission to access the device location. Written to the NSLocationWhenInUseUsageDescription field in Xcode project's info.plist file."); + public static readonly GUIContent microphoneUsageDescription = EditorGUIUtility.TrTextContent("Microphone Usage Description*", "String shown to the user when requesting to use the device microphone. Written to the NSMicrophoneUsageDescription field in Xcode project's info.plist file"); public static readonly GUIContent muteOtherAudioSources = EditorGUIUtility.TrTextContent("Mute Other Audio Sources*"); public static readonly GUIContent prepareIOSForRecording = EditorGUIUtility.TrTextContent("Prepare iOS for Recording"); public static readonly GUIContent forceIOSSpeakersWhenRecording = EditorGUIUtility.TrTextContent("Force iOS Speakers when Recording"); @@ -168,6 +168,7 @@ class SettingsContent public static readonly GUIContent managedStrippingLevel = EditorGUIUtility.TrTextContent("Managed Stripping Level", "If scripting backend is IL2CPP, managed stripping can't be disabled."); public static readonly GUIContent il2cppCompilerConfiguration = EditorGUIUtility.TrTextContent("C++ Compiler Configuration"); public static readonly GUIContent scriptingMono2x = EditorGUIUtility.TrTextContent("Mono"); + public static readonly GUIContent scriptingMono2xDeprecated = EditorGUIUtility.TrTextContent("Mono (Deprecated)"); public static readonly GUIContent scriptingWinRTDotNET = EditorGUIUtility.TrTextContent(".NET"); public static readonly GUIContent scriptingIL2CPP = EditorGUIUtility.TrTextContent("IL2CPP"); public static readonly GUIContent scriptingDefault = EditorGUIUtility.TrTextContent("Default"); @@ -1136,6 +1137,14 @@ void OpenGLES31OptionsGUI(BuildTargetGroup targetGroup, BuildTarget targetPlatfo void GraphicsAPIsGUIOnePlatform(BuildTargetGroup targetGroup, BuildTarget targetPlatform, string platformTitle) { + // Facebook on windows must be always DX11 + // TODO: Remove this when Facebook platform support contract is over + if (targetGroup == BuildTargetGroup.Facebook && + (targetPlatform == BuildTarget.StandaloneWindows || targetPlatform == BuildTarget.StandaloneWindows64)) + { + return; + } + GraphicsDeviceType[] availableDevices = PlayerSettings.GetSupportedGraphicsAPIs(targetPlatform); // if no devices (e.g. no platform module), or we only have one possible choice, then no // point in having any UI @@ -1697,10 +1706,10 @@ private void OtherSectionRenderingGUI(BuildPlatform platform, BuildTargetGroup t EditorGUI.BeginChangeCheck(); LightmapEncodingQuality encodingQuality = PlayerSettings.GetLightmapEncodingQualityForPlatformGroup(targetGroup); LightmapEncodingQuality[] lightmapEncodingValues = {LightmapEncodingQuality.Normal, LightmapEncodingQuality.High}; - encodingQuality = BuildEnumPopup(SettingsContent.lightmapEncodingLabel, encodingQuality, lightmapEncodingValues, SettingsContent.lightmapEncodingNames); - if (EditorGUI.EndChangeCheck()) + LightmapEncodingQuality newEncodingQuality = BuildEnumPopup(SettingsContent.lightmapEncodingLabel, encodingQuality, lightmapEncodingValues, SettingsContent.lightmapEncodingNames); + if (EditorGUI.EndChangeCheck() && encodingQuality != newEncodingQuality) { - PlayerSettings.SetLightmapEncodingQualityForPlatformGroup(targetGroup, encodingQuality); + PlayerSettings.SetLightmapEncodingQualityForPlatformGroup(targetGroup, newEncodingQuality); Lightmapping.OnUpdateLightmapEncoding(targetGroup); @@ -1890,123 +1899,128 @@ private void OtherSectionConfigurationGUI(BuildTargetGroup targetGroup, ISetting // Configuration GUILayout.Label(SettingsContent.configurationTitle, EditorStyles.boldLabel); - // Scripting Runtime Version - var scriptingRuntimeVersions = new[] {ScriptingRuntimeVersion.Legacy, ScriptingRuntimeVersion.Latest}; - var scriptingRuntimeVersionNames = new[] {SettingsContent.scriptingRuntimeVersionLegacy, SettingsContent.scriptingRuntimeVersionLatest}; - var newScriptingRuntimeVersions = PlayerSettings.scriptingRuntimeVersion; - - if (EditorApplication.isPlaying) - { - var current = PlayerSettings.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy ? SettingsContent.scriptingRuntimeVersionLegacy : SettingsContent.scriptingRuntimeVersionLatest; - BuildDisabledEnumPopup(current, SettingsContent.scriptingRuntimeVersion); - } - else + // scripting runtime settings in play mode are not supported + using (new EditorGUI.DisabledScope(EditorApplication.isPlaying)) { - newScriptingRuntimeVersions = BuildEnumPopup(SettingsContent.scriptingRuntimeVersion, PlayerSettings.scriptingRuntimeVersion, scriptingRuntimeVersions, scriptingRuntimeVersionNames); - } - - if (EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy) - { - EditorGUILayout.HelpBox(SettingsContent.scriptingRuntimeVersionDeprecationWarning.text, MessageType.Warning); - } - - if (PlayerSettings.scriptingRuntimeVersion != EditorApplication.scriptingRuntimeVersion) - { - var activeScriptingRuntime = EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy ? SettingsContent.scriptingRuntimeVersionLegacy : SettingsContent.scriptingRuntimeVersionLatest; - BuildDisabledEnumPopup(activeScriptingRuntime, SettingsContent.scriptingRuntimeVersionActive); - - EditorGUILayout.HelpBox(SettingsContent.scriptingRuntimeVersionActiveWarning.text, MessageType.Warning); - } + // Scripting Runtime Version + var scriptingRuntimeVersions = new[] {ScriptingRuntimeVersion.Legacy, ScriptingRuntimeVersion.Latest}; + var scriptingRuntimeVersionNames = new[] {SettingsContent.scriptingRuntimeVersionLegacy, SettingsContent.scriptingRuntimeVersionLatest}; + var newScriptingRuntimeVersions = PlayerSettings.scriptingRuntimeVersion; - if (newScriptingRuntimeVersions != PlayerSettings.scriptingRuntimeVersion) - { - if (newScriptingRuntimeVersions == EditorApplication.scriptingRuntimeVersion) + if (EditorApplication.isPlaying) { - PlayerSettings.scriptingRuntimeVersion = newScriptingRuntimeVersions; + var current = PlayerSettings.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy ? SettingsContent.scriptingRuntimeVersionLegacy : SettingsContent.scriptingRuntimeVersionLatest; + BuildDisabledEnumPopup(current, SettingsContent.scriptingRuntimeVersion); } else { - var currentScriptingRuntimeVersions = PlayerSettings.scriptingRuntimeVersion; - PlayerSettings.scriptingRuntimeVersion = newScriptingRuntimeVersions; + newScriptingRuntimeVersions = BuildEnumPopup(SettingsContent.scriptingRuntimeVersion, PlayerSettings.scriptingRuntimeVersion, scriptingRuntimeVersions, scriptingRuntimeVersionNames); + } - if (!PlayerSettings.RelaunchProjectIfScriptRuntimeVersionHasChanged()) - { - PlayerSettings.scriptingRuntimeVersion = currentScriptingRuntimeVersions; - } + if (EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy) + { + EditorGUILayout.HelpBox(SettingsContent.scriptingRuntimeVersionDeprecationWarning.text, MessageType.Warning); } - } - // Scripting back-end - IScriptingImplementations scripting = ModuleManager.GetScriptingImplementations(targetGroup); - bool targetGroupSupportsIl2Cpp = false; - bool currentBackendIsIl2Cpp = false; + if (PlayerSettings.scriptingRuntimeVersion != EditorApplication.scriptingRuntimeVersion) + { + var activeScriptingRuntime = EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy ? SettingsContent.scriptingRuntimeVersionLegacy : SettingsContent.scriptingRuntimeVersionLatest; + BuildDisabledEnumPopup(activeScriptingRuntime, SettingsContent.scriptingRuntimeVersionActive); - if (scripting == null) - { - BuildDisabledEnumPopup(SettingsContent.scriptingDefault, SettingsContent.scriptingBackend); - } - else - { - var backends = scripting.Enabled(); + EditorGUILayout.HelpBox(SettingsContent.scriptingRuntimeVersionActiveWarning.text, MessageType.Warning); + } - foreach (var backend in backends) + if (newScriptingRuntimeVersions != PlayerSettings.scriptingRuntimeVersion) { - if (backend == ScriptingImplementation.IL2CPP) + if (newScriptingRuntimeVersions == EditorApplication.scriptingRuntimeVersion) { - targetGroupSupportsIl2Cpp = true; - break; + PlayerSettings.scriptingRuntimeVersion = newScriptingRuntimeVersions; + } + else + { + var currentScriptingRuntimeVersions = PlayerSettings.scriptingRuntimeVersion; + PlayerSettings.scriptingRuntimeVersion = newScriptingRuntimeVersions; + + if (!PlayerSettings.RelaunchProjectIfScriptRuntimeVersionHasChanged()) + { + PlayerSettings.scriptingRuntimeVersion = currentScriptingRuntimeVersions; + } } } - ScriptingImplementation currBackend = PlayerSettings.GetScriptingBackend(targetGroup); - currentBackendIsIl2Cpp = currBackend == ScriptingImplementation.IL2CPP; - ScriptingImplementation newBackend; + // Scripting back-end + IScriptingImplementations scripting = ModuleManager.GetScriptingImplementations(targetGroup); + bool targetGroupSupportsIl2Cpp = false; + bool currentBackendIsIl2Cpp = false; - if (targetGroup == BuildTargetGroup.tvOS) - { - newBackend = ScriptingImplementation.IL2CPP; - PlayerSettingsEditor.BuildDisabledEnumPopup(SettingsContent.scriptingIL2CPP, SettingsContent.scriptingBackend); - } - else if (backends.Length == 1) + if (scripting == null) { - newBackend = backends[0]; - BuildDisabledEnumPopup(GetNiceScriptingBackendName(backends[0]), SettingsContent.scriptingBackend); + BuildDisabledEnumPopup(SettingsContent.scriptingDefault, SettingsContent.scriptingBackend); } else { - newBackend = BuildEnumPopup(SettingsContent.scriptingBackend, currBackend, backends, GetNiceScriptingBackendNames(backends)); - } + var backends = scripting.Enabled(); - if (targetGroup == BuildTargetGroup.iOS && newBackend == ScriptingImplementation.Mono2x) - { - EditorGUILayout.HelpBox(SettingsContent.monoNotSupportediOS11WarningGUIContent.text, MessageType.Warning); - } + foreach (var backend in backends) + { + if (backend == ScriptingImplementation.IL2CPP) + { + targetGroupSupportsIl2Cpp = true; + break; + } + } - if (newBackend != currBackend) - PlayerSettings.SetScriptingBackend(targetGroup, newBackend); - } + ScriptingImplementation currBackend = PlayerSettings.GetScriptingBackend(targetGroup); + currentBackendIsIl2Cpp = currBackend == ScriptingImplementation.IL2CPP; + ScriptingImplementation newBackend; + var mono2xDeprecated = targetGroup == BuildTargetGroup.iOS; - // Api Compatibility Level - var currentCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(targetGroup); - var availableCompatibilityLevels = GetAvailableApiCompatibilityLevels(targetGroup); + if (targetGroup == BuildTargetGroup.tvOS) + { + newBackend = ScriptingImplementation.IL2CPP; + PlayerSettingsEditor.BuildDisabledEnumPopup(SettingsContent.scriptingIL2CPP, SettingsContent.scriptingBackend); + } + else if (backends.Length == 1) + { + newBackend = backends[0]; + BuildDisabledEnumPopup(GetNiceScriptingBackendName(backends[0], mono2xDeprecated), SettingsContent.scriptingBackend); + } + else + { + newBackend = BuildEnumPopup(SettingsContent.scriptingBackend, currBackend, backends, GetNiceScriptingBackendNames(backends, mono2xDeprecated)); + } + + if (targetGroup == BuildTargetGroup.iOS && newBackend == ScriptingImplementation.Mono2x) + { + EditorGUILayout.HelpBox(SettingsContent.monoNotSupportediOS11WarningGUIContent.text, MessageType.Warning); + } + + if (newBackend != currBackend) + PlayerSettings.SetScriptingBackend(targetGroup, newBackend); + } - var newCompatibilityLevel = BuildEnumPopup(SettingsContent.apiCompatibilityLevel, currentCompatibilityLevel, availableCompatibilityLevels, GetNiceApiCompatibilityLevelNames(availableCompatibilityLevels)); + // Api Compatibility Level + var currentCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(targetGroup); + var availableCompatibilityLevels = GetAvailableApiCompatibilityLevels(targetGroup); - if (currentCompatibilityLevel != newCompatibilityLevel) - PlayerSettings.SetApiCompatibilityLevel(targetGroup, newCompatibilityLevel); + var newCompatibilityLevel = BuildEnumPopup(SettingsContent.apiCompatibilityLevel, currentCompatibilityLevel, availableCompatibilityLevels, GetNiceApiCompatibilityLevelNames(availableCompatibilityLevels)); - if (targetGroupSupportsIl2Cpp) - { - using (new EditorGUI.DisabledScope(!currentBackendIsIl2Cpp || !scripting.AllowIL2CPPCompilerConfigurationSelection())) + if (currentCompatibilityLevel != newCompatibilityLevel) + PlayerSettings.SetApiCompatibilityLevel(targetGroup, newCompatibilityLevel); + + if (targetGroupSupportsIl2Cpp) { - var currentConfiguration = PlayerSettings.GetIl2CppCompilerConfiguration(targetGroup); - var configurations = GetIl2CppCompilerConfigurations(); - var configurationNames = GetIl2CppCompilerConfigurationNames(); + using (new EditorGUI.DisabledScope(!currentBackendIsIl2Cpp || !scripting.AllowIL2CPPCompilerConfigurationSelection())) + { + var currentConfiguration = PlayerSettings.GetIl2CppCompilerConfiguration(targetGroup); + var configurations = GetIl2CppCompilerConfigurations(); + var configurationNames = GetIl2CppCompilerConfigurationNames(); - var newConfiguration = BuildEnumPopup(SettingsContent.il2cppCompilerConfiguration, currentConfiguration, configurations, configurationNames); + var newConfiguration = BuildEnumPopup(SettingsContent.il2cppCompilerConfiguration, currentConfiguration, configurations, configurationNames); - if (currentConfiguration != newConfiguration) - PlayerSettings.SetIl2CppCompilerConfiguration(targetGroup, newConfiguration); + if (currentConfiguration != newConfiguration) + PlayerSettings.SetIl2CppCompilerConfiguration(targetGroup, newConfiguration); + } } } @@ -2313,7 +2327,6 @@ private void OtherSectionLegacyGUI() EditorGUILayout.Space(); } - private static Dictionary m_NiceScriptingBackendNames; private static Dictionary m_NiceApiCompatibilityLevelNames; private static Dictionary m_NiceManagedStrippingLevelNames; @@ -2331,31 +2344,26 @@ private static GUIContent[] GetGUIContentsForValues(Dictionary return names; } - private static GUIContent[] GetNiceScriptingBackendNames(ScriptingImplementation[] scriptingBackends) + static GUIContent[] GetNiceScriptingBackendNames(ScriptingImplementation[] scriptingBackends, bool mono2xDeprecated) { - InitializeNiceScriptingBackendNames(); - return GetGUIContentsForValues(m_NiceScriptingBackendNames, scriptingBackends); + return scriptingBackends.Select(s => GetNiceScriptingBackendName(s, mono2xDeprecated)).ToArray(); } - static void InitializeNiceScriptingBackendNames() + static GUIContent GetNiceScriptingBackendName(ScriptingImplementation scriptingBackend, bool mono2xDeprecated) { - if (m_NiceScriptingBackendNames == null) + switch (scriptingBackend) { - m_NiceScriptingBackendNames = new Dictionary - { - { ScriptingImplementation.Mono2x, SettingsContent.scriptingMono2x }, - { ScriptingImplementation.WinRTDotNET, SettingsContent.scriptingWinRTDotNET }, - { ScriptingImplementation.IL2CPP, SettingsContent.scriptingIL2CPP } - }; + case ScriptingImplementation.Mono2x: + return mono2xDeprecated ? SettingsContent.scriptingMono2xDeprecated : SettingsContent.scriptingMono2x; + case ScriptingImplementation.IL2CPP: + return SettingsContent.scriptingIL2CPP; + case ScriptingImplementation.WinRTDotNET: + return SettingsContent.scriptingWinRTDotNET; + default: + throw new ArgumentException($"Scripting backend value {scriptingBackend} is not supported.", nameof(scriptingBackend)); } } - private static GUIContent GetNiceScriptingBackendName(ScriptingImplementation scriptingBackend) - { - InitializeNiceScriptingBackendNames(); - return GetGUIContentsForValues(m_NiceScriptingBackendNames, new[] { scriptingBackend }).First(); - } - private static GUIContent[] GetNiceApiCompatibilityLevelNames(ApiCompatibilityLevel[] apiCompatibilityLevels) { if (m_NiceApiCompatibilityLevelNames == null) diff --git a/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.cs b/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.cs deleted file mode 100644 index bf2cc635cb..0000000000 --- a/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.cs +++ /dev/null @@ -1,399 +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 UnityEditor.AnimatedValues; -using UnityEditor.Modules; -using UnityEditorInternal; -using UnityEngine.Rendering; -using UnityEngine; -using UnityEditor.Build; - -namespace UnityEditor -{ - internal partial class PlayerSettingsSplashScreenEditor - { - PlayerSettingsEditor m_Owner; - - SerializedProperty m_ResolutionDialogBanner; - SerializedProperty m_ShowUnitySplashLogo; - SerializedProperty m_ShowUnitySplashScreen; - SerializedProperty m_SplashScreenAnimation; - SerializedProperty m_SplashScreenBackgroundAnimationZoom; - SerializedProperty m_SplashScreenBackgroundColor; - SerializedProperty m_SplashScreenBackgroundLandscape; - SerializedProperty m_SplashScreenBackgroundPortrait; - SerializedProperty m_SplashScreenDrawMode; - SerializedProperty m_SplashScreenLogoAnimationZoom; - SerializedProperty m_SplashScreenLogos; - SerializedProperty m_SplashScreenLogoStyle; - SerializedProperty m_SplashScreenOverlayOpacity; - SerializedProperty m_VirtualRealitySplashScreen; - - ReorderableList m_LogoList; - - float m_TotalLogosDuration; - - static readonly float k_MinLogoTime = 2; - static readonly float k_MaxLogoTime = 10.0f; - static readonly float k_DefaultLogoTime = 2.0f; - - static readonly float k_LogoListElementHeight = 72; - static readonly float k_LogoListLogoFieldHeight = 64; - static readonly float k_LogoListFooterHeight = 20; - static readonly float k_LogoListUnityLogoMinWidth = 64; - static readonly float k_LogoListUnityLogoMaxWidth = 220; - static readonly float k_LogoListPropertyMinWidth = 230; - static readonly float k_LogoListPropertyLabelWidth = 100; - static readonly float k_MinPersonalEditionOverlayOpacity = 0.5f; - static readonly float k_MinProEditionOverlayOpacity = 0.0f; - - static Sprite s_UnityLogo; - - readonly AnimBool m_ShowAnimationControlsAnimator = new AnimBool(); - readonly AnimBool m_ShowBackgroundColorAnimator = new AnimBool(); - readonly AnimBool m_ShowLogoControlsAnimator = new AnimBool(); - - class Texts - { - public GUIContent animate = EditorGUIUtility.TrTextContent("Animation"); - public GUIContent backgroundColor = EditorGUIUtility.TrTextContent("Background Color", "Background color when no background image is used."); - public GUIContent backgroundImage = EditorGUIUtility.TrTextContent("Background Image", "Image to be used in landscape and portrait(when portrait image is not set)."); - public GUIContent backgroundPortraitImage = EditorGUIUtility.TrTextContent("Alternate Portrait Image*", "Optional image to be used in portrait mode."); - public GUIContent backgroundTitle = EditorGUIUtility.TrTextContent("Background*"); - public GUIContent backgroundZoom = EditorGUIUtility.TrTextContent("Background Zoom"); - public GUIContent configDialogBanner = EditorGUIUtility.TrTextContent("Application Config Dialog Banner"); - public GUIContent drawMode = EditorGUIUtility.TrTextContent("Draw Mode"); - public GUIContent logoDuration = EditorGUIUtility.TrTextContent("Logo Duration", "The time the logo will be shown for."); - public GUIContent logosTitle = EditorGUIUtility.TrTextContent("Logos*"); - public GUIContent logoZoom = EditorGUIUtility.TrTextContent("Logo Zoom"); - public GUIContent overlayOpacity = EditorGUIUtility.TrTextContent("Overlay Opacity", "Overlay strength applied to improve logo visibility."); - public GUIContent previewSplash = EditorGUIUtility.TrTextContent("Preview", "Preview the splash screen in the game view."); - public GUIContent showLogo = EditorGUIUtility.TrTextContent("Show Unity Logo"); - public GUIContent showSplash = EditorGUIUtility.TrTextContent("Show Splash Screen"); - public GUIContent splashStyle = EditorGUIUtility.TrTextContent("Splash Style"); - public GUIContent splashTitle = EditorGUIUtility.TrTextContent("Splash Screen"); - public GUIContent title = EditorGUIUtility.TrTextContent("Splash Image"); - public GUIContent vrSplashScreen = EditorGUIUtility.TrTextContent("Virtual Reality Splash Image"); - } - static readonly Texts k_Texts = new Texts(); - - public PlayerSettingsSplashScreenEditor(PlayerSettingsEditor owner) - { - m_Owner = owner; - } - - public void OnEnable() - { - m_ResolutionDialogBanner = m_Owner.FindPropertyAssert("resolutionDialogBanner"); - m_ShowUnitySplashLogo = m_Owner.FindPropertyAssert("m_ShowUnitySplashLogo"); - m_ShowUnitySplashScreen = m_Owner.FindPropertyAssert("m_ShowUnitySplashScreen"); - m_SplashScreenAnimation = m_Owner.FindPropertyAssert("m_SplashScreenAnimation"); - m_SplashScreenBackgroundAnimationZoom = m_Owner.FindPropertyAssert("m_SplashScreenBackgroundAnimationZoom"); - m_SplashScreenBackgroundColor = m_Owner.FindPropertyAssert("m_SplashScreenBackgroundColor"); - m_SplashScreenBackgroundLandscape = m_Owner.FindPropertyAssert("splashScreenBackgroundSourceLandscape"); - m_SplashScreenBackgroundPortrait = m_Owner.FindPropertyAssert("splashScreenBackgroundSourcePortrait"); - m_SplashScreenDrawMode = m_Owner.FindPropertyAssert("m_SplashScreenDrawMode"); - m_SplashScreenLogoAnimationZoom = m_Owner.FindPropertyAssert("m_SplashScreenLogoAnimationZoom"); - m_SplashScreenLogos = m_Owner.FindPropertyAssert("m_SplashScreenLogos"); - m_SplashScreenLogoStyle = m_Owner.FindPropertyAssert("m_SplashScreenLogoStyle"); - m_SplashScreenOverlayOpacity = m_Owner.FindPropertyAssert("m_SplashScreenOverlayOpacity"); - m_VirtualRealitySplashScreen = m_Owner.FindPropertyAssert("m_VirtualRealitySplashScreen"); - - m_LogoList = new ReorderableList(m_Owner.serializedObject, m_SplashScreenLogos, true, true, true, true); - m_LogoList.elementHeight = k_LogoListElementHeight; - m_LogoList.footerHeight = k_LogoListFooterHeight; - m_LogoList.onAddCallback = OnLogoListAddCallback; - m_LogoList.drawHeaderCallback = DrawLogoListHeaderCallback; - m_LogoList.onCanRemoveCallback = OnLogoListCanRemoveCallback; - m_LogoList.drawElementCallback = DrawLogoListElementCallback; - m_LogoList.drawFooterCallback = DrawLogoListFooterCallback; - - // Set up animations - m_ShowAnimationControlsAnimator.value = m_SplashScreenAnimation.intValue == (int)PlayerSettings.SplashScreen.AnimationMode.Custom; - m_ShowAnimationControlsAnimator.valueChanged.AddListener(m_Owner.Repaint); - m_ShowBackgroundColorAnimator.value = m_SplashScreenBackgroundLandscape.objectReferenceValue == null; - m_ShowBackgroundColorAnimator.valueChanged.AddListener(m_Owner.Repaint); - m_ShowLogoControlsAnimator.value = m_ShowUnitySplashLogo.boolValue; - m_ShowLogoControlsAnimator.valueChanged.AddListener(m_Owner.Repaint); - - if (s_UnityLogo == null) - s_UnityLogo = Resources.GetBuiltinResource("UnitySplash-cube.png"); - } - - private void DrawLogoListHeaderCallback(Rect rect) - { - m_TotalLogosDuration = 0; // Calculated during logo list draw - EditorGUI.LabelField(rect, "Logos"); - } - - private void DrawElementUnityLogo(Rect rect, int index, bool isActive, bool isFocused) - { - var element = m_SplashScreenLogos.GetArrayElementAtIndex(index); - var duration = element.FindPropertyRelative("duration"); - - // Unity logo - float logoWidth = Mathf.Clamp(rect.width - k_LogoListPropertyMinWidth, k_LogoListUnityLogoMinWidth, k_LogoListUnityLogoMaxWidth); - float logoHeight = logoWidth / (s_UnityLogo.texture.width / (float)s_UnityLogo.texture.height); - var logoRect = new Rect(rect.x, rect.y + (rect.height - logoHeight) / 2.0f, k_LogoListUnityLogoMaxWidth, logoHeight); - var oldCol = GUI.color; - GUI.color = (m_SplashScreenLogoStyle.intValue == (int)PlayerSettings.SplashScreen.UnityLogoStyle.DarkOnLight ? Color.black : Color.white); - GUI.Label(logoRect, s_UnityLogo.texture); - GUI.color = oldCol; - - // Properties - var oldLabelWidth = EditorGUIUtility.labelWidth; - EditorGUIUtility.labelWidth = k_LogoListPropertyLabelWidth; - var propertyRect = new Rect(rect.x + logoWidth, rect.y + EditorGUIUtility.standardVerticalSpacing + EditorGUIUtility.singleLineHeight, rect.width - logoWidth, EditorGUIUtility.singleLineHeight); - EditorGUI.BeginChangeCheck(); - var durationLabel = EditorGUI.BeginProperty(propertyRect, k_Texts.logoDuration, duration); - var newDurationVal = EditorGUI.Slider(propertyRect, durationLabel, duration.floatValue, k_MinLogoTime, k_MaxLogoTime); - if (EditorGUI.EndChangeCheck()) - duration.floatValue = newDurationVal; - EditorGUI.EndProperty(); - EditorGUIUtility.labelWidth = oldLabelWidth; - - m_TotalLogosDuration += duration.floatValue; - } - - private void DrawLogoListElementCallback(Rect rect, int index, bool isActive, bool isFocused) - { - rect.height -= EditorGUIUtility.standardVerticalSpacing; - - var element = m_SplashScreenLogos.GetArrayElementAtIndex(index); - var logo = element.FindPropertyRelative("logo"); - - if ((Sprite)logo.objectReferenceValue == s_UnityLogo) - { - DrawElementUnityLogo(rect, index, isActive, isFocused); - return; - } - - // Logo field - float unityLogoWidth = Mathf.Clamp(rect.width - k_LogoListPropertyMinWidth, k_LogoListUnityLogoMinWidth, k_LogoListUnityLogoMaxWidth); - var logoRect = new Rect(rect.x, rect.y + (rect.height - k_LogoListLogoFieldHeight) / 2.0f, k_LogoListUnityLogoMinWidth, k_LogoListLogoFieldHeight); - EditorGUI.BeginChangeCheck(); - var value = EditorGUI.ObjectField(logoRect, GUIContent.none, (Sprite)logo.objectReferenceValue, typeof(Sprite), false); - if (EditorGUI.EndChangeCheck()) - logo.objectReferenceValue = value; - - // Properties - var oldLabelWidth = EditorGUIUtility.labelWidth; - EditorGUIUtility.labelWidth = k_LogoListPropertyLabelWidth; - var propertyRect = new Rect(rect.x + unityLogoWidth, rect.y + EditorGUIUtility.standardVerticalSpacing + EditorGUIUtility.singleLineHeight, rect.width - unityLogoWidth, EditorGUIUtility.singleLineHeight); - EditorGUI.BeginChangeCheck(); - var duration = element.FindPropertyRelative("duration"); - var newDurationVal = EditorGUI.Slider(propertyRect, k_Texts.logoDuration, duration.floatValue, k_MinLogoTime, k_MaxLogoTime); - if (EditorGUI.EndChangeCheck()) - duration.floatValue = newDurationVal; - - EditorGUIUtility.labelWidth = oldLabelWidth; - - m_TotalLogosDuration += duration.floatValue; - } - - private void DrawLogoListFooterCallback(Rect rect) - { - float totalDuration = Mathf.Max(k_MinLogoTime, m_TotalLogosDuration); - EditorGUI.LabelField(rect, "Splash Screen Duration: " + totalDuration.ToString(), EditorStyles.miniBoldLabel); - ReorderableList.defaultBehaviours.DrawFooter(rect, m_LogoList); - } - - private void OnLogoListAddCallback(ReorderableList list) - { - int index = m_SplashScreenLogos.arraySize; - m_SplashScreenLogos.InsertArrayElementAtIndex(m_SplashScreenLogos.arraySize); - var element = m_SplashScreenLogos.GetArrayElementAtIndex(index); - - // Set up default values. - var logo = element.FindPropertyRelative("logo"); - var duration = element.FindPropertyRelative("duration"); - logo.objectReferenceValue = null; - duration.floatValue = k_DefaultLogoTime; - } - - // Prevent users removing the unity logo. - private static bool OnLogoListCanRemoveCallback(ReorderableList list) - { - var element = list.serializedProperty.GetArrayElementAtIndex(list.index); - var logo = (Sprite)element.FindPropertyRelative("logo").objectReferenceValue; - return logo != s_UnityLogo; - } - - private void AddUnityLogoToLogosList() - { - // Only add a logo if one does not already exist. - for (int i = 0; i < m_SplashScreenLogos.arraySize; ++i) - { - var listElement = m_SplashScreenLogos.GetArrayElementAtIndex(i); - var listLogo = listElement.FindPropertyRelative("logo"); - if ((Sprite)listLogo.objectReferenceValue == s_UnityLogo) - return; - } - - m_SplashScreenLogos.InsertArrayElementAtIndex(0); - var element = m_SplashScreenLogos.GetArrayElementAtIndex(0); - var logo = element.FindPropertyRelative("logo"); - var duration = element.FindPropertyRelative("duration"); - logo.objectReferenceValue = s_UnityLogo; - duration.floatValue = k_DefaultLogoTime; - } - - private void RemoveUnityLogoFromLogosList() - { - for (int i = 0; i < m_SplashScreenLogos.arraySize; ++i) - { - var element = m_SplashScreenLogos.GetArrayElementAtIndex(i); - var logo = element.FindPropertyRelative("logo"); - if ((Sprite)logo.objectReferenceValue == s_UnityLogo) - { - m_SplashScreenLogos.DeleteArrayElementAtIndex(i); - --i; // Continue checking in case we have duplicates. - } - } - } - - private static bool TargetSupportsOptionalBuiltinSplashScreen(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension) - { - if (settingsExtension != null) - return settingsExtension.CanShowUnitySplashScreen(); - return targetGroup == BuildTargetGroup.Standalone; - } - - private static void ObjectReferencePropertyField(SerializedProperty property, GUIContent label) where T : UnityEngine.Object - { - EditorGUI.BeginChangeCheck(); - Rect r = EditorGUILayout.GetControlRect(true, 64, EditorStyles.objectFieldThumb); - label = EditorGUI.BeginProperty(r, label, property); - var value = EditorGUI.ObjectField(r, label, (T)property.objectReferenceValue, typeof(T), false); - if (EditorGUI.EndChangeCheck()) - { - property.objectReferenceValue = value; - GUI.changed = true; - } - EditorGUI.EndProperty(); - } - - public void SplashSectionGUI(BuildPlatform platform, BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension, int sectionIndex = 2) - { - GUI.changed = false; - if (m_Owner.BeginSettingsBox(sectionIndex, k_Texts.title)) - { - if (targetGroup == BuildTargetGroup.Standalone) - { - ObjectReferencePropertyField(m_ResolutionDialogBanner, k_Texts.configDialogBanner); - EditorGUILayout.Space(); - } - - if (m_Owner.m_VRSettings.TargetGroupSupportsVirtualReality(targetGroup)) - ObjectReferencePropertyField(m_VirtualRealitySplashScreen, k_Texts.vrSplashScreen); - - if (TargetSupportsOptionalBuiltinSplashScreen(targetGroup, settingsExtension)) - BuiltinCustomSplashScreenGUI(); - - if (settingsExtension != null) - settingsExtension.SplashSectionGUI(); - - if (m_ShowUnitySplashScreen.boolValue) - m_Owner.ShowSharedNote(); - } - m_Owner.EndSettingsBox(); - } - - private void BuiltinCustomSplashScreenGUI() - { - EditorGUILayout.LabelField(k_Texts.splashTitle, EditorStyles.boldLabel); - - using (new EditorGUI.DisabledScope(!licenseAllowsDisabling)) - { - EditorGUILayout.PropertyField(m_ShowUnitySplashScreen, k_Texts.showSplash); - if (!m_ShowUnitySplashScreen.boolValue) - return; - } - - Rect previewButtonRect = GUILayoutUtility.GetRect(k_Texts.previewSplash, "button"); - previewButtonRect = EditorGUI.PrefixLabel(previewButtonRect, new GUIContent(" ")); - if (GUI.Button(previewButtonRect, k_Texts.previewSplash)) - { - SplashScreen.Begin(); - - var gv = GameView.GetMainGameView(); - if (gv) - gv.Focus(); - - GameView.RepaintAll(); - } - - EditorGUILayout.PropertyField(m_SplashScreenLogoStyle, k_Texts.splashStyle); - - // Animation - EditorGUILayout.PropertyField(m_SplashScreenAnimation, k_Texts.animate); - m_ShowAnimationControlsAnimator.target = m_SplashScreenAnimation.intValue == (int)PlayerSettings.SplashScreen.AnimationMode.Custom; - - if (EditorGUILayout.BeginFadeGroup(m_ShowAnimationControlsAnimator.faded)) - { - EditorGUI.indentLevel++; - EditorGUILayout.Slider(m_SplashScreenLogoAnimationZoom, 0.0f, 1.0f, k_Texts.logoZoom); - EditorGUILayout.Slider(m_SplashScreenBackgroundAnimationZoom, 0.0f, 1.0f, k_Texts.backgroundZoom); - EditorGUI.indentLevel--; - } - EditorGUILayout.EndFadeGroup(); - - EditorGUILayout.Space(); - - // Logos - EditorGUILayout.LabelField(k_Texts.logosTitle, EditorStyles.boldLabel); - using (new EditorGUI.DisabledScope(!Application.HasProLicense())) - { - EditorGUI.BeginChangeCheck(); - EditorGUILayout.PropertyField(m_ShowUnitySplashLogo, k_Texts.showLogo); - if (EditorGUI.EndChangeCheck()) - { - if (!m_ShowUnitySplashLogo.boolValue) - RemoveUnityLogoFromLogosList(); - else if (m_SplashScreenDrawMode.intValue == (int)PlayerSettings.SplashScreen.DrawMode.AllSequential) - AddUnityLogoToLogosList(); - } - - m_ShowLogoControlsAnimator.target = m_ShowUnitySplashLogo.boolValue; - } - - if (EditorGUILayout.BeginFadeGroup(m_ShowLogoControlsAnimator.faded)) - { - EditorGUI.indentLevel++; - EditorGUI.BeginChangeCheck(); - var oldDrawmode = m_SplashScreenDrawMode.intValue; - EditorGUILayout.PropertyField(m_SplashScreenDrawMode, k_Texts.drawMode); - if (oldDrawmode != m_SplashScreenDrawMode.intValue) - { - if (m_SplashScreenDrawMode.intValue == (int)PlayerSettings.SplashScreen.DrawMode.UnityLogoBelow) - RemoveUnityLogoFromLogosList(); - else - AddUnityLogoToLogosList(); - } - EditorGUI.indentLevel--; - } - EditorGUILayout.EndFadeGroup(); - - m_LogoList.DoLayoutList(); - EditorGUILayout.Space(); - - // Background - EditorGUILayout.LabelField(k_Texts.backgroundTitle, EditorStyles.boldLabel); - EditorGUILayout.Slider(m_SplashScreenOverlayOpacity, Application.HasProLicense() ? k_MinProEditionOverlayOpacity : k_MinPersonalEditionOverlayOpacity, 1.0f, k_Texts.overlayOpacity); - m_ShowBackgroundColorAnimator.target = m_SplashScreenBackgroundLandscape.objectReferenceValue == null; - if (EditorGUILayout.BeginFadeGroup(m_ShowBackgroundColorAnimator.faded)) - EditorGUILayout.PropertyField(m_SplashScreenBackgroundColor, k_Texts.backgroundColor); - EditorGUILayout.EndFadeGroup(); - - ObjectReferencePropertyField(m_SplashScreenBackgroundLandscape, k_Texts.backgroundImage); - if (GUI.changed && m_SplashScreenBackgroundLandscape.objectReferenceValue == null) - m_SplashScreenBackgroundPortrait.objectReferenceValue = null; - - using (new EditorGUI.DisabledScope(m_SplashScreenBackgroundLandscape.objectReferenceValue == null)) - { - ObjectReferencePropertyField(m_SplashScreenBackgroundPortrait, k_Texts.backgroundPortraitImage); - } - } - } -} diff --git a/Editor/Mono/Inspector/PlayerSettingsEditor/WebTemplate.cs b/Editor/Mono/Inspector/PlayerSettingsEditor/WebTemplate.cs deleted file mode 100644 index a913b80955..0000000000 --- a/Editor/Mono/Inspector/PlayerSettingsEditor/WebTemplate.cs +++ /dev/null @@ -1,43 +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; - -namespace UnityEditor -{ - internal class WebTemplate - { - public string m_Path, m_Name; - public Texture2D m_Thumbnail; - public string[] m_CustomKeys; - - public string[] CustomKeys - { - get - { - return m_CustomKeys; - } - } - - public override bool Equals(System.Object other) - { - return other is WebTemplate && other.ToString().Equals(ToString()); - } - - public override int GetHashCode() - { - return base.GetHashCode() ^ m_Path.GetHashCode(); - } - - public override string ToString() - { - return m_Path; - } - - public GUIContent ToGUIContent(Texture2D defaultIcon) - { - return new GUIContent(m_Name, m_Thumbnail == null ? defaultIcon : m_Thumbnail); - } - } -} diff --git a/Editor/Mono/Inspector/PointEffector2DEditor.cs b/Editor/Mono/Inspector/PointEffector2DEditor.cs deleted file mode 100644 index 6c875b2b7a..0000000000 --- a/Editor/Mono/Inspector/PointEffector2DEditor.cs +++ /dev/null @@ -1,89 +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.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor.AnimatedValues; - -namespace UnityEditor -{ - /// - /// Prompts the end-user to add 2D colliders if non exist for 2D effector to work with. - /// - [CustomEditor(typeof(PointEffector2D), true)] - [CanEditMultipleObjects] - internal class PointEffector2DEditor : Effector2DEditor - { - readonly AnimBool m_ShowForceRollout = new AnimBool(); - SerializedProperty m_ForceMagnitude; - SerializedProperty m_ForceVariation; - SerializedProperty m_ForceSource; - SerializedProperty m_ForceTarget; - SerializedProperty m_ForceMode; - SerializedProperty m_DistanceScale; - - static readonly AnimBool m_ShowDampingRollout = new AnimBool(); - SerializedProperty m_Drag; - SerializedProperty m_AngularDrag; - - public override void OnEnable() - { - base.OnEnable(); - - m_ShowForceRollout.value = true; - m_ShowForceRollout.valueChanged.AddListener(Repaint); - m_ForceMagnitude = serializedObject.FindProperty("m_ForceMagnitude"); - m_ForceVariation = serializedObject.FindProperty("m_ForceVariation"); - m_ForceSource = serializedObject.FindProperty("m_ForceSource"); - m_ForceTarget = serializedObject.FindProperty("m_ForceTarget"); - m_ForceMode = serializedObject.FindProperty("m_ForceMode"); - m_DistanceScale = serializedObject.FindProperty("m_DistanceScale"); - - m_ShowDampingRollout.valueChanged.AddListener(Repaint); - m_Drag = serializedObject.FindProperty("m_Drag"); - m_AngularDrag = serializedObject.FindProperty("m_AngularDrag"); - } - - public override void OnDisable() - { - base.OnDisable(); - - m_ShowForceRollout.valueChanged.RemoveListener(Repaint); - m_ShowDampingRollout.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - serializedObject.Update(); - - // Force. - m_ShowForceRollout.target = EditorGUILayout.Foldout(m_ShowForceRollout.target, "Force", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowForceRollout.faded)) - { - EditorGUILayout.PropertyField(m_ForceMagnitude); - EditorGUILayout.PropertyField(m_ForceVariation); - EditorGUILayout.PropertyField(m_DistanceScale); - EditorGUILayout.PropertyField(m_ForceSource); - EditorGUILayout.PropertyField(m_ForceTarget); - EditorGUILayout.PropertyField(m_ForceMode); - EditorGUILayout.Space(); - } - EditorGUILayout.EndFadeGroup(); - - // Drag. - m_ShowDampingRollout.target = EditorGUILayout.Foldout(m_ShowDampingRollout.target, "Damping", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowDampingRollout.faded)) - { - EditorGUILayout.PropertyField(m_Drag); - EditorGUILayout.PropertyField(m_AngularDrag); - } - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/PositionConstraintEditor.cs b/Editor/Mono/Inspector/PositionConstraintEditor.cs deleted file mode 100644 index 4d76744b2c..0000000000 --- a/Editor/Mono/Inspector/PositionConstraintEditor.cs +++ /dev/null @@ -1,82 +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.Animations; - -namespace UnityEditor -{ - [CustomEditor(typeof(PositionConstraint))] - [CanEditMultipleObjects] - internal class PositionConstraintEditor : ConstraintEditorBase - { - private SerializedProperty m_TranslationAtRest; - private SerializedProperty m_TranslationOffset; - private SerializedProperty m_Weight; - private SerializedProperty m_IsContraintActive; - private SerializedProperty m_IsLocked; - private SerializedProperty m_Sources; - - internal override SerializedProperty atRest { get { return m_TranslationAtRest; } } - internal override SerializedProperty offset { get { return m_TranslationOffset; } } - internal override SerializedProperty weight { get { return m_Weight; } } - internal override SerializedProperty isContraintActive { get { return m_IsContraintActive; } } - internal override SerializedProperty isLocked { get { return m_IsLocked; } } - internal override SerializedProperty sources { get { return m_Sources; } } - - private class Styles : ConstraintStyleBase - { - GUIContent m_RestTranslation = EditorGUIUtility.TrTextContent("Position At Rest"); - GUIContent m_TranslationOffset = EditorGUIUtility.TrTextContent("Position Offset"); - - GUIContent m_TranslationAxes = EditorGUIUtility.TrTextContent("Freeze Position Axes"); - - public override GUIContent AtRest { get { return m_RestTranslation; } } - public override GUIContent Offset { get { return m_TranslationOffset; } } - public GUIContent FreezeAxes { get { return m_TranslationAxes; } } - } - - private static Styles s_Style; - - public void OnEnable() - { - if (s_Style == null) - s_Style = new Styles(); - - m_TranslationAtRest = serializedObject.FindProperty("m_TranslationAtRest"); - m_TranslationOffset = serializedObject.FindProperty("m_TranslationOffset"); - m_Weight = serializedObject.FindProperty("m_Weight"); - m_IsContraintActive = serializedObject.FindProperty("m_IsContraintActive"); - m_IsLocked = serializedObject.FindProperty("m_IsLocked"); - m_Sources = serializedObject.FindProperty("m_Sources"); - - OnEnable(s_Style); - } - - internal override void OnValueAtRestChanged() - { - foreach (var t in targets) - (t as PositionConstraint).transform.localPosition = atRest.vector3Value; - } - - internal override void ShowFreezeAxesControl() - { - Rect drawRect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector3, s_Style.FreezeAxes), EditorStyles.toggle); - EditorGUI.MultiPropertyField(drawRect, s_Style.Axes, serializedObject.FindProperty("m_AffectTranslationX"), s_Style.FreezeAxes); - } - - public override void OnInspectorGUI() - { - if (s_Style == null) - s_Style = new Styles(); - - serializedObject.Update(); - - ShowConstraintEditor(s_Style); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/PreviewRenderUtility.cs b/Editor/Mono/Inspector/PreviewRenderUtility.cs index 783603be1a..0417154154 100644 --- a/Editor/Mono/Inspector/PreviewRenderUtility.cs +++ b/Editor/Mono/Inspector/PreviewRenderUtility.cs @@ -229,7 +229,7 @@ public void BeginPreview(Rect r, GUIStyle previewBackground) new Rect(0, 0, 1, 1), previewBackground.border.left, previewBackground.border.right, previewBackground.border.top, previewBackground.border.bottom, - new Color(.5f, .5f, .5f, 1), + new Color(.5f, .5f, .5f, 0.5f), null ); diff --git a/Editor/Mono/Inspector/PrimitiveCollider3DEditor.cs b/Editor/Mono/Inspector/PrimitiveCollider3DEditor.cs deleted file mode 100644 index da13f9bded..0000000000 --- a/Editor/Mono/Inspector/PrimitiveCollider3DEditor.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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - internal abstract class PrimitiveCollider3DEditor : Collider3DEditorBase - { - protected abstract PrimitiveBoundsHandle boundsHandle { get; } - - protected abstract void CopyColliderPropertiesToHandle(); - - protected abstract void CopyHandlePropertiesToCollider(); - - protected override GUIContent editModeButton { get { return PrimitiveBoundsHandle.editModeButton; } } - - protected Vector3 InvertScaleVector(Vector3 scaleVector) - { - for (int axis = 0; axis < 3; ++axis) - scaleVector[axis] = scaleVector[axis] == 0f ? 0f : 1f / scaleVector[axis]; - return scaleVector; - } - - protected virtual void OnSceneGUI() - { - if (!editingCollider) - return; - - Collider collider = (Collider)target; - - if (Mathf.Approximately(collider.transform.lossyScale.sqrMagnitude, 0f)) - return; - - // collider matrix is center multiplied by transform's matrix with custom postmultiplied lossy scale matrix - using (new Handles.DrawingScope(Matrix4x4.TRS(collider.transform.position, collider.transform.rotation, Vector3.one))) - { - CopyColliderPropertiesToHandle(); - - boundsHandle.SetColor(collider.enabled ? Handles.s_ColliderHandleColor : Handles.s_ColliderHandleColorDisabled); - EditorGUI.BeginChangeCheck(); - boundsHandle.DrawHandle(); - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(collider, string.Format("Modify {0}", ObjectNames.NicifyVariableName(target.GetType().Name))); - CopyHandlePropertiesToCollider(); - } - } - } - - protected Vector3 TransformColliderCenterToHandleSpace(Transform colliderTransform, Vector3 colliderCenter) - { - return Handles.inverseMatrix * (colliderTransform.localToWorldMatrix * colliderCenter); - } - - protected Vector3 TransformHandleCenterToColliderSpace(Transform colliderTransform, Vector3 handleCenter) - { - return colliderTransform.localToWorldMatrix.inverse * (Handles.matrix * handleCenter); - } - } -} diff --git a/Editor/Mono/Inspector/PropertyDrawerCache.cs b/Editor/Mono/Inspector/PropertyDrawerCache.cs deleted file mode 100644 index 2a0a64eb61..0000000000 --- a/Editor/Mono/Inspector/PropertyDrawerCache.cs +++ /dev/null @@ -1,48 +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.Collections.Generic; - -namespace UnityEditor -{ - internal class PropertyHandlerCache - { - protected Dictionary m_PropertyHandlers = new Dictionary(); - - internal PropertyHandler GetHandler(SerializedProperty property) - { - PropertyHandler handler; - int key = GetPropertyHash(property); - if (m_PropertyHandlers.TryGetValue(key, out handler)) - return handler; - - return null; - } - - internal void SetHandler(SerializedProperty property, PropertyHandler handler) - { - int key = GetPropertyHash(property); - m_PropertyHandlers[key] = handler; - } - - private static int GetPropertyHash(SerializedProperty property) - { - if (property.serializedObject.targetObject == null) - return 0; - - // For efficiency, ignore indices inside brackets [] in order to make array elements share handlers. - int key = property.serializedObject.targetObject.GetInstanceID() ^ property.hashCodeForPropertyPathWithoutArrayIndex; - if (property.propertyType == SerializedPropertyType.ObjectReference) - { - key ^= property.objectReferenceInstanceIDValue; - } - return key; - } - - public void Clear() - { - m_PropertyHandlers.Clear(); - } - } -} diff --git a/Editor/Mono/Inspector/QualitySettingsEditor.cs b/Editor/Mono/Inspector/QualitySettingsEditor.cs index d079c972d7..495fd0a4a9 100644 --- a/Editor/Mono/Inspector/QualitySettingsEditor.cs +++ b/Editor/Mono/Inspector/QualitySettingsEditor.cs @@ -503,6 +503,7 @@ public override void OnInspectorGUI() var particleRaycastBudgetProperty = currentSettings.FindPropertyRelative("particleRaycastBudget"); var asyncUploadTimeSliceProperty = currentSettings.FindPropertyRelative("asyncUploadTimeSlice"); var asyncUploadBufferSizeProperty = currentSettings.FindPropertyRelative("asyncUploadBufferSize"); + var asyncUploadPersistentBufferProperty = currentSettings.FindPropertyRelative("asyncUploadPersistentBuffer"); var resolutionScalingFixedDPIFactorProperty = currentSettings.FindPropertyRelative("resolutionScalingFixedDPIFactor"); bool usingSRP = GraphicsSettings.renderPipelineAsset != null; @@ -586,6 +587,7 @@ public override void OnInspectorGUI() EditorGUILayout.PropertyField(particleRaycastBudgetProperty); EditorGUILayout.PropertyField(asyncUploadTimeSliceProperty); EditorGUILayout.PropertyField(asyncUploadBufferSizeProperty); + EditorGUILayout.PropertyField(asyncUploadPersistentBufferProperty); asyncUploadTimeSliceProperty.intValue = Mathf.Clamp(asyncUploadTimeSliceProperty.intValue, kMinAsyncUploadTimeSlice, kMaxAsyncUploadTimeSlice); asyncUploadBufferSizeProperty.intValue = Mathf.Clamp(asyncUploadBufferSizeProperty.intValue, kMinAsyncRingBufferSize, kMaxAsyncRingBufferSize); diff --git a/Editor/Mono/Inspector/RectHandles.cs b/Editor/Mono/Inspector/RectHandles.cs deleted file mode 100644 index f3f48c55d0..0000000000 --- a/Editor/Mono/Inspector/RectHandles.cs +++ /dev/null @@ -1,296 +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; - -namespace UnityEditor -{ - internal class RectHandles - { - static Styles s_Styles; - class Styles - { - public readonly GUIStyle dragdot = "U2D.dragDot"; - public readonly GUIStyle pivotdot = "U2D.pivotDot"; - public readonly GUIStyle dragdotactive = "U2D.dragDotActive"; - public readonly GUIStyle pivotdotactive = "U2D.pivotDotActive"; - } - - private static int s_LastCursorId; - - internal static bool RaycastGUIPointToWorldHit(Vector2 guiPoint, Plane plane, out Vector3 hit) - { - Ray ray = HandleUtility.GUIPointToWorldRay(guiPoint); - float dist = 0f; - bool isHit = plane.Raycast(ray, out dist); - hit = isHit ? ray.GetPoint(dist) : Vector3.zero; - return isHit; - } - - internal static void DetectCursorChange(int id) - { - if (HandleUtility.nearestControl == id) - { - // Don't optimize this to only use event if s_LastCursorId wasn't already id. - // Cursor can sometimes change for the same handle. - s_LastCursorId = id; - Event.current.Use(); - } - else if (s_LastCursorId == id) - { - s_LastCursorId = 0; - Event.current.Use(); - } - } - - internal static Vector3 SideSlider(int id, Vector3 position, Vector3 sideVector, Vector3 direction, float size, Handles.CapFunction capFunction, float snap) - { - return SideSlider(id, position, sideVector, direction, size, capFunction, snap, 0); - } - - internal static Vector3 SideSlider(int id, Vector3 position, Vector3 sideVector, Vector3 direction, float size, Handles.CapFunction capFunction, float snap, float bias) - { - Event evt = Event.current; - Vector3 handleDir = Vector3.Cross(sideVector, direction).normalized; - Vector3 pos = Handles.Slider2D(id, position, handleDir, direction, sideVector, 0, capFunction, Vector2.one * snap); - pos = position + Vector3.Project(pos - position, direction); - - switch (evt.type) - { - case EventType.Layout: - Vector3 sideDir = sideVector.normalized; - HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position + sideVector * 0.5f - sideDir * size * 2, position - sideVector * 0.5f + sideDir * size * 2) - bias); - break; - - case EventType.MouseMove: - DetectCursorChange(id); - break; - - case EventType.Repaint: - if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) - HandleDirectionalCursor(position, handleDir, direction); - break; - } - - return pos; - } - - internal static Vector3 CornerSlider(int id, Vector3 cornerPos, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, Handles.CapFunction drawFunc, Vector2 snap) - { - Event evt = Event.current; - Vector3 pos = Handles.Slider2D(id, cornerPos, handleDir, outwardsDir1, outwardsDir2, handleSize, drawFunc, snap); - - switch (evt.type) - { - case EventType.MouseMove: - DetectCursorChange(id); - break; - - case EventType.Repaint: - if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) - HandleDirectionalCursor(cornerPos, handleDir, outwardsDir1 + outwardsDir2); - break; - } - return pos; - } - - private static void HandleDirectionalCursor(Vector3 handlePosition, Vector3 handlePlaneNormal, Vector3 direction) - { - Vector2 mousePosition = Event.current.mousePosition; - - // Find cursor direction (supports perspective camera) - Plane guiPlane = new Plane(handlePlaneNormal, handlePosition); - Vector3 mousePosWorld; - if (RaycastGUIPointToWorldHit(mousePosition, guiPlane, out mousePosWorld)) - { - Vector2 cursorDir = WorldToScreenSpaceDir(mousePosWorld, direction); - // 200px x 200px rect around mousepos to switch cursor via fake cursorRect. - Rect mouseScreenRect = new Rect(mousePosition.x - 100f, mousePosition.y - 100f, 200f, 200f); - EditorGUIUtility.AddCursorRect(mouseScreenRect, GetScaleCursor(cursorDir)); - } - } - - public static float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis) - { - // Project A and B onto the plane orthogonal target axis - dirA = Vector3.ProjectOnPlane(dirA, axis); - dirB = Vector3.ProjectOnPlane(dirB, axis); - - // Find (positive) angle between A and B - float angle = Vector3.Angle(dirA, dirB); - - // Return angle multiplied with 1 or -1 - return angle * (Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) < 0 ? -1 : 1); - } - - public static float RotationSlider(int id, Vector3 cornerPos, float rotation, Vector3 pivot, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, Handles.CapFunction drawFunc, Vector2 snap) - { - Vector3 diagonal = (outwardsDir1 + outwardsDir2); - Vector2 screenCorner = HandleUtility.WorldToGUIPoint(cornerPos); - Vector2 screenOffset = HandleUtility.WorldToGUIPoint(cornerPos + diagonal) - screenCorner; - screenOffset = screenOffset.normalized * 15; - RaycastGUIPointToWorldHit(screenCorner + screenOffset, new Plane(handleDir, cornerPos), out cornerPos); - - Event evt = Event.current; - Vector3 pos = Handles.Slider2D(id, cornerPos, handleDir, outwardsDir1, outwardsDir2, handleSize, drawFunc, Vector2.zero); - - if (evt.type == EventType.MouseMove) - DetectCursorChange(id); - - if (evt.type == EventType.Repaint) - { - if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) - { - Rect mouseScreenRect = new Rect(evt.mousePosition.x - 100f, evt.mousePosition.y - 100f, 200f, 200f); - EditorGUIUtility.AddCursorRect(mouseScreenRect, MouseCursor.RotateArrow); - } - } - - return rotation - AngleAroundAxis(pos - pivot, cornerPos - pivot, handleDir); - } - - static Vector2 WorldToScreenSpaceDir(Vector3 worldPos, Vector3 worldDir) - { - Vector3 screenPos = HandleUtility.WorldToGUIPoint(worldPos); - Vector3 screenPosPlusDirection = HandleUtility.WorldToGUIPoint(worldPos + worldDir); - Vector2 screenSpaceDir = screenPosPlusDirection - screenPos; - screenSpaceDir.y *= -1; - return screenSpaceDir; - } - - private static MouseCursor GetScaleCursor(Vector2 direction) - { - float angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg; - - if (angle < 0f) - angle = 360f + angle; - - if (angle < 0f + 27.5f) - return MouseCursor.ResizeVertical; - if (angle < 45f + 27.5f) - return MouseCursor.ResizeUpRight; - if (angle < 90f + 27.5f) - return MouseCursor.ResizeHorizontal; - if (angle < 135f + 27.5f) - return MouseCursor.ResizeUpLeft; - if (angle < 180f + 27.5f) - return MouseCursor.ResizeVertical; - if (angle < 225f + 27.5f) - return MouseCursor.ResizeUpRight; - if (angle < 270f + 27.5f) - return MouseCursor.ResizeHorizontal; - if (angle < 315f + 27.5f) - return MouseCursor.ResizeUpLeft; - else - return MouseCursor.ResizeVertical; - } - - public static void RectScalingHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) - { - if (s_Styles == null) - s_Styles = new Styles(); - - switch (eventType) - { - case EventType.Layout: - HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position, size * .5f)); - break; - case EventType.Repaint: - DrawImageBasedCap(controlID, position, rotation, size, s_Styles.dragdot, s_Styles.dragdotactive); - break; - } - } - - public static void PivotHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) - { - if (s_Styles == null) - s_Styles = new Styles(); - - switch (eventType) - { - case EventType.Layout: - HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position, size * .5f)); - break; - case EventType.Repaint: - DrawImageBasedCap(controlID, position, rotation, size, s_Styles.pivotdot, s_Styles.pivotdotactive); - break; - } - } - - static void DrawImageBasedCap(int controlID, Vector3 position, Quaternion rotation, float size, GUIStyle normal, GUIStyle active) - { - // Don't draw positions behind the camera - if (Camera.current && Vector3.Dot(position - Camera.current.transform.position, Camera.current.transform.forward) < 0) - return; - - Vector3 screenPos = HandleUtility.WorldToGUIPoint(position); - - Handles.BeginGUI(); - float w = normal.fixedWidth; - float h = normal.fixedHeight; - Rect r = new Rect(screenPos.x - w / 2f, screenPos.y - h / 2f, w, h); - if (GUIUtility.hotControl == controlID) - active.Draw(r, GUIContent.none, controlID); - else - normal.Draw(r, GUIContent.none, controlID); - - Handles.EndGUI(); - } - - public static void RenderRectWithShadow(bool active, params Vector3[] corners) - { - Vector3[] verts = new Vector3[] { corners[0], corners[1], corners[2], corners[3], corners[0] }; - - Color oldColor = Handles.color; - Handles.color = new Color(1f, 1f, 1f, active ? 1f : 0.5f); - DrawPolyLineWithShadow(new Color(0f, 0f, 0f, active ? 1f : 0.5f), new Vector2(1f, -1f), verts); - Handles.color = oldColor; - } - - static Vector3[] s_TempVectors = new Vector3[0]; - public static void DrawPolyLineWithShadow(Color shadowColor, Vector2 screenOffset, params Vector3[] points) - { - Camera cam = Camera.current; - if (!cam || Event.current.type != EventType.Repaint) - return; - - if (s_TempVectors.Length != points.Length) - s_TempVectors = new Vector3[points.Length]; - - for (int i = 0; i < points.Length; i++) - s_TempVectors[i] = cam.ScreenToWorldPoint(cam.WorldToScreenPoint(points[i]) + (Vector3)screenOffset); - - Color oldColor = Handles.color; - - // shadow - shadowColor.a = shadowColor.a * oldColor.a; - Handles.color = shadowColor; - Handles.DrawPolyLine(s_TempVectors); - - // line itself - Handles.color = oldColor; - Handles.DrawPolyLine(points); - } - - public static void DrawDottedLineWithShadow(Color shadowColor, Vector2 screenOffset, Vector3 p1, Vector3 p2, float screenSpaceSize) - { - Camera cam = Camera.current; - if (!cam || Event.current.type != EventType.Repaint) - return; - - Color oldColor = Handles.color; - - // shadow - shadowColor.a = shadowColor.a * oldColor.a; - Handles.color = shadowColor; - Handles.DrawDottedLine( - cam.ScreenToWorldPoint(cam.WorldToScreenPoint(p1) + (Vector3)screenOffset), - cam.ScreenToWorldPoint(cam.WorldToScreenPoint(p2) + (Vector3)screenOffset), screenSpaceSize); - - // line itself - Handles.color = oldColor; - Handles.DrawDottedLine(p1, p2, screenSpaceSize); - } - } -} diff --git a/Editor/Mono/Inspector/RectTransformEditor.cs b/Editor/Mono/Inspector/RectTransformEditor.cs index 3ee6543a67..a98c23be5b 100644 --- a/Editor/Mono/Inspector/RectTransformEditor.cs +++ b/Editor/Mono/Inspector/RectTransformEditor.cs @@ -298,7 +298,7 @@ void LayoutDropdownButton(bool anyWithoutParent) { GUIUtility.keyboardControl = 0; m_DropdownWindow = new LayoutDropdownWindow(serializedObject); - PopupWindow.Show(dropdownPosition, m_DropdownWindow, null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(dropdownPosition, m_DropdownWindow); } GUI.color = oldColor; } diff --git a/Editor/Mono/Inspector/RelativeJoint2DEditor.cs b/Editor/Mono/Inspector/RelativeJoint2DEditor.cs deleted file mode 100644 index e2a57cb780..0000000000 --- a/Editor/Mono/Inspector/RelativeJoint2DEditor.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 System; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(RelativeJoint2D))] - [CanEditMultipleObjects] - internal class RelativeJoint2DEditor : Joint2DEditor - { - public void OnSceneGUI() - { - var relativeJoint2D = (RelativeJoint2D)target; - - // Ignore disabled joint. - if (!relativeJoint2D.enabled) - return; - - // Fetch the anchors. - var anchor = (Vector3)relativeJoint2D.target; - var connectedAnchor = relativeJoint2D.connectedBody ? relativeJoint2D.connectedBody.transform.position : Vector3.zero; - - // Draw a line between the bodies. - Handles.color = Color.green; - DrawAALine(anchor, connectedAnchor); - - // Draw the source point. - var sourceScale = HandleUtility.GetHandleSize(connectedAnchor) * 0.16f; - var horzSource = Vector3.left * sourceScale; - var vertSource = Vector3.up * sourceScale; - DrawAALine(connectedAnchor - horzSource, connectedAnchor + horzSource); - DrawAALine(connectedAnchor - vertSource, connectedAnchor + vertSource); - - // Draw the target point. - var targetScale = HandleUtility.GetHandleSize(anchor) * 0.16f; - var horzTarget = Vector3.left * targetScale; - var vertTarget = Vector3.up * targetScale; - DrawAALine(anchor - horzTarget, anchor + horzTarget); - DrawAALine(anchor - vertTarget, anchor + vertTarget); - } - } -} diff --git a/Editor/Mono/Inspector/RenderSettingsInspector.cs b/Editor/Mono/Inspector/RenderSettingsInspector.cs deleted file mode 100644 index 3d0cc0efb1..0000000000 --- a/Editor/Mono/Inspector/RenderSettingsInspector.cs +++ /dev/null @@ -1,47 +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 UnityEditor.AnimatedValues; -using UnityEngine; -using UnityEngine.Rendering; - -namespace UnityEditor -{ - [CustomEditor(typeof(RenderSettings))] - internal class RenderSettingsInspector : Editor - { - Editor m_LightingEditor; - Editor lightingEditor - { - get { return m_LightingEditor ?? (m_LightingEditor = Editor.CreateEditor(target, typeof(LightingEditor))); } - } - - - Editor m_FogEditor; - Editor fogEditor - { - get { return m_FogEditor ?? (m_FogEditor = Editor.CreateEditor(target, typeof(FogEditor))); } - } - - Editor m_OtherRenderingEditor; - Editor otherRenderingEditor - { - get { return m_OtherRenderingEditor ?? (m_OtherRenderingEditor = Editor.CreateEditor(target, typeof(OtherRenderingEditor))); } - } - - public virtual void OnEnable() - { - m_LightingEditor = null; - m_FogEditor = null; - m_OtherRenderingEditor = null; - } - - public override void OnInspectorGUI() - { - lightingEditor.OnInspectorGUI(); - fogEditor.OnInspectorGUI(); - otherRenderingEditor.OnInspectorGUI(); - } - } -} diff --git a/Editor/Mono/Inspector/RotationConstraintEditor.cs b/Editor/Mono/Inspector/RotationConstraintEditor.cs deleted file mode 100644 index 647105e325..0000000000 --- a/Editor/Mono/Inspector/RotationConstraintEditor.cs +++ /dev/null @@ -1,81 +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.Animations; - -namespace UnityEditor -{ - [CustomEditor(typeof(RotationConstraint))] - [CanEditMultipleObjects] - internal class RotationConstraintEditor : ConstraintEditorBase - { - private SerializedProperty m_RotationAtRest; - private SerializedProperty m_RotationOffset; - private SerializedProperty m_Weight; - private SerializedProperty m_IsContraintActive; - private SerializedProperty m_IsLocked; - private SerializedProperty m_Sources; - - internal override SerializedProperty atRest { get { return m_RotationAtRest; } } - internal override SerializedProperty offset { get { return m_RotationOffset; } } - internal override SerializedProperty weight { get { return m_Weight; } } - internal override SerializedProperty isContraintActive { get { return m_IsContraintActive; } } - internal override SerializedProperty isLocked { get { return m_IsLocked; } } - internal override SerializedProperty sources { get { return m_Sources; } } - - private class Styles : ConstraintStyleBase - { - GUIContent m_RotationAtRest = EditorGUIUtility.TrTextContent("Rotation At Rest"); - GUIContent m_RotationOffset = EditorGUIUtility.TrTextContent("Rotation Offset"); - - GUIContent m_RotationAxes = EditorGUIUtility.TrTextContent("Freeze Rotation Axes"); - - public override GUIContent AtRest { get { return m_RotationAtRest; } } - public override GUIContent Offset { get { return m_RotationOffset; } } - public GUIContent FreezeAxes { get { return m_RotationAxes; } } - } - - private static Styles s_Style = null; - - public void OnEnable() - { - if (s_Style == null) - s_Style = new Styles(); - - m_RotationAtRest = serializedObject.FindProperty("m_RotationAtRest"); - m_RotationOffset = serializedObject.FindProperty("m_RotationOffset"); - m_Weight = serializedObject.FindProperty("m_Weight"); - m_IsContraintActive = serializedObject.FindProperty("m_IsContraintActive"); - m_IsLocked = serializedObject.FindProperty("m_IsLocked"); - m_Sources = serializedObject.FindProperty("m_Sources"); - - OnEnable(s_Style); - } - - internal override void OnValueAtRestChanged() - { - foreach (var t in targets) - (t as RotationConstraint).transform.SetLocalEulerAngles(atRest.vector3Value, RotationOrder.OrderZXY); - } - - internal override void ShowFreezeAxesControl() - { - Rect drawRect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector3, s_Style.FreezeAxes), EditorStyles.toggle); - EditorGUI.MultiPropertyField(drawRect, s_Style.Axes, serializedObject.FindProperty("m_AffectRotationX"), s_Style.FreezeAxes); - } - - public override void OnInspectorGUI() - { - if (s_Style == null) - s_Style = new Styles(); - - serializedObject.Update(); - - ShowConstraintEditor(s_Style); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/ScaleConstraintEditor.cs b/Editor/Mono/Inspector/ScaleConstraintEditor.cs deleted file mode 100644 index c286b8c2fe..0000000000 --- a/Editor/Mono/Inspector/ScaleConstraintEditor.cs +++ /dev/null @@ -1,81 +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.Animations; - -namespace UnityEditor -{ - [CustomEditor(typeof(ScaleConstraint))] - [CanEditMultipleObjects] - internal class ScaleConstraintEditor : ConstraintEditorBase - { - private SerializedProperty m_ScaleAtRest; - private SerializedProperty m_ScaleOffset; - private SerializedProperty m_Weight; - private SerializedProperty m_IsContraintActive; - private SerializedProperty m_IsLocked; - private SerializedProperty m_Sources; - - internal override SerializedProperty atRest { get { return m_ScaleAtRest; } } - internal override SerializedProperty offset { get { return m_ScaleOffset; } } - internal override SerializedProperty weight { get { return m_Weight; } } - internal override SerializedProperty isContraintActive { get { return m_IsContraintActive; } } - internal override SerializedProperty isLocked { get { return m_IsLocked; } } - internal override SerializedProperty sources { get { return m_Sources; } } - - private class Styles : ConstraintStyleBase - { - GUIContent m_ScaleAtRest = EditorGUIUtility.TrTextContent("Scale At Rest"); - GUIContent m_ScaleOffset = EditorGUIUtility.TrTextContent("Scale Offset"); - - GUIContent m_ScalingAxes = EditorGUIUtility.TrTextContent("Freeze Scaling Axes"); - - public override GUIContent AtRest { get { return m_ScaleAtRest; } } - public override GUIContent Offset { get { return m_ScaleOffset; } } - public GUIContent FreezeAxes { get { return m_ScalingAxes; } } - } - - private static Styles s_Style; - - public void OnEnable() - { - if (s_Style == null) - s_Style = new Styles(); - - m_ScaleAtRest = serializedObject.FindProperty("m_ScaleAtRest"); - m_ScaleOffset = serializedObject.FindProperty("m_ScaleOffset"); - m_Weight = serializedObject.FindProperty("m_Weight"); - m_IsContraintActive = serializedObject.FindProperty("m_IsContraintActive"); - m_IsLocked = serializedObject.FindProperty("m_IsLocked"); - m_Sources = serializedObject.FindProperty("m_Sources"); - - OnEnable(s_Style); - } - - internal override void OnValueAtRestChanged() - { - foreach (var t in targets) - (t as ScaleConstraint).transform.localScale = atRest.vector3Value; - } - - internal override void ShowFreezeAxesControl() - { - Rect drawRect = EditorGUILayout.GetControlRect(true, EditorGUI.GetPropertyHeight(SerializedPropertyType.Vector3, s_Style.FreezeAxes), EditorStyles.toggle); - EditorGUI.MultiPropertyField(drawRect, s_Style.Axes, serializedObject.FindProperty("m_AffectScalingX"), s_Style.FreezeAxes); - } - - public override void OnInspectorGUI() - { - if (s_Style == null) - s_Style = new Styles(); - - serializedObject.Update(); - - ShowConstraintEditor(s_Style); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/ShaderGUI.cs b/Editor/Mono/Inspector/ShaderGUI.cs deleted file mode 100644 index a48ba6cbb5..0000000000 --- a/Editor/Mono/Inspector/ShaderGUI.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; - -namespace UnityEditor -{ - public abstract class ShaderGUI - { - virtual public void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) - { - materialEditor.PropertiesDefaultGUI(properties); - } - - virtual public void OnMaterialPreviewGUI(MaterialEditor materialEditor, Rect r, GUIStyle background) - { - materialEditor.DefaultPreviewGUI(r, background); - } - - virtual public void OnMaterialInteractivePreviewGUI(MaterialEditor materialEditor, Rect r, GUIStyle background) - { - materialEditor.DefaultPreviewGUI(r, background); - } - - virtual public void OnMaterialPreviewSettingsGUI(MaterialEditor materialEditor) - { - materialEditor.DefaultPreviewSettingsGUI(); - } - - virtual public void OnClosed(Material material) - { - } - - virtual public void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) - { - material.shader = newShader; - } - - // Utility methods - protected static MaterialProperty FindProperty(string propertyName, MaterialProperty[] properties) - { - return FindProperty(propertyName, properties, true); - } - - protected static MaterialProperty FindProperty(string propertyName, MaterialProperty[] properties, bool propertyIsMandatory) - { - for (var i = 0; i < properties.Length; i++) - if (properties[i] != null && properties[i].name == propertyName) - return properties[i]; - - // We assume all required properties can be found, otherwise something is broken - if (propertyIsMandatory) - throw new ArgumentException("Could not find MaterialProperty: '" + propertyName + "', Num properties: " + properties.Length); - return null; - } - } - - internal static class ShaderGUIUtility - { - private static Type ExtractCustomEditorType(string customEditorName) - { - if (string.IsNullOrEmpty(customEditorName)) return null; - - // To allow users to implement their own ShaderGUI for the Standard shader we iterate in reverse order - // because the UnityEditor assembly is assumed first in the assembly list. - // Users can now place a copy of the StandardShaderGUI script in the project and start modifying that copy to make their own version. - - string unityEditorFullName = "UnityEditor." + customEditorName; // for convenience: adding UnityEditor namespace is not needed in the shader - - var editorAssemblies = EditorAssemblies.loadedAssemblies; - for (int i = editorAssemblies.Length - 1; i >= 0; i--) - { - foreach (var type in AssemblyHelper.GetTypesFromAssembly(editorAssemblies[i])) - { - if (type.FullName.Equals(customEditorName, StringComparison.Ordinal) || type.FullName.Equals(unityEditorFullName, StringComparison.Ordinal)) - return typeof(ShaderGUI).IsAssignableFrom(type) ? type : null; - } - } - return null; - } - - internal static ShaderGUI CreateShaderGUI(string customEditorName) - { - Type customEditorType = ExtractCustomEditorType(customEditorName); - return customEditorType != null ? (Activator.CreateInstance(customEditorType) as ShaderGUI) : null; - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/Inspector/ShaderIncludePathAttribute.cs b/Editor/Mono/Inspector/ShaderIncludePathAttribute.cs deleted file mode 100644 index 965696df1c..0000000000 --- a/Editor/Mono/Inspector/ShaderIncludePathAttribute.cs +++ /dev/null @@ -1,15 +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 -{ - [AttributeUsage(AttributeTargets.Method)] - public class ShaderIncludePathAttribute : Attribute - { - [RequiredSignature] - static extern string[] GetIncludePaths(); - } -} diff --git a/Editor/Mono/Inspector/SkyboxPanoramicShaderGUI.cs b/Editor/Mono/Inspector/SkyboxPanoramicShaderGUI.cs deleted file mode 100644 index 641d047221..0000000000 --- a/Editor/Mono/Inspector/SkyboxPanoramicShaderGUI.cs +++ /dev/null @@ -1,78 +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 UnityEditor; -using UnityEditor.AnimatedValues; -using UnityEditorInternal; -using UnityEditor.Build; - -namespace UnityEditor -{ - internal class SkyboxPanoramicShaderGUI : ShaderGUI - { - readonly AnimBool m_ShowLatLongLayout = new AnimBool(); - readonly AnimBool m_ShowMirrorOnBack = new AnimBool(); - readonly AnimBool m_Show3DControl = new AnimBool(); - - bool m_Initialized = false; - - public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) - { - if (!m_Initialized) - { - m_ShowLatLongLayout.valueChanged.AddListener(materialEditor.Repaint); - m_ShowMirrorOnBack.valueChanged.AddListener(materialEditor.Repaint); - m_Show3DControl.valueChanged.AddListener(materialEditor.Repaint); - m_Initialized = true; - } - - // Allow the default implementation to set widths for consistency for common properties. - float lw = EditorGUIUtility.labelWidth; - materialEditor.SetDefaultGUIWidths(); - ShowProp(materialEditor, FindProperty("_Tint", props)); - ShowProp(materialEditor, FindProperty("_Exposure", props)); - ShowProp(materialEditor, FindProperty("_Rotation", props)); - ShowProp(materialEditor, FindProperty("_MainTex", props)); - EditorGUIUtility.labelWidth = lw; - - m_ShowLatLongLayout.target = ShowProp(materialEditor, FindProperty("_Mapping", props)) == 1; - if (EditorGUILayout.BeginFadeGroup(m_ShowLatLongLayout.faded)) - { - m_ShowMirrorOnBack.target = ShowProp(materialEditor, FindProperty("_ImageType", props)) == 1; - if (EditorGUILayout.BeginFadeGroup(m_ShowMirrorOnBack.faded)) - { - EditorGUI.indentLevel++; - ShowProp(materialEditor, FindProperty("_MirrorOnBack", props)); - EditorGUI.indentLevel--; - } - EditorGUILayout.EndFadeGroup(); - - // Show 3D settings if VR support is enabled on ANY platform. - m_Show3DControl.value = false; - foreach (BuildPlatform cur in BuildPlatforms.instance.buildPlatforms) - { - if (UnityEditorInternal.VR.VREditor.GetVREnabledOnTargetGroup(cur.targetGroup)) - { - m_Show3DControl.value = true; - break; - } - } - if (EditorGUILayout.BeginFadeGroup(m_Show3DControl.faded)) - ShowProp(materialEditor, FindProperty("_Layout", props)); - EditorGUILayout.EndFadeGroup(); - } - EditorGUILayout.EndFadeGroup(); - - // Let the default implementation add the extra shader properties at the bottom. - materialEditor.PropertiesDefaultGUI(new MaterialProperty[0]); - } - - private float ShowProp(MaterialEditor materialEditor, MaterialProperty prop) - { - materialEditor.ShaderProperty(prop, prop.displayName); - return prop.floatValue; - } - } -} diff --git a/Editor/Mono/Inspector/SkyboxProceduralShaderGUI.cs b/Editor/Mono/Inspector/SkyboxProceduralShaderGUI.cs deleted file mode 100644 index ce67c8da95..0000000000 --- a/Editor/Mono/Inspector/SkyboxProceduralShaderGUI.cs +++ /dev/null @@ -1,42 +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 -{ - internal class SkyboxProceduralShaderGUI : ShaderGUI - { - private enum SunDiskMode - { - None, - Simple, - HighQuality - } - - public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) - { - materialEditor.SetDefaultGUIWidths(); - - MaterialProperty sunDiskModeProp = FindProperty("_SunDisk", props); - SunDiskMode sunDiskMode = (SunDiskMode)sunDiskModeProp.floatValue; - - for (var i = 0; i < props.Length; i++) - { - if ((props[i].flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0) - continue; - - //_SunSizeConvergence is only used with the HighQuality sun disk. - if ((props[i].name == "_SunSizeConvergence") && (sunDiskMode != SunDiskMode.HighQuality)) - continue; - - float h = materialEditor.GetPropertyHeight(props[i], props[i].displayName); - Rect r = EditorGUILayout.GetControlRect(true, h, EditorStyles.layerMaskField); - - materialEditor.ShaderProperty(r, props[i], props[i].displayName); - } - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/Inspector/SliderJoint2DEditor.cs b/Editor/Mono/Inspector/SliderJoint2DEditor.cs deleted file mode 100644 index ffdf26624b..0000000000 --- a/Editor/Mono/Inspector/SliderJoint2DEditor.cs +++ /dev/null @@ -1,55 +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 -{ - [CustomEditor(typeof(SliderJoint2D))] - [CanEditMultipleObjects] - internal class SliderJoint2DEditor : AnchoredJoint2DEditor - { - new public void OnSceneGUI() - { - var sliderJoint2D = (SliderJoint2D)target; - - // Ignore disabled joint. - if (!sliderJoint2D.enabled) - return; - - var anchor = TransformPoint(sliderJoint2D.transform, sliderJoint2D.anchor); - - // Draw lines for slider angle and limits - Vector3 upper = anchor; - Vector3 lower = anchor; - Vector3 direction = RotateVector2(Vector3.right, -sliderJoint2D.angle - sliderJoint2D.transform.eulerAngles.z); - - Handles.color = Color.green; - - if (sliderJoint2D.useLimits) - { - upper = anchor + direction * sliderJoint2D.limits.max; - lower = anchor + direction * sliderJoint2D.limits.min; - - Vector3 normal = Vector3.Cross(direction, Vector3.forward); - float upperSize = HandleUtility.GetHandleSize(upper) * 0.16f; - float lowerSize = HandleUtility.GetHandleSize(lower) * 0.16f; - - DrawAALine(upper + normal * upperSize, upper - normal * upperSize); - DrawAALine(lower + normal * lowerSize, lower - normal * lowerSize); - } - else - { - direction *= HandleUtility.GetHandleSize(anchor) * 0.3f; - upper += direction; - lower -= direction; - } - - DrawAALine(upper, lower); - - base.OnSceneGUI(); - } - } -} diff --git a/Editor/Mono/Inspector/SortingGroupEditor.cs b/Editor/Mono/Inspector/SortingGroupEditor.cs deleted file mode 100644 index abb39e0716..0000000000 --- a/Editor/Mono/Inspector/SortingGroupEditor.cs +++ /dev/null @@ -1,31 +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 UnityEditorInternal; -using UnityEngine; -using UnityEngine.Rendering; - -namespace UnityEditor -{ - [CustomEditor(typeof(UnityEngine.Rendering.SortingGroup))] - [CanEditMultipleObjects] - internal class SortingGroupEditor : Editor - { - private SerializedProperty m_SortingOrder; - private SerializedProperty m_SortingLayerID; - - public virtual void OnEnable() - { - m_SortingOrder = serializedObject.FindProperty("m_SortingOrder"); - m_SortingLayerID = serializedObject.FindProperty("m_SortingLayerID"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - SortingLayerEditorUtility.RenderSortingLayerFields(m_SortingOrder, m_SortingLayerID); - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/SortingLayerEditorUtility.cs b/Editor/Mono/Inspector/SortingLayerEditorUtility.cs deleted file mode 100644 index 079b0dd800..0000000000 --- a/Editor/Mono/Inspector/SortingLayerEditorUtility.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 UnityEditorInternal; -using UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal class SortingLayerEditorUtility - { - private static class Styles - { - public static GUIContent m_SortingLayerStyle = EditorGUIUtility.TrTextContent("Sorting Layer", "Name of the Renderer's sorting layer"); - public static GUIContent m_SortingOrderStyle = EditorGUIUtility.TrTextContent("Order in Layer", "Renderer's order within a sorting layer"); - } - - public static void RenderSortingLayerFields(SerializedProperty sortingOrder, SerializedProperty sortingLayer) - { - EditorGUILayout.SortingLayerField(Styles.m_SortingLayerStyle, sortingLayer, EditorStyles.popup, EditorStyles.label); - EditorGUILayout.PropertyField(sortingOrder, Styles.m_SortingOrderStyle); - } - - public static void RenderSortingLayerFields(Rect r, SerializedProperty sortingOrder, SerializedProperty sortingLayer) - { - EditorGUI.SortingLayerField(r, Styles.m_SortingLayerStyle, sortingLayer, EditorStyles.popup, EditorStyles.label); - r.y += EditorGUIUtility.singleLineHeight; - EditorGUI.PropertyField(r, sortingOrder, Styles.m_SortingOrderStyle); - } - } -} diff --git a/Editor/Mono/Inspector/SpeedTreeMaterialInspector.cs b/Editor/Mono/Inspector/SpeedTreeMaterialInspector.cs deleted file mode 100644 index 4a75a69585..0000000000 --- a/Editor/Mono/Inspector/SpeedTreeMaterialInspector.cs +++ /dev/null @@ -1,187 +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 System; -using System.Collections.Generic; -using System.Linq; - -namespace UnityEditor -{ - [CanEditMultipleObjects] - internal class SpeedTreeMaterialInspector : MaterialEditor - { - private enum SpeedTreeGeometryType - { - Branch = 0, - BranchDetail, - Frond, - Leaf, - Mesh // mapped with GEOM_TYPE_MESH in SpeedTreeImporter - } - - private string[] speedTreeGeometryTypeString = - { - "GEOM_TYPE_BRANCH", - "GEOM_TYPE_BRANCH_DETAIL", - "GEOM_TYPE_FROND", - "GEOM_TYPE_LEAF", - "GEOM_TYPE_MESH" - }; - - private bool ShouldEnableAlphaTest(SpeedTreeGeometryType geomType) - { - return geomType == SpeedTreeGeometryType.Frond - || geomType == SpeedTreeGeometryType.Leaf; - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - var theShader = serializedObject.FindProperty("m_Shader"); - - // if we are not visible... return - if (!isVisible || theShader.hasMultipleDifferentValues || theShader.objectReferenceValue == null) - return; - - List props = new List(GetMaterialProperties(targets)); - - SetDefaultGUIWidths(); - - // Geometry type choice - //--------------------------------------------------------------- - var geomTypes = new SpeedTreeGeometryType[targets.Length]; - for (int i = 0; i < targets.Length; ++i) - { - geomTypes[i] = SpeedTreeGeometryType.Branch; - for (int j = 0; j < speedTreeGeometryTypeString.Length; ++j) - { - if (((Material)targets[i]).shaderKeywords.Contains(speedTreeGeometryTypeString[j])) - { - geomTypes[i] = (SpeedTreeGeometryType)j; - break; - } - } - } - EditorGUI.showMixedValue = geomTypes.Distinct().Count() > 1; - EditorGUI.BeginChangeCheck(); - var setGeomType = (SpeedTreeGeometryType)EditorGUILayout.EnumPopup("Geometry Type", geomTypes[0]); - if (EditorGUI.EndChangeCheck()) - { - bool shouldEnableAlphaTest = ShouldEnableAlphaTest(setGeomType); - UnityEngine.Rendering.CullMode cullMode = shouldEnableAlphaTest ? UnityEngine.Rendering.CullMode.Off : UnityEngine.Rendering.CullMode.Back; - - foreach (var m in targets.Cast()) - { - if (shouldEnableAlphaTest) - m.SetOverrideTag("RenderType", "treeTransparentCutout"); - for (int i = 0; i < speedTreeGeometryTypeString.Length; ++i) - m.DisableKeyword(speedTreeGeometryTypeString[i]); - m.EnableKeyword(speedTreeGeometryTypeString[(int)setGeomType]); - m.renderQueue = shouldEnableAlphaTest ? (int)UnityEngine.Rendering.RenderQueue.AlphaTest : (int)UnityEngine.Rendering.RenderQueue.Geometry; - m.SetInt("_Cull", (int)cullMode); - } - } - EditorGUI.showMixedValue = false; - - //--------------------------------------------------------------- - var mainTex = props.Find(prop => prop.name == "_MainTex"); - if (mainTex != null) - { - props.Remove(mainTex); - ShaderProperty(mainTex, mainTex.displayName); - } - - //--------------------------------------------------------------- - var bumpMap = props.Find(prop => prop.name == "_BumpMap"); - if (bumpMap != null) - { - props.Remove(bumpMap); - - var enableBump = targets.Select(t => ((Material)t).shaderKeywords.Contains("EFFECT_BUMP")); - bool? enable = ToggleShaderProperty(bumpMap, enableBump.First(), enableBump.Distinct().Count() > 1); - if (enable != null) - { - foreach (var m in targets.Cast()) - { - if (enable.Value) - m.EnableKeyword("EFFECT_BUMP"); - else - m.DisableKeyword("EFFECT_BUMP"); - } - } - } - - //--------------------------------------------------------------- - var detailTex = props.Find(prop => prop.name == "_DetailTex"); - if (detailTex != null) - { - props.Remove(detailTex); - if (geomTypes.Contains(SpeedTreeGeometryType.BranchDetail)) - ShaderProperty(detailTex, detailTex.displayName); - } - - //--------------------------------------------------------------- - var enableHueVariation = targets.Select(t => ((Material)t).shaderKeywords.Contains("EFFECT_HUE_VARIATION")); - var hueVariation = props.Find(prop => prop.name == "_HueVariation"); - if (enableHueVariation != null && hueVariation != null) - { - props.Remove(hueVariation); - bool? enable = ToggleShaderProperty(hueVariation, enableHueVariation.First(), enableHueVariation.Distinct().Count() > 1); - if (enable != null) - { - foreach (var m in targets.Cast()) - { - if (enable.Value) - m.EnableKeyword("EFFECT_HUE_VARIATION"); - else - m.DisableKeyword("EFFECT_HUE_VARIATION"); - } - } - } - - //--------------------------------------------------------------- - var alphaCutoff = props.Find(prop => prop.name == "_Cutoff"); - if (alphaCutoff != null) - { - props.Remove(alphaCutoff); - if (geomTypes.Any(t => ShouldEnableAlphaTest(t))) - ShaderProperty(alphaCutoff, alphaCutoff.displayName); - } - - //--------------------------------------------------------------- - foreach (var prop in props) - { - if ((prop.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0) - continue; - ShaderProperty(prop, prop.displayName); - } - - EditorGUILayout.Space(); - EditorGUILayout.Space(); - - RenderQueueField(); - EnableInstancingField(); - DoubleSidedGIField(); - } - - private bool? ToggleShaderProperty(MaterialProperty prop, bool enable, bool hasMixedEnable) - { - EditorGUI.BeginChangeCheck(); - EditorGUI.showMixedValue = hasMixedEnable; - enable = EditorGUI.ToggleLeft(EditorGUILayout.GetControlRect(false, GUILayout.ExpandWidth(false)), prop.displayName, enable); - EditorGUI.showMixedValue = false; - bool? retValue = EditorGUI.EndChangeCheck() ? (bool?)enable : null; - - GUILayout.Space(-EditorGUIUtility.singleLineHeight); - using (new EditorGUI.DisabledScope(!enable && !hasMixedEnable)) - { - EditorGUI.showMixedValue = prop.hasMixedValue; - ShaderProperty(prop, " "); - EditorGUI.showMixedValue = false; - } - return retValue; - } - } -} diff --git a/Editor/Mono/Inspector/SphereColliderEditor.cs b/Editor/Mono/Inspector/SphereColliderEditor.cs deleted file mode 100644 index c178da3b70..0000000000 --- a/Editor/Mono/Inspector/SphereColliderEditor.cs +++ /dev/null @@ -1,68 +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 UnityEditor.IMGUI.Controls; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(SphereCollider))] - [CanEditMultipleObjects] - internal class SphereColliderEditor : PrimitiveCollider3DEditor - { - SerializedProperty m_Center; - SerializedProperty m_Radius; - private readonly SphereBoundsHandle m_BoundsHandle = new SphereBoundsHandle(); - - public override void OnEnable() - { - base.OnEnable(); - - m_Center = serializedObject.FindProperty("m_Center"); - m_Radius = serializedObject.FindProperty("m_Radius"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - InspectorEditButtonGUI(); - EditorGUILayout.PropertyField(m_IsTrigger); - EditorGUILayout.PropertyField(m_Material); - EditorGUILayout.PropertyField(m_Center); - EditorGUILayout.PropertyField(m_Radius); - - serializedObject.ApplyModifiedProperties(); - } - - protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } - - protected override void CopyColliderPropertiesToHandle() - { - SphereCollider collider = (SphereCollider)target; - m_BoundsHandle.center = TransformColliderCenterToHandleSpace(collider.transform, collider.center); - m_BoundsHandle.radius = collider.radius * GetRadiusScaleFactor(); - } - - protected override void CopyHandlePropertiesToCollider() - { - SphereCollider collider = (SphereCollider)target; - collider.center = TransformHandleCenterToColliderSpace(collider.transform, m_BoundsHandle.center); - float scaleFactor = GetRadiusScaleFactor(); - collider.radius = - Mathf.Approximately(scaleFactor, 0f) ? 0f : m_BoundsHandle.radius / GetRadiusScaleFactor(); - } - - private float GetRadiusScaleFactor() - { - float result = 0f; - Vector3 lossyScale = ((SphereCollider)target).transform.lossyScale; - for (int axis = 0; axis < 3; ++axis) - { - result = Mathf.Max(result, Mathf.Abs(lossyScale[axis])); - } - return result; - } - } -} diff --git a/Editor/Mono/Inspector/SpringJoint2DEditor.cs b/Editor/Mono/Inspector/SpringJoint2DEditor.cs deleted file mode 100644 index 07ddc6ed01..0000000000 --- a/Editor/Mono/Inspector/SpringJoint2DEditor.cs +++ /dev/null @@ -1,35 +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 -{ - [CustomEditor(typeof(SpringJoint2D))] - [CanEditMultipleObjects] - internal class SpringJoint2DEditor : AnchoredJoint2DEditor - { - new public void OnSceneGUI() - { - var springJoint2D = (SpringJoint2D)target; - - // Ignore disabled joint. - if (!springJoint2D.enabled) - return; - - // Start and end points for distance gizmo - Vector3 anchor = TransformPoint(springJoint2D.transform, springJoint2D.anchor); - Vector3 connectedAnchor = springJoint2D.connectedAnchor; - - // If connectedBody present, convert the position to match that - if (springJoint2D.connectedBody) - connectedAnchor = TransformPoint(springJoint2D.connectedBody.transform, connectedAnchor); - - DrawDistanceGizmo(anchor, connectedAnchor, springJoint2D.distance); - - base.OnSceneGUI(); - } - } -} diff --git a/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs b/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs index 656b97c002..760f41840b 100644 --- a/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs +++ b/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs @@ -54,20 +54,18 @@ private static class Styles public static GUIContent colorMode = EditorGUIUtility.TrTextContent("Color Mode", "Determines the blending mode between the particle color and the texture albedo."); public static GUIContent[] colorNames = Array.ConvertAll(Enum.GetNames(typeof(ColorMode)), item => new GUIContent(item)); - public static GUIContent flipbookMode = EditorGUIUtility.TrTextContent("Flip-Book Mode", "Determines the blending mode used for animated texture sheets."); - public static GUIContent[] flipbookNames = Array.ConvertAll(Enum.GetNames(typeof(FlipbookMode)), item => new GUIContent(item)); - + public static GUIContent flipbookBlending = EditorGUIUtility.TrTextContent("Flip-Book Frame Blending", "Enables blending between the frames of animated texture sheets."); public static GUIContent twoSidedEnabled = EditorGUIUtility.TrTextContent("Two Sided", "Render both front and back faces of the particle geometry."); - public static GUIContent distortionEnabled = EditorGUIUtility.TrTextContent("Enable Distortion", "Use a grab pass and normal map to simulate refraction."); + public static GUIContent distortionEnabled = EditorGUIUtility.TrTextContent("Distortion", "Use a grab pass and normal map to simulate refraction."); public static GUIContent distortionStrengthText = EditorGUIUtility.TrTextContent("Strength", "Distortion Strength."); public static GUIContent distortionBlendText = EditorGUIUtility.TrTextContent("Blend", "Weighting between albedo and grab pass."); - public static GUIContent softParticlesEnabled = EditorGUIUtility.TrTextContent("Enable Soft Particles", "Fade out particle geometry when it gets close to the surface of objects written into the depth buffer."); + public static GUIContent softParticlesEnabled = EditorGUIUtility.TrTextContent("Soft Particles", "Fade out particle geometry when it gets close to the surface of objects written into the depth buffer."); public static GUIContent softParticlesNearFadeDistanceText = EditorGUIUtility.TrTextContent("Near fade", "Soft Particles near fade distance."); public static GUIContent softParticlesFarFadeDistanceText = EditorGUIUtility.TrTextContent("Far fade", "Soft Particles far fade distance."); - public static GUIContent cameraFadingEnabled = EditorGUIUtility.TrTextContent("Enable Camera Fading", "Fade out particle geometry when it gets close to the camera."); + public static GUIContent cameraFadingEnabled = EditorGUIUtility.TrTextContent("Camera Fading", "Fade out particle geometry when it gets close to the camera."); public static GUIContent cameraNearFadeDistanceText = EditorGUIUtility.TrTextContent("Near fade", "Camera near fade distance."); public static GUIContent cameraFarFadeDistanceText = EditorGUIUtility.TrTextContent("Far fade", "Camera far fade distance."); @@ -184,7 +182,7 @@ public void ShaderPropertiesGUI(Material material) EditorGUILayout.Space(); GUILayout.Label(Styles.mainOptionsText, EditorStyles.boldLabel); - FlipbookModePopup(); + FlipbookBlendingPopup(); TwoSidedPopup(material); FadingPopup(material); DistortionPopup(material); @@ -296,17 +294,17 @@ void ColorModePopup() } } - void FlipbookModePopup() + void FlipbookBlendingPopup() { EditorGUI.showMixedValue = flipbookMode.hasMixedValue; - var mode = (FlipbookMode)flipbookMode.floatValue; + var enabled = (flipbookMode.floatValue == (float)FlipbookMode.Blended); EditorGUI.BeginChangeCheck(); - mode = (FlipbookMode)EditorGUILayout.Popup(Styles.flipbookMode, (int)mode, Styles.flipbookNames); + enabled = EditorGUILayout.Toggle(Styles.flipbookBlending, enabled); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Flip-Book Mode"); - flipbookMode.floatValue = (float)mode; + flipbookMode.floatValue = enabled ? (float)FlipbookMode.Blended : (float)FlipbookMode.Simple; } EditorGUI.showMixedValue = false; diff --git a/Editor/Mono/Inspector/SurfaceEffector2DEditor.cs b/Editor/Mono/Inspector/SurfaceEffector2DEditor.cs deleted file mode 100644 index e2e1d2c4cd..0000000000 --- a/Editor/Mono/Inspector/SurfaceEffector2DEditor.cs +++ /dev/null @@ -1,84 +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.Collections.Generic; -using System.Linq; -using UnityEngine; -using UnityEditor.AnimatedValues; - -namespace UnityEditor -{ - /// - /// Prompts the end-user to add 2D colliders if non exist for 2D effector to work with. - /// - [CustomEditor(typeof(SurfaceEffector2D), true)] - [CanEditMultipleObjects] - internal class SurfaceEffector2DEditor : Effector2DEditor - { - readonly AnimBool m_ShowForceRollout = new AnimBool(); - SerializedProperty m_Speed; - SerializedProperty m_SpeedVariation; - SerializedProperty m_ForceScale; - - static readonly AnimBool m_ShowOptionsRollout = new AnimBool(); - SerializedProperty m_UseContactForce; - SerializedProperty m_UseFriction; - SerializedProperty m_UseBounce; - - public override void OnEnable() - { - base.OnEnable(); - - - m_ShowForceRollout.value = true; - m_ShowForceRollout.valueChanged.AddListener(Repaint); - m_Speed = serializedObject.FindProperty("m_Speed"); - m_SpeedVariation = serializedObject.FindProperty("m_SpeedVariation"); - m_ForceScale = serializedObject.FindProperty("m_ForceScale"); - - m_ShowOptionsRollout.valueChanged.AddListener(Repaint); - m_UseContactForce = serializedObject.FindProperty("m_UseContactForce"); - m_UseFriction = serializedObject.FindProperty("m_UseFriction"); - m_UseBounce = serializedObject.FindProperty("m_UseBounce"); - } - - public override void OnDisable() - { - base.OnDisable(); - - m_ShowForceRollout.valueChanged.RemoveListener(Repaint); - m_ShowOptionsRollout.valueChanged.RemoveListener(Repaint); - } - - public override void OnInspectorGUI() - { - base.OnInspectorGUI(); - - serializedObject.Update(); - - // Force. - m_ShowForceRollout.target = EditorGUILayout.Foldout(m_ShowForceRollout.target, "Force", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowForceRollout.faded)) - { - EditorGUILayout.PropertyField(m_Speed); - EditorGUILayout.PropertyField(m_SpeedVariation); - EditorGUILayout.PropertyField(m_ForceScale); - EditorGUILayout.Space(); - } - EditorGUILayout.EndFadeGroup(); - - // Options. - m_ShowOptionsRollout.target = EditorGUILayout.Foldout(m_ShowOptionsRollout.target, "Options", true); - if (EditorGUILayout.BeginFadeGroup(m_ShowOptionsRollout.faded)) - { - EditorGUILayout.PropertyField(m_UseContactForce); - EditorGUILayout.PropertyField(m_UseFriction); - EditorGUILayout.PropertyField(m_UseBounce); - } - EditorGUILayout.EndFadeGroup(); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/TagManagerInspector.cs b/Editor/Mono/Inspector/TagManagerInspector.cs index 4d6d4b4f38..b4548b6da4 100644 --- a/Editor/Mono/Inspector/TagManagerInspector.cs +++ b/Editor/Mono/Inspector/TagManagerInspector.cs @@ -175,7 +175,7 @@ void NewElement(Rect buttonRect, ReorderableList list) { buttonRect.x -= 400; buttonRect.y -= 13; - PopupWindow.Show(buttonRect, new EnterNamePopup(m_Tags, s => { InternalEditorUtility.AddTag(s); }), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(buttonRect, new EnterNamePopup(m_Tags, s => { InternalEditorUtility.AddTag(s); })); } private void RemoveFromTagsList(ReorderableList list) diff --git a/Editor/Mono/Inspector/TargetJoint2DEditor.cs b/Editor/Mono/Inspector/TargetJoint2DEditor.cs deleted file mode 100644 index 3872d74017..0000000000 --- a/Editor/Mono/Inspector/TargetJoint2DEditor.cs +++ /dev/null @@ -1,50 +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 -{ - [CustomEditor(typeof(TargetJoint2D))] - [CanEditMultipleObjects] - internal class TargetJoint2DEditor : Joint2DEditor - { - public void OnSceneGUI() - { - var targetJoint2D = (TargetJoint2D)target; - - // Ignore disabled joint. - if (!targetJoint2D.enabled) - return; - - // Fetch the anchor/target. - var jointAnchor = TransformPoint(targetJoint2D.transform, targetJoint2D.anchor); - var jointTarget = (Vector3)targetJoint2D.target; - - // Draw a line between the bodies. - Handles.color = Color.green; - Handles.DrawDottedLine(jointAnchor, jointTarget, 5.0f); - - // Draw the anchor point. - if (HandleAnchor(ref jointAnchor, false)) - { - Undo.RecordObject(targetJoint2D, "Move Anchor"); - targetJoint2D.anchor = InverseTransformPoint(targetJoint2D.transform, jointAnchor); - } - - // Draw the target point. - var targetScale = HandleUtility.GetHandleSize(jointTarget) * 0.3f; - var horzTarget = Vector3.left * targetScale; - var vertTarget = Vector3.up * targetScale; - DrawAALine(jointTarget - horzTarget, jointTarget + horzTarget); - DrawAALine(jointTarget - vertTarget, jointTarget + vertTarget); - if (HandleAnchor(ref jointTarget, true)) - { - Undo.RecordObject(targetJoint2D, "Move Target"); - targetJoint2D.target = jointTarget; - } - } - } -} diff --git a/Editor/Mono/Inspector/TerrainColliderEditor.cs b/Editor/Mono/Inspector/TerrainColliderEditor.cs deleted file mode 100644 index 5dfcd77277..0000000000 --- a/Editor/Mono/Inspector/TerrainColliderEditor.cs +++ /dev/null @@ -1,38 +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; - -namespace UnityEditor -{ - [CustomEditor(typeof(TerrainCollider))] - [CanEditMultipleObjects] - internal class TerrainColliderEditor : Collider3DEditorBase - { - SerializedProperty m_TerrainData; - SerializedProperty m_EnableTreeColliders; - - protected GUIContent terrainContent = EditorGUIUtility.TrTextContent("Terrain Data", "The TerrainData asset that stores heightmaps, terrain textures, detail meshes and trees."); - protected GUIContent treeColliderContent = EditorGUIUtility.TrTextContent("Enable Tree Colliders", "When selected, Tree Colliders will be enabled."); - - public override void OnEnable() - { - base.OnEnable(); - - m_TerrainData = serializedObject.FindProperty("m_TerrainData"); - m_EnableTreeColliders = serializedObject.FindProperty("m_EnableTreeColliders"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_Material, materialContent); - EditorGUILayout.PropertyField(m_TerrainData, terrainContent); - EditorGUILayout.PropertyField(m_EnableTreeColliders, treeColliderContent); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/TextMeshInspector.cs b/Editor/Mono/Inspector/TextMeshInspector.cs deleted file mode 100644 index d7d2fcf7c0..0000000000 --- a/Editor/Mono/Inspector/TextMeshInspector.cs +++ /dev/null @@ -1,38 +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 UnityEditor; - - -namespace UnityEditor -{ - [CustomEditor(typeof(TextMesh))] - [CanEditMultipleObjects] - internal class TextMeshInspector : Editor - { - SerializedProperty m_Font; - - void OnEnable() - { - m_Font = serializedObject.FindProperty("m_Font"); - } - - public override void OnInspectorGUI() - { - Font oldFont = m_Font.hasMultipleDifferentValues ? null : (m_Font.objectReferenceValue as Font); - DrawDefaultInspector(); - Font newFont = m_Font.hasMultipleDifferentValues ? null : (m_Font.objectReferenceValue as Font); - if (newFont != null && newFont != oldFont) - { - foreach (TextMesh textMesh in targets) - { - var renderer = textMesh.GetComponent(); - if (renderer) - renderer.sharedMaterial = newFont.material; - } - } - } - } -} diff --git a/Editor/Mono/Inspector/TextureInspector.cs b/Editor/Mono/Inspector/TextureInspector.cs index 86ba109b6e..ab99053c9b 100644 --- a/Editor/Mono/Inspector/TextureInspector.cs +++ b/Editor/Mono/Inspector/TextureInspector.cs @@ -2,8 +2,10 @@ // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License +using System.Collections.Generic; using UnityEngine; using UnityEditor; +using UnityEngine.Rendering; namespace UnityEditor @@ -48,8 +50,9 @@ internal class TextureInspector : Editor { class Styles { - public GUIContent smallZoom, largeZoom, alphaIcon, RGBIcon; + public GUIContent smallZoom, largeZoom; public GUIStyle previewButton, previewSlider, previewSliderThumb, previewLabel; + public GUIStyle previewButtonRed, previewButtonGreen, previewButtonBlue; public readonly GUIContent wrapModeLabel = EditorGUIUtility.TrTextContent("Wrap Mode"); public readonly GUIContent wrapU = EditorGUIUtility.TrTextContent("U axis"); @@ -77,9 +80,11 @@ public Styles() { smallZoom = EditorGUIUtility.IconContent("PreTextureMipMapLow"); largeZoom = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); - alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); - RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); + previewButton = "preButton"; + previewButtonRed = "preButtonRed"; + previewButtonGreen = "preButtonGreen"; + previewButtonBlue = "preButtonBlue"; previewSlider = "preSlider"; previewSliderThumb = "preSliderThumb"; previewLabel = "preLabelUpper"; @@ -87,8 +92,20 @@ public Styles() } static Styles s_Styles; - private bool m_ShowAlpha; - public bool showAlpha { get { return m_ShowAlpha; } } + enum PreviewMode + { + RGB, + R, + G, + B, + A, + }; + + private PreviewMode m_PreviewMode = PreviewMode.RGB; + public bool showAlpha + { + get { return m_PreviewMode == PreviewMode.A; } + } // Plain Texture protected SerializedProperty m_WrapU; @@ -410,7 +427,6 @@ public override void OnPreviewSettings() // and while it's being shown the actual texture object might disappear -- // make sure to handle null targets. Texture tex = target as Texture; - bool showMode = true; bool alphaOnly = false; bool hasAlpha = true; int mipCount = 1; @@ -448,19 +464,53 @@ public override void OnPreviewSettings() mipCount = Mathf.Max(mipCount, TextureUtil.GetMipmapCount(t)); } + + List previewCandidates = new List(5); + previewCandidates.Add(PreviewMode.RGB); + previewCandidates.Add(PreviewMode.R); + previewCandidates.Add(PreviewMode.G); + previewCandidates.Add(PreviewMode.B); + previewCandidates.Add(PreviewMode.A); + if (alphaOnly) { - m_ShowAlpha = true; - showMode = false; + previewCandidates.Clear(); + previewCandidates.Add(PreviewMode.A); + m_PreviewMode = PreviewMode.A; } else if (!hasAlpha) { - m_ShowAlpha = false; - showMode = false; + previewCandidates.Remove(PreviewMode.A); } - if (showMode && tex != null && !IsNormalMap(tex)) - m_ShowAlpha = GUILayout.Toggle(m_ShowAlpha, m_ShowAlpha ? s_Styles.alphaIcon : s_Styles.RGBIcon, s_Styles.previewButton); + + if (previewCandidates.Count > 1 && tex != null && !IsNormalMap(tex)) + { + int selectedIndex = previewCandidates.IndexOf(m_PreviewMode); + if (selectedIndex == -1) + selectedIndex = 0; + + if (previewCandidates.Contains(PreviewMode.RGB)) + m_PreviewMode = GUILayout.Toggle(m_PreviewMode == PreviewMode.RGB, "RGB", s_Styles.previewButton) + ? PreviewMode.RGB + : m_PreviewMode; + if (previewCandidates.Contains(PreviewMode.R)) + m_PreviewMode = GUILayout.Toggle(m_PreviewMode == PreviewMode.R, "R", s_Styles.previewButtonRed) + ? PreviewMode.R + : m_PreviewMode; + if (previewCandidates.Contains(PreviewMode.G)) + m_PreviewMode = GUILayout.Toggle(m_PreviewMode == PreviewMode.G, "G", s_Styles.previewButtonGreen) + ? PreviewMode.G + : m_PreviewMode; + if (previewCandidates.Contains(PreviewMode.B)) + m_PreviewMode = GUILayout.Toggle(m_PreviewMode == PreviewMode.B, "B", s_Styles.previewButtonBlue) + ? PreviewMode.B + : m_PreviewMode; + if (previewCandidates.Contains(PreviewMode.A)) + m_PreviewMode = GUILayout.Toggle(m_PreviewMode == PreviewMode.A, "A", s_Styles.previewButton) + ? PreviewMode.A + : m_PreviewMode; + } if (mipCount > 1) { @@ -512,14 +562,33 @@ public override void OnPreviewGUI(Rect r, GUIStyle background) PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); FilterMode oldFilter = t.filterMode; TextureUtil.SetFilterModeNoDirty(t, FilterMode.Point); - Texture2D t2d = t as Texture2D; - if (m_ShowAlpha) + ColorWriteMask colorWriteMask = ColorWriteMask.All; + + switch (m_PreviewMode) + { + case PreviewMode.R: + colorWriteMask = ColorWriteMask.Red | ColorWriteMask.Alpha; + break; + case PreviewMode.G: + colorWriteMask = ColorWriteMask.Green | ColorWriteMask.Alpha; + break; + case PreviewMode.B: + colorWriteMask = ColorWriteMask.Blue | ColorWriteMask.Alpha; + break; + } + + if (m_PreviewMode == PreviewMode.A) + { EditorGUI.DrawTextureAlpha(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel); - else if (t2d != null && t2d.alphaIsTransparency) - EditorGUI.DrawTextureTransparent(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel); + } else - EditorGUI.DrawPreviewTexture(wantedRect, t, null, ScaleMode.StretchToFill, 0, mipLevel); + { + if (t2d != null && t2d.alphaIsTransparency) + EditorGUI.DrawTextureTransparent(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel, colorWriteMask); + else + EditorGUI.DrawPreviewTexture(wantedRect, t, null, ScaleMode.StretchToFill, 0, mipLevel, colorWriteMask); + } // TODO: Less hacky way to prevent sprite rects to not appear in smaller previews like icons. if (wantedRect.width > 32 && wantedRect.height > 32) diff --git a/Editor/Mono/Inspector/TimeControl.cs b/Editor/Mono/Inspector/TimeControl.cs deleted file mode 100644 index 707cea4774..0000000000 --- a/Editor/Mono/Inspector/TimeControl.cs +++ /dev/null @@ -1,230 +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 UnityEditor; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class TimeControl - { - // currentTime will be clamped to preview range. - // Make sure it's initially at the beginning, even if the clip start is negative. - public float currentTime = Mathf.NegativeInfinity; - public float nextCurrentTime - { - set { deltaTime = value - currentTime; m_NextCurrentTimeSet = true; } - } - private bool m_NextCurrentTimeSet = false; - public float startTime = 0.0f; - public float stopTime = 1.0f; - public bool playSelection = false; - public bool loop = true; - public float playbackSpeed = 1.0f; - private float m_DeltaTime = 0.0f; - private bool m_DeltaTimeSet = false; - public float deltaTime - { - get { return m_DeltaTime; } - set { m_DeltaTime = value; m_DeltaTimeSet = true; } - } - public float normalizedTime - { - // Don't use InverseLerp and Lerp since they clamp between 0 and 1 - get { return (stopTime == startTime) ? 0 : ((currentTime - startTime) / (stopTime - startTime)); } - set { currentTime = startTime * (1 - value) + stopTime * value; } - } - public bool playing - { - get { return m_Playing; } - set - { - if (m_Playing != value) - { - // Start Playing - if (value) - { - EditorApplication.update += InspectorWindow.RepaintAllInspectors; - m_LastFrameEditorTime = EditorApplication.timeSinceStartup; - - if (m_ResetOnPlay) - { - nextCurrentTime = startTime; - m_ResetOnPlay = false; - } - } - // Stop Playing - else - { - EditorApplication.update -= InspectorWindow.RepaintAllInspectors; - } - } - - m_Playing = value; - } - } - - private double m_LastFrameEditorTime = 0.0f; - private bool m_Playing = false; - private bool m_ResetOnPlay = false; - private float m_MouseDrag = 0.0f; - private bool m_WrapForwardDrag = false; - - private const float kStepTime = 0.01f; - private const float kScrubberHeight = 21; - private const float kPlayButtonWidth = 33; - - private class Styles - { - public GUIContent playIcon = EditorGUIUtility.IconContent("PlayButton"); - public GUIContent pauseIcon = EditorGUIUtility.IconContent("PauseButton"); - - public GUIStyle playButton = "TimeScrubberButton"; - public GUIStyle timeScrubber = "TimeScrubber"; - } - private static Styles s_Styles; - - private static readonly int kScrubberIDHash = "ScrubberIDHash".GetHashCode(); - public void DoTimeControl(Rect rect) - { - if (s_Styles == null) - s_Styles = new Styles(); - - var evt = Event.current; - int id = EditorGUIUtility.GetControlID(kScrubberIDHash, FocusType.Keyboard); - - // Play/Pause Button + Scrubber - Rect timelineRect = rect; - timelineRect.height = kScrubberHeight; - // Only Scrubber - Rect scrubberRect = timelineRect; - scrubberRect.xMin += kPlayButtonWidth; - - // Handle Input - switch (evt.GetTypeForControl(id)) - { - case EventType.MouseDown: - if (rect.Contains(evt.mousePosition)) - { - EditorGUIUtility.keyboardControl = id; - } - if (scrubberRect.Contains(evt.mousePosition)) - { - EditorGUIUtility.SetWantsMouseJumping(1); - EditorGUIUtility.hotControl = id; - m_MouseDrag = evt.mousePosition.x - scrubberRect.xMin; - nextCurrentTime = (m_MouseDrag * (stopTime - startTime) / scrubberRect.width + startTime); - m_WrapForwardDrag = false; - evt.Use(); - } - break; - case EventType.MouseDrag: - if (EditorGUIUtility.hotControl == id) - { - m_MouseDrag += evt.delta.x * playbackSpeed; - // We want to not wrap if we immediately drag to the beginning, but we do want to wrap if we drag past the end. - if (loop && ((m_MouseDrag < 0.0f && m_WrapForwardDrag) || (m_MouseDrag > scrubberRect.width))) - { - // scrubing out of range was generating a big deltaTime in wrong time direction - // this new code prevent this and it is compliant with new and more robust v5.0 root motion looping of animation clip - if (m_MouseDrag > scrubberRect.width) - { - currentTime -= (stopTime - startTime); - } - else if (m_MouseDrag < 0) - { - currentTime += (stopTime - startTime); - } - - m_WrapForwardDrag = true; - m_MouseDrag = Mathf.Repeat(m_MouseDrag, scrubberRect.width); - } - nextCurrentTime = (Mathf.Clamp(m_MouseDrag, 0.0f, scrubberRect.width) * (stopTime - startTime) / scrubberRect.width + startTime); - evt.Use(); - } - break; - case EventType.MouseUp: - if (EditorGUIUtility.hotControl == id) - { - EditorGUIUtility.SetWantsMouseJumping(0); - EditorGUIUtility.hotControl = 0; - evt.Use(); - } - break; - case EventType.KeyDown: - if (EditorGUIUtility.keyboardControl == id) - { - // TODO: loop? - if (evt.keyCode == KeyCode.LeftArrow) - { - if (currentTime - startTime > kStepTime) - deltaTime = -kStepTime; - evt.Use(); - } - if (evt.keyCode == KeyCode.RightArrow) - { - if (stopTime - currentTime > kStepTime) - deltaTime = kStepTime; - evt.Use(); - } - } - break; - } - - // background - GUI.Box(timelineRect, GUIContent.none, s_Styles.timeScrubber); - - // Play/Pause Button - playing = GUI.Toggle(timelineRect, playing, playing ? s_Styles.pauseIcon : s_Styles.playIcon, s_Styles.playButton); - - // Current time indicator - float normalizedPosition = Mathf.Lerp(scrubberRect.x, scrubberRect.xMax, normalizedTime); - TimeArea.DrawPlayhead(normalizedPosition, scrubberRect.yMin, scrubberRect.yMax, 2f, (EditorGUIUtility.keyboardControl == id) ? 1f : 0.5f); - } - - public void OnDisable() - { - playing = false; - } - - public void Update() - { - // If the deltaTime was not set, update it when playing - if (!m_DeltaTimeSet) - { - if (playing) - { - double timeSinceStartup = EditorApplication.timeSinceStartup; - deltaTime = (float)(timeSinceStartup - m_LastFrameEditorTime) * playbackSpeed; - m_LastFrameEditorTime = timeSinceStartup; - } - else - deltaTime = 0; - } - - - currentTime += deltaTime; - - // If the nextCurrentTime was set explicitly, we don't want to loop - bool wrap = loop && playing && !m_NextCurrentTimeSet; - if (wrap) - { - normalizedTime = Mathf.Repeat(normalizedTime, 1.0f); - } - else - { - if (normalizedTime > 1) - { - playing = false; - m_ResetOnPlay = true; - } - normalizedTime = Mathf.Clamp01(normalizedTime); - } - - m_DeltaTimeSet = false; - m_NextCurrentTimeSet = false; - } - }//class TimeControl -}//namespace UnityEditor diff --git a/Editor/Mono/Inspector/TransformInspector.cs b/Editor/Mono/Inspector/TransformInspector.cs deleted file mode 100644 index 6d3b16bccb..0000000000 --- a/Editor/Mono/Inspector/TransformInspector.cs +++ /dev/null @@ -1,66 +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; - -namespace UnityEditor -{ - [CustomEditor(typeof(Transform))] - [CanEditMultipleObjects] - internal class TransformInspector : Editor - { - SerializedProperty m_Position; - SerializedProperty m_Scale; - TransformRotationGUI m_RotationGUI; - - class Contents - { - public GUIContent positionContent = EditorGUIUtility.TrTextContent("Position", "The local position of this GameObject relative to the parent."); - public GUIContent scaleContent = EditorGUIUtility.TrTextContent("Scale", "The local scaling of this GameObject relative to the parent."); - public string floatingPointWarning = LocalizationDatabase.GetLocalizedString("Due to floating-point precision limitations, it is recommended to bring the world coordinates of the GameObject within a smaller range."); - } - static Contents s_Contents; - - public void OnEnable() - { - m_Position = serializedObject.FindProperty("m_LocalPosition"); - m_Scale = serializedObject.FindProperty("m_LocalScale"); - - if (m_RotationGUI == null) - m_RotationGUI = new TransformRotationGUI(); - m_RotationGUI.OnEnable(serializedObject.FindProperty("m_LocalRotation"), EditorGUIUtility.TrTextContent("Rotation", "The local rotation of this GameObject relative to the parent.")); - } - - public override void OnInspectorGUI() - { - if (s_Contents == null) - s_Contents = new Contents(); - - if (!EditorGUIUtility.wideMode) - { - EditorGUIUtility.wideMode = true; - EditorGUIUtility.labelWidth = EditorGUIUtility.currentViewWidth - 212; - } - - serializedObject.Update(); - - Inspector3D(); - // Warning if global position is too large for floating point errors. - // SanitizeBounds function doesn't even support values beyond 100000 - Transform t = target as Transform; - Vector3 pos = t.position; - if (Mathf.Abs(pos.x) > 100000 || Mathf.Abs(pos.y) > 100000 || Mathf.Abs(pos.z) > 100000) - EditorGUILayout.HelpBox(s_Contents.floatingPointWarning, MessageType.Warning); - - serializedObject.ApplyModifiedProperties(); - } - - private void Inspector3D() - { - EditorGUILayout.PropertyField(m_Position, s_Contents.positionContent); - m_RotationGUI.RotationField(); - EditorGUILayout.PropertyField(m_Scale, s_Contents.scaleContent); - } - } -} diff --git a/Editor/Mono/Inspector/TransformUtils.cs b/Editor/Mono/Inspector/TransformUtils.cs deleted file mode 100644 index 6238ea9153..0000000000 --- a/Editor/Mono/Inspector/TransformUtils.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 UnityEngine; -using UnityEditor; - -namespace UnityEditor -{ - public static class TransformUtils - { - public static Vector3 GetInspectorRotation(Transform t) - { - return t.GetLocalEulerAngles(t.rotationOrder); - } - - public static void SetInspectorRotation(Transform t, Vector3 r) - { - t.SetLocalEulerAngles(r, t.rotationOrder); - } - } -} diff --git a/Editor/Mono/Inspector/UNetBehaviourInspector.cs b/Editor/Mono/Inspector/UNetBehaviourInspector.cs deleted file mode 100644 index aa57e50446..0000000000 --- a/Editor/Mono/Inspector/UNetBehaviourInspector.cs +++ /dev/null @@ -1,5 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -// gone diff --git a/Editor/Mono/Inspector/WebCamTextureInspector.cs b/Editor/Mono/Inspector/WebCamTextureInspector.cs deleted file mode 100644 index b1a8334e4a..0000000000 --- a/Editor/Mono/Inspector/WebCamTextureInspector.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 UnityEngine; -using UnityEditor; - -namespace UnityEditor -{ - [CustomEditor(typeof(WebCamTexture))] - internal class WebCamTextureInspector : Editor - { - static GUIContent[] s_PlayIcons = {null, null}; - Vector2 m_Pos; - - public override void OnInspectorGUI() - { - WebCamTexture t = target as WebCamTexture; - EditorGUILayout.LabelField("Requested FPS", t.requestedFPS.ToString()); - EditorGUILayout.LabelField("Requested Width", t.requestedWidth.ToString()); - EditorGUILayout.LabelField("Requested Height", t.requestedHeight.ToString()); - EditorGUILayout.LabelField("Device Name", t.deviceName); - } - - static void Init() - { - s_PlayIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff"); - s_PlayIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn"); - } - - public override bool HasPreviewGUI() - { - return (target != null); - } - - public override void OnPreviewSettings() - { - Init(); - - // Disallow playing movie previews in play mode. Better not to interfere - // with any playback the game does. - GUI.enabled = !Application.isPlaying; - WebCamTexture t = target as WebCamTexture; - bool isPlaying = PreviewGUI.CycleButton(t.isPlaying ? 1 : 0, s_PlayIcons) != 0; - if (isPlaying != t.isPlaying) - { - if (isPlaying) - { - t.Stop(); - t.Play(); - } - else - { - t.Pause(); - } - } - GUI.enabled = true; - } - - public override void OnPreviewGUI(Rect r, GUIStyle background) - { - if (Event.current.type == EventType.Repaint) - background.Draw(r, false, false, false, false); - - // show texture - WebCamTexture t = target as WebCamTexture; - - float zoomLevel = Mathf.Min(Mathf.Min(r.width / t.width, r.height / t.height), 1); - Rect wantedRect = new Rect(r.x, r.y, t.width * zoomLevel, t.height * zoomLevel); - PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); - GUI.DrawTexture(wantedRect, t, ScaleMode.StretchToFill, false); - m_Pos = PreviewGUI.EndScrollView(); - - // force update GUI - if (t.isPlaying) - GUIView.current.Repaint(); - - if (Application.isPlaying) - { - if (t.isPlaying) - EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10, r.width, 20), "Can't pause preview when in play mode"); - else - EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10, r.width, 20), "Can't start preview when in play mode"); - } - } - - public void OnDisable() - { - WebCamTexture t = target as WebCamTexture; - - //stop the camera if we started it - if (!Application.isPlaying && t != null) - { - t.Stop(); - } - } - - public override string GetInfoString() - { - Texture t = target as Texture; - string info = t.width.ToString() + "x" + t.height.ToString(); - TextureFormat format = TextureUtil.GetTextureFormat(t); - info += " " + TextureUtil.GetTextureFormatString(format); - return info; - } - } -} diff --git a/Editor/Mono/Inspector/WheelColliderEditor.cs b/Editor/Mono/Inspector/WheelColliderEditor.cs deleted file mode 100644 index 9a8876b770..0000000000 --- a/Editor/Mono/Inspector/WheelColliderEditor.cs +++ /dev/null @@ -1,58 +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 UnityEditor; -using UnityEditorInternal; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(WheelCollider))] - [CanEditMultipleObjects] - internal class WheelColliderEditor : Editor - { - SerializedProperty m_Center; - SerializedProperty m_Radius; - SerializedProperty m_SuspensionDistance; - SerializedProperty m_SuspensionSpring; - SerializedProperty m_ForceAppPointDistance; - SerializedProperty m_Mass; - SerializedProperty m_WheelDampingRate; - SerializedProperty m_ForwardFriction; - SerializedProperty m_SidewaysFriction; - - public void OnEnable() - { - // Wheel Collider does not serialize Collider properties, so we don't use base OnEnable like other collider types - m_Center = serializedObject.FindProperty("m_Center"); - m_Radius = serializedObject.FindProperty("m_Radius"); - m_SuspensionDistance = serializedObject.FindProperty("m_SuspensionDistance"); - m_SuspensionSpring = serializedObject.FindProperty("m_SuspensionSpring"); - m_Mass = serializedObject.FindProperty("m_Mass"); - m_ForceAppPointDistance = serializedObject.FindProperty("m_ForceAppPointDistance"); - m_WheelDampingRate = serializedObject.FindProperty("m_WheelDampingRate"); - m_ForwardFriction = serializedObject.FindProperty("m_ForwardFriction"); - m_SidewaysFriction = serializedObject.FindProperty("m_SidewaysFriction"); - } - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_Mass); - EditorGUILayout.PropertyField(m_Radius); - EditorGUILayout.PropertyField(m_WheelDampingRate); - EditorGUILayout.PropertyField(m_SuspensionDistance); - EditorGUILayout.PropertyField(m_ForceAppPointDistance); - EditorGUILayout.Space(); - EditorGUILayout.PropertyField(m_Center); - EditorGUILayout.Space(); - StructPropertyGUILayout.GenericStruct(m_SuspensionSpring); - StructPropertyGUILayout.GenericStruct(m_ForwardFriction); - StructPropertyGUILayout.GenericStruct(m_SidewaysFriction); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/Inspector/WheelJoint2DEditor.cs b/Editor/Mono/Inspector/WheelJoint2DEditor.cs deleted file mode 100644 index 65dbf3cd9e..0000000000 --- a/Editor/Mono/Inspector/WheelJoint2DEditor.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 System; -using UnityEngine; - -namespace UnityEditor -{ - [CustomEditor(typeof(WheelJoint2D))] - [CanEditMultipleObjects] - internal class WheelJoint2DEditor : AnchoredJoint2DEditor - { - new public void OnSceneGUI() - { - var wheelJoint2D = (WheelJoint2D)target; - - // Ignore disabled joint. - if (!wheelJoint2D.enabled) - return; - - var anchor = TransformPoint(wheelJoint2D.transform, wheelJoint2D.anchor); - - // Draw lines for slider angle and limits - Vector3 upper = anchor; - Vector3 lower = anchor; - Vector3 direction = RotateVector2(Vector3.right, -wheelJoint2D.suspension.angle - wheelJoint2D.transform.eulerAngles.z); - - Handles.color = Color.green; - - direction *= HandleUtility.GetHandleSize(anchor) * 0.3f; - upper += direction; - lower -= direction; - - DrawAALine(upper, lower); - - base.OnSceneGUI(); - } - } -} diff --git a/Editor/Mono/Internal/MonoScripts.cs b/Editor/Mono/Internal/MonoScripts.cs deleted file mode 100644 index bde203fa3d..0000000000 --- a/Editor/Mono/Internal/MonoScripts.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 UnityEditor; -using UnityEngine; - -namespace UnityEditorInternal -{ - /// - /// Helper factory for instances. - /// - public static class MonoScripts - { - public static MonoScript CreateMonoScript(string scriptContents, string className, string nameSpace, string assemblyName, bool isEditorScript) - { - var script = new MonoScript(); - script.Init(scriptContents, className, nameSpace, assemblyName, isEditorScript); - return script; - } - } -} diff --git a/Editor/Mono/JSProxy/ClipboardAccess.cs b/Editor/Mono/JSProxy/ClipboardAccess.cs deleted file mode 100644 index 52fc2cd3b7..0000000000 --- a/Editor/Mono/JSProxy/ClipboardAccess.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 UnityEditor; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - internal class ClipboardAccess - { - private ClipboardAccess() - { - // Nothing to do - } - - public void CopyToClipboard(string value) - { - TextEditor te = new TextEditor(); - te.text = value; - te.SelectAll(); - te.Copy(); - } - - public string PasteFromClipboard() - { - TextEditor te = new TextEditor(); - te.Paste(); - return te.text; - } - - static ClipboardAccess() - { - JSProxyMgr.GetInstance().AddGlobalObject("unity/ClipboardAccess", new ClipboardAccess()); - } - } -} - diff --git a/Editor/Mono/JSProxy/PreviewGenerator.cs b/Editor/Mono/JSProxy/PreviewGenerator.cs deleted file mode 100644 index edec441abe..0000000000 --- a/Editor/Mono/JSProxy/PreviewGenerator.cs +++ /dev/null @@ -1,50 +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 UnityEditor; -using System; -using System.Collections; - -namespace UnityEditor.Web -{ - internal class PreviewGenerator - { - const string kPreviewBuildFolder = "builds"; - - static protected PreviewGenerator s_Instance = null; - - public static PreviewGenerator GetInstance() - { - if (s_Instance == null) - { - return new PreviewGenerator(); - } - return s_Instance; - } - - public byte[] GeneratePreview(string assetPath, int width, int height) - { - UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(assetPath); - if (obj == null) - return null; - - Editor editor = Editor.CreateEditor(obj); - if (editor == null) - return null; - - Texture2D tex = editor.RenderStaticPreview(assetPath, null, width, height); - if (tex == null) - { - UnityEngine.Object.DestroyImmediate(editor); - return null; - } - - byte[] bytes = tex.EncodeToPNG(); - UnityEngine.Object.DestroyImmediate(tex); - UnityEngine.Object.DestroyImmediate(editor); - return bytes; - } - } -} diff --git a/Editor/Mono/JSProxy/TroubleshooterAccess.cs b/Editor/Mono/JSProxy/TroubleshooterAccess.cs deleted file mode 100644 index b20e25dd1a..0000000000 --- a/Editor/Mono/JSProxy/TroubleshooterAccess.cs +++ /dev/null @@ -1,61 +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 UnityEditor; -using UnityEditor.Connect; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - internal class TroubleshooterAccess - { - private TroubleshooterAccess() - { - // Nothing to do - } - - public string GetUserName() - { - var uc = UnityConnect.instance; - if (!uc.GetConnectInfo().loggedIn) - { - return "Anonymous"; - } - return uc.GetUserName(); - } - - public string GetUserId() - { - var uc = UnityConnect.instance; - if (!uc.GetConnectInfo().loggedIn) - { - return string.Empty; - } - return uc.GetUserInfo().userId; - } - - public void SignIn() - { - UnityConnect.instance.ShowLogin(); - } - - public void SignOut() - { - UnityConnect.instance.Logout(); - } - - public void StartBugReporter() - { - EditorUtility.LaunchBugReporter(); - } - - static TroubleshooterAccess() - { - JSProxyMgr.GetInstance().AddGlobalObject("/unity/editor/troubleshooter", new TroubleshooterAccess()); - } - } -} - diff --git a/Editor/Mono/LookDevView/CameraState.cs b/Editor/Mono/LookDevView/CameraState.cs deleted file mode 100644 index d7e0aad601..0000000000 --- a/Editor/Mono/LookDevView/CameraState.cs +++ /dev/null @@ -1,75 +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 UnityEditor.AnimatedValues; -using System; -using UnityEngine; -using System.Collections.Generic; -using UnityEditorInternal; - -namespace UnityEditor -{ - [Serializable] - internal class CameraState - { - private static readonly Quaternion kDefaultRotation = Quaternion.LookRotation(new Vector3(0.0f, 0.0f, 1.0f)); - private const float kDefaultViewSize = 10f; - private static readonly Vector3 kDefaultPivot = Vector3.zero; - private const float kDefaultFoV = 90f; - - [SerializeField] private AnimVector3 m_Pivot = new AnimVector3(kDefaultPivot); - [SerializeField] private AnimQuaternion m_Rotation = new AnimQuaternion(kDefaultRotation); - [SerializeField] private AnimFloat m_ViewSize = new AnimFloat(kDefaultViewSize); - - public float GetCameraDistance() - { - float fov = kDefaultFoV; - return m_ViewSize.value / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad); - } - - public void FixNegativeSize() - { - float fov = kDefaultFoV; - if (m_ViewSize.value < 0) - { - float distance = m_ViewSize.value / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad); - Vector3 p = m_Pivot.value + m_Rotation.value * new Vector3(0, 0, -distance); - m_ViewSize.value = -m_ViewSize.value; - distance = m_ViewSize.value / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad); - m_Pivot.value = p + m_Rotation.value * new Vector3(0, 0, distance); - } - } - - public void UpdateCamera(Camera camera) - { - camera.transform.rotation = m_Rotation.value; - camera.transform.position = m_Pivot.value + camera.transform.rotation * new Vector3(0, 0, -GetCameraDistance()); - - float farClip = Mathf.Max(1000f, 2000f * m_ViewSize.value); - camera.nearClipPlane = farClip * 0.000005f; - camera.farClipPlane = farClip; - } - - public CameraState Clone() - { - CameraState newState = new CameraState(); - newState.pivot.value = pivot.value; - newState.rotation.value = rotation.value; - newState.viewSize.value = viewSize.value; - - return newState; - } - - public void Copy(CameraState cameraStateIn) - { - pivot.value = cameraStateIn.pivot.value; - rotation.value = cameraStateIn.rotation.value; - viewSize.value = cameraStateIn.viewSize.value; - } - - public AnimVector3 pivot { get { return m_Pivot; } set { m_Pivot = value; } } - public AnimQuaternion rotation { get { return m_Rotation; } set { m_Rotation = value; } } - public AnimFloat viewSize { get { return m_ViewSize; } set { m_ViewSize = value; } } - } -} diff --git a/Editor/Mono/LookDevView/LookDevContext.cs b/Editor/Mono/LookDevView/LookDevContext.cs deleted file mode 100644 index 9fbbb22236..0000000000 --- a/Editor/Mono/LookDevView/LookDevContext.cs +++ /dev/null @@ -1,80 +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 UnityEditor; - -namespace UnityEditor -{ - [Serializable] - internal class LookDevContext - { - [Serializable] - public class LookDevPropertyValue - { - public float floatValue = 0.0f; - public int intValue = 0; - } - - [SerializeField] - private LookDevPropertyValue[] m_Properties = new LookDevPropertyValue[(int)LookDevProperty.Count]; - - public float exposureValue - { - get { return m_Properties[(int)LookDevProperty.ExposureValue].floatValue; } - } - - public float envRotation - { - get { return m_Properties[(int)LookDevProperty.EnvRotation].floatValue; } - set { m_Properties[(int)LookDevProperty.EnvRotation].floatValue = value; } - } - - public int currentHDRIIndex - { - get { return m_Properties[(int)LookDevProperty.HDRI].intValue; } - set { m_Properties[(int)LookDevProperty.HDRI].intValue = value; } - } - - public int shadingMode - { - get { return m_Properties[(int)LookDevProperty.ShadingMode].intValue; } - } - - public int lodIndex - { - get { return m_Properties[(int)LookDevProperty.LoDIndex].intValue; } - } - - public LookDevContext() - { - for (int i = 0; i < (int)LookDevProperty.Count; ++i) - { - m_Properties[i] = new LookDevPropertyValue(); - } - - m_Properties[(int)LookDevProperty.ExposureValue].floatValue = 0.0f; - m_Properties[(int)LookDevProperty.HDRI].intValue = 0; - m_Properties[(int)LookDevProperty.ShadingMode].intValue = (int)DrawCameraMode.Normal; - m_Properties[(int)LookDevProperty.LoDIndex].intValue = -1; - m_Properties[(int)LookDevProperty.EnvRotation].floatValue = 0.0f; - } - - public LookDevPropertyValue GetProperty(LookDevProperty property) - { - return m_Properties[(int)property]; - } - - public void UpdateProperty(LookDevProperty property, float value) - { - m_Properties[(int)property].floatValue = value; - } - - public void UpdateProperty(LookDevProperty property, int value) - { - m_Properties[(int)property].intValue = value; - } - } -} diff --git a/Editor/Mono/LookDevView/LookDevEnvironmentLibrary.cs b/Editor/Mono/LookDevView/LookDevEnvironmentLibrary.cs deleted file mode 100644 index 1640b96854..0000000000 --- a/Editor/Mono/LookDevView/LookDevEnvironmentLibrary.cs +++ /dev/null @@ -1,227 +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 System.Collections.Generic; -using UnityEditor.Experimental.AssetImporters; -using UnityEngine.Rendering; - -namespace UnityEditor -{ - internal class LookDevEnvironmentLibrary - : ScriptableObject, ISerializationCallbackReceiver - { - [SerializeField] private List m_HDRIList = new List(); - [SerializeField] private List m_SerialShadowMapHDRIList = new List(); // Dedicated to save shadow cubemap info for serialization purpose - - private LookDevView m_LookDevView = null; - private bool m_Dirty = false; - - public bool dirty - { - get { return m_Dirty; } - set { m_Dirty = value; } - } - - public List hdriList - { - get { return m_HDRIList; } - } - - public int hdriCount - { - get { return hdriList.Count; } - } - - public void InsertHDRI(Cubemap cubemap) - { - InsertHDRI(cubemap, -1); - } - - // If insertionIndex is -1 it mean we insert at the end of the list - public void InsertHDRI(Cubemap cubemap, int insertionIndex) - { - Undo.RecordObject(m_LookDevView.envLibrary, "Insert HDRI"); - Undo.RecordObject(m_LookDevView.config, "Insert HDRI"); - - // Handle cubemap index remapping for both context. Simply do it brute force in all cases. - // Save the cubemap info before any modification to m_HDRIList. - // Also if we are inserting m_DefaultHDRI, it mean we have an empty m_HDRIList - Cubemap cubemap0 = null; - Cubemap cubemap1 = null; - - if (cubemap == LookDevResources.m_DefaultHDRI) - { - cubemap0 = LookDevResources.m_DefaultHDRI; - cubemap1 = LookDevResources.m_DefaultHDRI; - } - else - { - cubemap0 = m_HDRIList[m_LookDevView.config.lookDevContexts[0].currentHDRIIndex].cubemap; - cubemap1 = m_HDRIList[m_LookDevView.config.lookDevContexts[1].currentHDRIIndex].cubemap; - } - - // Check if the cubemap already exist - int iIndex = m_HDRIList.FindIndex(x => x.cubemap == cubemap); - - // Create cubemap if it doesn't exist - if (iIndex == -1) - { - m_Dirty = true; - - CubemapInfo newInfo = null; - - // Check if the cubemap exist but as a shadow cubemap only - // in this case we don't recreate the CubemapInfo, but we still insert it as a new one. - for (int i = 0; i < m_HDRIList.Count; ++i) - { - if (m_HDRIList[i].cubemapShadowInfo.cubemap == cubemap) - { - newInfo = m_HDRIList[i].cubemapShadowInfo; - // Prevent recursion with shadow cubemap info - newInfo.SetCubemapShadowInfo(newInfo); - break; - } - } - - if (newInfo == null) - { - newInfo = new CubemapInfo(); - newInfo.cubemap = cubemap; - newInfo.ambientProbe.Clear(); - newInfo.alreadyComputed = false; - newInfo.SetCubemapShadowInfo(newInfo); // By default we use the same cubemap for the version without sun. - } - - int newCubemapIndex = m_HDRIList.Count; - // Add the cubemap to the specified location or last if no location provide - m_HDRIList.Insert(insertionIndex == -1 ? newCubemapIndex : insertionIndex, newInfo); - - // When inserting the default HDRI the first time, the lookdev env is not yet ready. - // But as we default the latlong light position of ShadowInfo to brightest location of default HDRI this is not a problem to not call the function. - if (newInfo.cubemap != LookDevResources.m_DefaultHDRI) - LookDevResources.UpdateShadowInfoWithBrightestSpot(newInfo); - } - - // If we haven't inserted at end of the list, if it is not a new cubemap and if we do not insert at the same place, we need to shift current cubemap position in the list - if (iIndex != insertionIndex && iIndex != -1 && insertionIndex != -1) - { - // Get cubemap info before modifying m_LookDevSetup.m_HDRIList; - CubemapInfo infos = m_HDRIList[iIndex]; - - m_HDRIList.RemoveAt(iIndex); - // If we insert after the removed cubemap we need to increase the index - m_HDRIList.Insert(iIndex > insertionIndex ? insertionIndex : insertionIndex - 1, infos); - } - - m_LookDevView.config.lookDevContexts[0].UpdateProperty(LookDevProperty.HDRI, m_HDRIList.FindIndex(x => x.cubemap == cubemap0)); - m_LookDevView.config.lookDevContexts[1].UpdateProperty(LookDevProperty.HDRI, m_HDRIList.FindIndex(x => x.cubemap == cubemap1)); - - m_LookDevView.Repaint(); - } - - public bool RemoveHDRI(Cubemap cubemap) - { - if (cubemap != null) - { - Undo.RecordObject(m_LookDevView.envLibrary, "Remove HDRI"); - Undo.RecordObject(m_LookDevView.config, "Remove HDRI"); - } - - if (cubemap == LookDevResources.m_DefaultHDRI) - { - Debug.LogWarning("Cannot remove default HDRI from the library"); - return false; - } - - int iIndex = m_HDRIList.FindIndex(x => x.cubemap == cubemap); - if (iIndex != -1) - { - Cubemap cubemap0 = m_HDRIList[m_LookDevView.config.lookDevContexts[0].currentHDRIIndex].cubemap; - Cubemap cubemap1 = m_HDRIList[m_LookDevView.config.lookDevContexts[1].currentHDRIIndex].cubemap; - - m_HDRIList.RemoveAt(iIndex); - - int defaultIndex = m_HDRIList.Count == 0 ? -1 : 0; - - // If not the one removed, restore the right indices for both views - m_LookDevView.config.lookDevContexts[0].UpdateProperty(LookDevProperty.HDRI, cubemap0 == cubemap ? defaultIndex : m_HDRIList.FindIndex(x => x.cubemap == cubemap0)); - m_LookDevView.config.lookDevContexts[1].UpdateProperty(LookDevProperty.HDRI, cubemap1 == cubemap ? defaultIndex : m_HDRIList.FindIndex(x => x.cubemap == cubemap1)); - - m_LookDevView.Repaint(); - m_Dirty = true; - return true; - } - - return false; - } - - public void CleanupDeletedHDRI() - { - while (RemoveHDRI(null)) - { - // When we suppress HDRI we will have null reference, so keep the list clean and delete in the list - } - } - - ShadowInfo GetCurrentShadowInfo() - { - return m_HDRIList[m_LookDevView.config.lookDevContexts[(int)m_LookDevView.config.currentEditionContext].currentHDRIIndex].shadowInfo; - } - - public void SetLookDevView(LookDevView lookDevView) - { - m_LookDevView = lookDevView; - } - - public void OnBeforeSerialize() - { - m_SerialShadowMapHDRIList.Clear(); - - // We need to 'convert' all shadow cubemap to index before saving, any shadow cubemap without matching HDRI in the main list - // will be added to the HDRI list for serialization. - for (int i = 0; i < m_HDRIList.Count; ++i) - { - CubemapInfo shadowCubemapInfo = m_HDRIList[i].cubemapShadowInfo; - - // Check if we have already added it to shadow cubemap list - m_HDRIList[i].serialIndexMain = m_HDRIList.FindIndex(x => x == shadowCubemapInfo); - if (m_HDRIList[i].serialIndexMain == -1) - { - m_HDRIList[i].serialIndexShadow = m_SerialShadowMapHDRIList.FindIndex(x => x == shadowCubemapInfo); - if (m_HDRIList[i].serialIndexShadow == -1) - { - m_SerialShadowMapHDRIList.Add(shadowCubemapInfo); - m_HDRIList[i].serialIndexShadow = m_SerialShadowMapHDRIList.Count - 1; - } - } - } - } - - public void OnAfterDeserialize() - { - for (int i = 0; i < m_HDRIList.Count; ++i) - { - if (m_HDRIList[i].serialIndexMain != -1) - { - m_HDRIList[i].cubemapShadowInfo = m_HDRIList[hdriList[i].serialIndexMain]; - } - else - { - m_HDRIList[i].cubemapShadowInfo = m_SerialShadowMapHDRIList[m_HDRIList[i].serialIndexShadow]; - } - } - } - } - - [CustomEditor(typeof(LookDevEnvironmentLibrary))] - internal class LookDevEnvironmentLibraryInspector : AssetImporterEditor - { - // We don't want users to edit these in the inspector - public override void OnInspectorGUI() - { - } - } -} diff --git a/Editor/Mono/LookDevView/LookDevInc.cs b/Editor/Mono/LookDevView/LookDevInc.cs deleted file mode 100644 index 4ef3a62b9d..0000000000 --- a/Editor/Mono/LookDevView/LookDevInc.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 UnityEngine; -using UnityEngine.Rendering; -using UnityEditor.AnimatedValues; -using System.Collections.Generic; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal enum LookDevPropertyType - { - Int = 0, - Float, - } - - internal enum LookDevProperty - { - ExposureValue = 0, - HDRI, - ShadingMode, - EnvRotation, - LoDIndex, - Count - } - - internal enum LookDevMode - { - Single1 = 0, - Single2, - SideBySide, - Split, - Zone, - Count - } - - internal enum LookDevEditionContext - { - Left = 0, - Right = 1, - None = 2 - } - - enum LookDevOperationType - { - None = 0, - GizmoTranslation, - GizmoRotationZone1, - GizmoRotationZone2, - GizmoAll, // Used in shader to highlight all gizmo parts - BlendFactor, - RotateLight, - RotateEnvironment - } - - [Serializable] - internal class GizmoInfo - { - [SerializeField] - private Vector2 m_Point1; - [SerializeField] - private Vector2 m_Point2; - [SerializeField] - private Vector2 m_Center = new Vector2(0.0f, 0.0f); - [SerializeField] - private float m_Angle = 0.0f; - [SerializeField] - private float m_Length = 0.2f; - [SerializeField] - private Vector4 m_Plane; - [SerializeField] - private Vector4 m_PlaneOrtho; - - public GizmoInfo() - { - Update(m_Center, m_Length, m_Angle); - } - - public Vector2 point1 - { - get { return m_Point1; } - } - - public Vector2 point2 - { - get { return m_Point2; } - } - - public Vector2 center - { - get { return m_Center; } - } - - public float angle - { - get { return m_Angle; } - } - - public float length - { - get { return m_Length; } - } - - public Vector4 plane - { - get { return m_Plane; } - } - - public Vector4 planeOrtho - { - get { return m_PlaneOrtho; } - } - - private Vector4 Get2DPlane(Vector2 firstPoint, float angle) - { - Vector4 result = new Vector4(); - angle = angle % (2.0f * (float)Math.PI); - Vector2 secondPoint = new Vector2(firstPoint.x + Mathf.Sin(angle), firstPoint.y + Mathf.Cos(angle)); - Vector2 diff = secondPoint - firstPoint; - if (Mathf.Abs(diff.x) < 1e-5) - { - result.Set(-1.0f, 0.0f, firstPoint.x, 0.0f); - float sign = Mathf.Cos(angle) > 0.0f ? 1.0f : -1.0f; - result *= sign; - } - else - { - float slope = diff.y / diff.x; - result.Set(-slope, 1.0f, -(firstPoint.y - slope * firstPoint.x), 0.0f); - } - - if (angle > Mathf.PI) - result = -result; - - float length = Mathf.Sqrt(result.x * result.x + result.y * result.y); - result = result / length; - return result; - } - - public void Update(Vector2 point1, Vector2 point2) - { - m_Point1 = point1; - m_Point2 = point2; - m_Center = (point1 + point2) * 0.5f; - m_Length = (point2 - point1).magnitude * 0.5f; - - Vector3 verticalPlane = Get2DPlane(m_Center, 0.0f); - float side = Vector3.Dot(new Vector3(point1.x, point1.y, 1.0f), verticalPlane); - m_Angle = (Mathf.Deg2Rad * Vector2.Angle(new Vector2(0.0f, 1.0f), (point1 - point2).normalized)); - if (side > 0.0f) - m_Angle = 2.0f * Mathf.PI - m_Angle; - - m_Plane = Get2DPlane(m_Center, m_Angle); - m_PlaneOrtho = Get2DPlane(m_Center, m_Angle + 0.5f * (float)Mathf.PI); - } - - public void Update(Vector2 center, float length, float angle) - { - m_Center = center; - m_Length = length; - m_Angle = angle; - - m_Plane = Get2DPlane(m_Center, m_Angle); - m_PlaneOrtho = Get2DPlane(m_Center, m_Angle + 0.5f * (float)Mathf.PI); - - Vector2 dir = new Vector2(m_PlaneOrtho.x, m_PlaneOrtho.y); - m_Point1 = m_Center + dir * m_Length; - m_Point2 = m_Center - dir * m_Length; - } - } - - [Serializable] - internal class LookDevPropertyInfo - { - [SerializeField] - private bool m_Linked = false; - [SerializeField] - private LookDevPropertyType m_PropertyType; - - public LookDevPropertyType propertyType - { - get { return m_PropertyType; } - } - public bool linked - { - get { return m_Linked; } - set { m_Linked = value; } - } - - public LookDevPropertyInfo(LookDevPropertyType type) - { - m_PropertyType = type; - } - } - - [Serializable] - internal class ShadowInfo - { - // Setup default position to be on the sun in the default HDRI. - // This is important as the defaultHDRI don't call the set brightest spot funciton on first call. - [SerializeField] - private float m_Latitude = 60.0f; // [-90..90] - [SerializeField] - private float m_Longitude = 299.0f; // [0..360] - [SerializeField] - private float m_ShadowIntensity = 1.0f; - [SerializeField] - private Color m_ShadowColor = Color.white; - - public float shadowIntensity - { - get { return m_ShadowIntensity; } - set { m_ShadowIntensity = value; } - } - - public Color shadowColor - { - get { return m_ShadowColor; } - set { m_ShadowColor = value; } - } - - public float latitude - { - get { return m_Latitude; } - set { m_Latitude = value; ConformLatLong(); } - } - - public float longitude - { - get { return m_Longitude; } - set { m_Longitude = value; ConformLatLong(); } - } - - private void ConformLatLong() - { - // Clamp latitude to [-90..90] - if (m_Latitude < -90.0f) - m_Latitude = -90.0f; - if (m_Latitude > 89.0f) - m_Latitude = 89.0f; - - // wrap longitude around - m_Longitude = m_Longitude % 360.0f; - if (m_Longitude < 0.0) - m_Longitude = 360.0f + m_Longitude; - } - } - - [Serializable] - internal class CubemapInfo - { - const float kDefaultShadowIntensity = 0.3f; - - public void SetCubemapShadowInfo(CubemapInfo newCubemapShadowInfo) - { - cubemapShadowInfo = newCubemapShadowInfo; - shadowInfo.shadowIntensity = newCubemapShadowInfo == this ? kDefaultShadowIntensity : 1.0f; - shadowInfo.shadowColor = Color.white; - } - - public void ResetEnvInfos() - { - angleOffset = 0.0f; - } - - public Cubemap cubemap; - public CubemapInfo cubemapShadowInfo; - public float angleOffset = 0.0f; - public SphericalHarmonicsL2 ambientProbe; - public ShadowInfo shadowInfo = new ShadowInfo(); - - // Dedicated to serialization workaround - // We can't serialize CubemapInfo inside a CubemapInfo, so before serializing we will 'flatten' the shadow cubemap in a new list and save index into this list. - // THis also allow to manage case of sahdow cubemap without matching HDRI in the main list. - public int serialIndexMain; - public int serialIndexShadow; - - [NonSerialized] - public bool alreadyComputed; // this is not serialized because SH are not serialized so we need to compute them again after deserialization - } - - internal class LookDevResources - { - static public SphericalHarmonicsL2 m_ZeroAmbientProbe; - static public Material m_SkyboxMaterial = null; - static public Material m_GBufferPatchMaterial = null; - static public Material m_DrawBallsMaterial = null; - static public Mesh m_ScreenQuadMesh = null; - static public Material m_LookDevCompositing = null; - static public Material m_DeferredOverlayMaterial = null; - static public Cubemap m_DefaultHDRI = null; - static public Material m_LookDevCubeToLatlong = null; - static public RenderTexture m_SelectionTexture = null; - static public RenderTexture m_BrightestPointRT = null; - static public Texture2D m_BrightestPointTexture = null; - - static public void Initialize() - { - m_ZeroAmbientProbe.Clear(); - - // For some reason, a few frames after LoadRenderDoc reset the gfx device, the pointers turn null. Is there a better way to handle that? - if (m_SkyboxMaterial == null) - m_SkyboxMaterial = new Material(Shader.Find("Skybox/Cubemap")); - - if (m_ScreenQuadMesh == null) - { - // Draw a full screen quad with GBuffer patch material - m_ScreenQuadMesh = new Mesh(); - m_ScreenQuadMesh.vertices = new Vector3[] - { - // Note: Invert Z or not should not have influence here. - new Vector3(-1, -1, 0), - new Vector3(1, 1, 0), - new Vector3(1, -1, 0), - new Vector3(-1, 1, 0) - }; - - m_ScreenQuadMesh.triangles = new int[] - { - 0, 1, 2, 1, 0, 3 - }; - } - - // Material can be null if we switch API device or when we init the first time. We can safely re-allocate everything if this is null - if (m_GBufferPatchMaterial == null) - { - m_GBufferPatchMaterial = new Material(EditorGUIUtility.LoadRequired("LookDevView/GBufferWhitePatch.shader") as Shader); - m_DrawBallsMaterial = new Material(EditorGUIUtility.LoadRequired("LookDevView/GBufferBalls.shader") as Shader); - } - - if (m_LookDevCompositing == null) - m_LookDevCompositing = new Material(EditorGUIUtility.LoadRequired("LookDevView/LookDevCompositing.shader") as Shader); - - if (m_DeferredOverlayMaterial == null) - m_DeferredOverlayMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewDeferredMaterial.mat") as Material; - - if (m_DefaultHDRI == null) - { - m_DefaultHDRI = EditorGUIUtility.Load("LookDevView/DefaultHDRI.exr") as Cubemap; - if (m_DefaultHDRI == null) - { - m_DefaultHDRI = EditorGUIUtility.Load("LookDevView/DefaultHDRI.asset") as Cubemap; - } - } - - if (m_LookDevCubeToLatlong == null) - { - m_LookDevCubeToLatlong = new Material(EditorGUIUtility.LoadRequired("LookDevView/LookDevCubeToLatlong.shader") as Shader); - } - - /* - // Debug code to remove - bool tutu = false; - if (tutu) - { - Shader devShader = Shader.Find("Custom/DevShader2") as Shader; - if (devShader != null) - m_LookDevCubeToLatlong = new Material(devShader); - } - */ - - - if (m_SelectionTexture == null) - m_SelectionTexture = new RenderTexture((int)LookDevEnvironmentWindow.m_HDRIWidth, (int)LookDevEnvironmentWindow.m_latLongHeight, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default); - - if (m_BrightestPointRT == null) - m_BrightestPointRT = new RenderTexture((int)LookDevEnvironmentWindow.m_HDRIWidth, (int)LookDevEnvironmentWindow.m_latLongHeight, 0, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Default); - - if (m_BrightestPointTexture == null) - m_BrightestPointTexture = new Texture2D((int)LookDevEnvironmentWindow.m_HDRIWidth, (int)LookDevEnvironmentWindow.m_latLongHeight, TextureFormat.RGBAHalf, false); - } - - static public void Cleanup() - { - m_SkyboxMaterial = null; - - if (m_LookDevCompositing) - { - UnityEngine.Object.DestroyImmediate(m_LookDevCompositing); - m_LookDevCompositing = null; - } - } - - // Find brightest spot of the cubemap - static public void UpdateShadowInfoWithBrightestSpot(CubemapInfo cubemapInfo) - { - m_LookDevCubeToLatlong.SetTexture("_MainTex", cubemapInfo.cubemap); - m_LookDevCubeToLatlong.SetVector("_WindowParams", new Vector4(10000, -1000.0f, 2, 0.0f)); // Neutral value to not clip - m_LookDevCubeToLatlong.SetVector("_CubeToLatLongParams", new Vector4(Mathf.Deg2Rad * cubemapInfo.angleOffset, 0.5f, 1.0f, 3.0f)); // We use LOD 3 to take a region rather than a single pixel in the map - m_LookDevCubeToLatlong.SetPass(0); - - int width = (int)LookDevEnvironmentWindow.m_HDRIWidth; - int height = (int)LookDevEnvironmentWindow.m_latLongHeight; - - // Convert cubemap to a 2D LatLong to read on CPU - Graphics.Blit(cubemapInfo.cubemap, m_BrightestPointRT, m_LookDevCubeToLatlong); - m_BrightestPointTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0, false); - m_BrightestPointTexture.Apply(); - - // CPU read back - // From Doc: The returned array is a flattened 2D array, where pixels are laid out left to right, bottom to top (i.e. row after row) - Color[] color = m_BrightestPointTexture.GetPixels(); - - float maxLum = 0.0f; - for (int y = 0; y < height; ++y) - { - for (int x = 0; x < width; ++x) - { - Vector3 rgb = new Vector3(color[y * width + x].r, color[y * width + x].g, color[y * width + x].b); - - float lum = rgb.x * 0.2126729f + rgb.y * 0.7151522f + rgb.z * 0.0721750f; - - if (maxLum < lum) - { - Vector2 vec = LookDevEnvironmentWindow.PositionToLatLong(new Vector2(((float)x / (float)(width - 1)) * 2.0f - 1.0f, ((float)y / (float)(height - 1)) * 2.0f - 1.0f)); - cubemapInfo.shadowInfo.latitude = vec.x; - cubemapInfo.shadowInfo.longitude = vec.y - cubemapInfo.angleOffset; - - maxLum = lum; - } - } - } - } - } -} diff --git a/Editor/Mono/LookDevView/LookDevSettingsWindow.cs b/Editor/Mono/LookDevView/LookDevSettingsWindow.cs deleted file mode 100644 index 959801e206..0000000000 --- a/Editor/Mono/LookDevView/LookDevSettingsWindow.cs +++ /dev/null @@ -1,278 +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 Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class LookDevSettingsWindow - : PopupWindowContent - { - public class Styles - { - public readonly GUIStyle sMenuItem = "MenuItem"; - public readonly GUIStyle sSeparator = "sv_iconselector_sep"; - - public readonly GUIContent sTitle = EditorGUIUtility.TrTextContent("Settings"); - public readonly GUIContent sMultiView = EditorGUIUtility.TrTextContent("Multi-view"); - public readonly GUIContent sCamera = EditorGUIUtility.TrTextContent("Camera"); - public readonly GUIContent sLighting = EditorGUIUtility.TrTextContent("Lighting"); - public readonly GUIContent sAnimation = EditorGUIUtility.TrTextContent("Animation"); - public readonly GUIContent sViewport = EditorGUIUtility.TrTextContent("Viewport"); - public readonly GUIContent sEnvLibrary = EditorGUIUtility.TrTextContent("Environment Library"); - public readonly GUIContent sMisc = EditorGUIUtility.TrTextContent("Misc"); - - public readonly GUIContent sResetCamera = EditorGUIUtility.TrTextContent("Fit View F"); - public readonly GUIContent sCreateNewLibrary = EditorGUIUtility.TrTextContent("Save as new library"); - public readonly GUIContent sSaveCurrentLibrary = EditorGUIUtility.TrTextContent("Save current library"); - public readonly GUIContent sResetView = EditorGUIUtility.TrTextContent("Reset View"); - public readonly GUIContent sEnableToneMap = EditorGUIUtility.TrTextContent("Enable Tone Mapping"); - public readonly GUIContent sEnableAutoExp = EditorGUIUtility.TrTextContent("Enable Auto Exposure"); - public readonly GUIContent sExposureRange = EditorGUIUtility.TrTextContent("Exposure Range"); - public readonly GUIContent sEnableShadows = EditorGUIUtility.TrTextContent("Enable Shadows"); - public readonly GUIContent sShadowDistance = EditorGUIUtility.TrTextContent("Shadow distance"); - public readonly GUIContent sShowBalls = EditorGUIUtility.TrTextContent("Show Chrome/grey balls"); - public readonly GUIContent sShowControlWindows = EditorGUIUtility.TrTextContent("Show Controls"); - public readonly GUIContent sAllowDifferentObjects = EditorGUIUtility.TrTextContent("Allow Different Objects"); - public readonly GUIContent sResyncObjects = EditorGUIUtility.TrTextContent("Resynchronize Objects"); - public readonly GUIContent sRotateObjectMode = EditorGUIUtility.TrTextContent("Rotate Objects"); - public readonly GUIContent sObjRotationSpeed = EditorGUIUtility.TrTextContent("Rotate Objects speed"); - public readonly GUIContent sRotateEnvMode = EditorGUIUtility.TrTextContent("Rotate environment"); - public readonly GUIContent sEnvRotationSpeed = EditorGUIUtility.TrTextContent("Rotate Env. speed"); - public readonly GUIContent sEnableShadowIcon = EditorGUIUtility.TrIconContent("LookDevShadow", "Toggles shadows on and off"); - public readonly GUIContent sEnableObjRotationIcon = EditorGUIUtility.IconContent("LookDevObjRotation", "ObjRotation|Toggles object rotation (turntable) on and off"); - public readonly GUIContent sEnableEnvRotationIcon = EditorGUIUtility.TrIconContent("LookDevEnvRotation", "Toggles environment rotation on and off"); - public readonly Texture sEnableShadowTexture = EditorGUIUtility.FindTexture("LookDevShadow"); - public readonly Texture sEnableObjRotationTexture = EditorGUIUtility.FindTexture("LookDevObjRotation"); - public readonly Texture sEnableEnvRotationTexture = EditorGUIUtility.FindTexture("LookDevEnvRotation"); - - public readonly GUIContent[] sMultiViewMode = - { - EditorGUIUtility.TrTextContent("Single1"), - EditorGUIUtility.TrTextContent("Single2"), - EditorGUIUtility.TrTextContent("Side by side"), - EditorGUIUtility.TrTextContent("Split-screen"), - EditorGUIUtility.TrTextContent("Zone"), - }; - - - public readonly Texture[] sMultiViewTextures = - { - EditorGUIUtility.FindTexture("LookDevSingle1"), - EditorGUIUtility.FindTexture("LookDevSingle2"), - EditorGUIUtility.FindTexture("LookDevSideBySide"), - EditorGUIUtility.FindTexture("LookDevSplit"), - EditorGUIUtility.FindTexture("LookDevZone"), - }; - } - - static Styles s_Styles = null; - public static Styles styles { get { if (s_Styles == null) s_Styles = new Styles(); return s_Styles; } } - - // This enum is only to calculate the size of the windows for settings. - // Below are listed the number of label, separator, checkbox, button and slider use in the menu. - // Keep in sync with the code below that generate the menu to have a correct windows size. - enum UINumElement - { - UINumDrawHeader = 6, - UINumToggle = (int)LookDevMode.Count + 7, - UINumSlider = 4, - UINumSeparator = 7, - UINumButton = 6, - - UITotalElement = UINumDrawHeader + UINumToggle + UINumSlider + UINumSeparator + UINumButton - } - - readonly float m_WindowHeight = (int)(UINumElement.UITotalElement) * EditorGUI.kSingleLineHeight; - const float m_WindowWidth = 180; - - const float kIconSize = 16.0f; - const float kIconHorizontalPadding = 3.0f; - - readonly LookDevView m_LookDevView; - - public LookDevSettingsWindow(LookDevView lookDevView) - { - m_LookDevView = lookDevView; - } - - public override Vector2 GetWindowSize() - { - return new Vector2(m_WindowWidth, m_WindowHeight); - } - - public override void OnGUI(Rect rect) - { - if (m_LookDevView == null) - return; - - GUILayout.BeginVertical(); - { - // We need to have a sufficient size to display negative float number - EditorGUIUtility.labelWidth = 130; - EditorGUIUtility.fieldWidth = 35; - - // Look Dev view mode - DrawHeader(styles.sMultiView); - - for (int i = 0; i < (int)LookDevMode.Count; ++i) - { - EditorGUI.BeginChangeCheck(); - bool value = GUILayout.Toggle(m_LookDevView.config.lookDevMode == (LookDevMode)i, styles.sMultiViewMode[i], styles.sMenuItem); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.UpdateLookDevModeToggle((LookDevMode)i, value); - m_LookDevView.Repaint(); - GUIUtility.ExitGUI(); - } - } - - // Camera settings - DrawSeparator(); - DrawHeader(styles.sCamera); - - if (GUILayout.Button(styles.sResetCamera, styles.sMenuItem)) - { - m_LookDevView.Frame(); - } - - m_LookDevView.config.enableToneMap = GUILayout.Toggle(m_LookDevView.config.enableToneMap, styles.sEnableToneMap, styles.sMenuItem); - EditorGUI.BeginChangeCheck(); - // Cast to int to have integer step - float newExposureRange = (float)EditorGUILayout.IntSlider(styles.sExposureRange, (int)m_LookDevView.config.exposureRange, 1, 32); - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(m_LookDevView.config, "Change exposure range"); - m_LookDevView.config.exposureRange = newExposureRange; - } - - DrawSeparator(); - DrawHeader(styles.sLighting); - - EditorGUI.BeginChangeCheck(); - - GUILayout.BeginHorizontal(); - m_LookDevView.config.enableShadowCubemap = GUILayout.Toggle(m_LookDevView.config.enableShadowCubemap, styles.sEnableShadows, styles.sMenuItem); - GUILayout.EndHorizontal(); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.Repaint(); - } - - EditorGUI.BeginChangeCheck(); - float newShadowDistance = EditorGUILayout.Slider(styles.sShadowDistance, m_LookDevView.config.shadowDistance, 0.0f, 1000.0f); - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(m_LookDevView.config, "Change shadow distance"); - m_LookDevView.config.shadowDistance = newShadowDistance; - } - - DrawSeparator(); - DrawHeader(styles.sAnimation); - - GUILayout.BeginHorizontal(); - m_LookDevView.config.rotateObjectMode = GUILayout.Toggle(m_LookDevView.config.rotateObjectMode, styles.sRotateObjectMode, styles.sMenuItem); - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(); - m_LookDevView.config.rotateEnvMode = GUILayout.Toggle(m_LookDevView.config.rotateEnvMode, styles.sRotateEnvMode, styles.sMenuItem); - GUILayout.EndHorizontal(); - - EditorGUI.BeginChangeCheck(); - float newObjRotationSpeed = EditorGUILayout.Slider(styles.sObjRotationSpeed, m_LookDevView.config.objRotationSpeed, -5.0f, 5.0f); - - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(m_LookDevView.config, "Change rotation speed"); - m_LookDevView.config.objRotationSpeed = newObjRotationSpeed; - } - - EditorGUI.BeginChangeCheck(); - float newEnvRotationSpeed = EditorGUILayout.Slider(styles.sEnvRotationSpeed, m_LookDevView.config.envRotationSpeed, -5.0f, 5.0f); - if (EditorGUI.EndChangeCheck()) - { - Undo.RecordObject(m_LookDevView.config, "Change env speed"); - m_LookDevView.config.envRotationSpeed = newEnvRotationSpeed; - } - - DrawSeparator(); - DrawHeader(styles.sViewport); - if (GUILayout.Button(styles.sResetView, styles.sMenuItem)) - { - m_LookDevView.ResetView(); - } - - DrawSeparator(); - DrawHeader(styles.sEnvLibrary); - using (new EditorGUI.DisabledScope(!m_LookDevView.envLibrary.dirty)) - { - if (GUILayout.Button(styles.sSaveCurrentLibrary, styles.sMenuItem)) - { - editorWindow.Close(); - if (m_LookDevView.SaveLookDevLibrary()) - m_LookDevView.envLibrary.dirty = false; - GUIUtility.ExitGUI(); - } - } - if (GUILayout.Button(styles.sCreateNewLibrary, styles.sMenuItem)) - { - editorWindow.Close(); - string assetPath = EditorUtility.SaveFilePanelInProject("Save New Environment Library", "New Env Library", "asset", ""); - if (!string.IsNullOrEmpty(assetPath)) - { - m_LookDevView.CreateNewLibrary(assetPath); - } - - GUIUtility.ExitGUI(); - } - EditorGUI.BeginChangeCheck(); - LookDevEnvironmentLibrary library = EditorGUILayout.ObjectField(m_LookDevView.userEnvLibrary, typeof(LookDevEnvironmentLibrary), false) as LookDevEnvironmentLibrary; - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.envLibrary = library; - } - - DrawSeparator(); - DrawHeader(styles.sMisc); - m_LookDevView.config.showBalls = GUILayout.Toggle(m_LookDevView.config.showBalls, styles.sShowBalls, styles.sMenuItem); - m_LookDevView.config.showControlWindows = GUILayout.Toggle(m_LookDevView.config.showControlWindows, styles.sShowControlWindows, styles.sMenuItem); - EditorGUI.BeginChangeCheck(); - bool allowDifferentObjects = GUILayout.Toggle(m_LookDevView.config.allowDifferentObjects, styles.sAllowDifferentObjects, styles.sMenuItem); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.allowDifferentObjects = allowDifferentObjects; - } - if (GUILayout.Button(styles.sResyncObjects, styles.sMenuItem)) - { - m_LookDevView.config.ResynchronizeObjects(); - } - } - GUILayout.EndVertical(); - - // Use mouse move so we get hover state correctly in the menu item rows - if (Event.current.type == EventType.MouseMove) - Event.current.Use(); - - // Escape closes the window - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) - { - editorWindow.Close(); - GUIUtility.ExitGUI(); - } - } - - private void DrawSeparator() - { - GUILayout.Space(3.0f); - GUILayout.Label(GUIContent.none, styles.sSeparator); - } - - private void DrawHeader(GUIContent label) - { - GUILayout.Label(label, EditorStyles.miniLabel); - } - } -} diff --git a/Editor/Mono/LookDevView/LookDevView.cs b/Editor/Mono/LookDevView/LookDevView.cs index ceadf35366..4709caf02b 100644 --- a/Editor/Mono/LookDevView/LookDevView.cs +++ b/Editor/Mono/LookDevView/LookDevView.cs @@ -1676,7 +1676,7 @@ private void HandleDragging() } GameObject go = o as GameObject; - if (go && EditorUtility.IsPersistent(go) && PrefabUtility.GetPrefabObject(go) != null) + if (go && EditorUtility.IsPersistent(go) && PrefabUtility.IsPartOfPrefabAsset(go)) { if (GameObjectInspector.HasRenderableParts(go)) { diff --git a/Editor/Mono/LookDevView/LookDevViewsWindow.cs b/Editor/Mono/LookDevView/LookDevViewsWindow.cs deleted file mode 100644 index 3a80ef6856..0000000000 --- a/Editor/Mono/LookDevView/LookDevViewsWindow.cs +++ /dev/null @@ -1,284 +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 Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class LookDevViewsWindow - : PopupWindowContent - { - public class Styles - { - public readonly GUIStyle sMenuItem = "MenuItem"; - public readonly GUIStyle sHeaderStyle = EditorStyles.miniLabel; - public readonly GUIStyle sToolBarButton = "toolbarbutton"; - - public readonly GUIContent sTitle = EditorGUIUtility.TrTextContent("Views"); - public readonly GUIContent sExposure = EditorGUIUtility.TrTextContent("EV", "Exposure value: control the brightness of the environment."); - public readonly GUIContent sEnvironment = EditorGUIUtility.TrTextContent("Environment", "Select an environment from the list of currently available environments"); - public readonly GUIContent sRotation = EditorGUIUtility.TrTextContent("Rotation", "Change the rotation of the environment"); - public readonly GUIContent sZero = EditorGUIUtility.TextContent("0"); - public readonly GUIContent sLoD = EditorGUIUtility.TrTextContent("LoD", "Choose displayed LoD"); - public readonly GUIContent sLoDAuto = EditorGUIUtility.TrTextContent("LoD (auto)", "Choose displayed LoD"); - public readonly GUIContent sShadingMode = EditorGUIUtility.TrTextContent("Shading", "Select shading mode"); - - public readonly GUIContent[] sViewTitle = - { - EditorGUIUtility.TrTextContent("Main View (1)"), - EditorGUIUtility.TrTextContent("Second View (2)"), - }; - - public readonly GUIStyle[] sViewTitleStyles = - { - new GUIStyle(EditorStyles.miniLabel), - new GUIStyle(EditorStyles.miniLabel) - }; - - public readonly string[] sShadingModeStrings = { "Shaded", "Shaded Wireframe", "Albedo", "Specular", "Smoothness", "Normal" }; - public readonly int[] sShadingModeValues = { (int)DrawCameraMode.Normal, (int)DrawCameraMode.TexturedWire, (int)DrawCameraMode.DeferredDiffuse, (int)DrawCameraMode.DeferredSpecular, (int)DrawCameraMode.DeferredSmoothness, (int)DrawCameraMode.DeferredNormal }; - - public readonly GUIContent sLinkActive = EditorGUIUtility.TrIconContent("LookDevMirrorViewsActive", "Links the property between the different views"); - public readonly GUIContent sLinkInactive = EditorGUIUtility.TrIconContent("LookDevMirrorViewsInactive", "Links the property between the different views"); - - - public Styles() - { - sViewTitleStyles[0].normal.textColor = LookDevView.m_FirstViewGizmoColor; - sViewTitleStyles[1].normal.textColor = LookDevView.m_SecondViewGizmoColor; - } - } - - GUIContent GetGUIContentLink(bool active) - { - return active ? styles.sLinkActive : styles.sLinkInactive; - } - - static Styles s_Styles = new Styles(); - public static Styles styles { get { return s_Styles; } } - - static float kIconSize = 32; - static float kLabelWidth = 120.0f; - static float kSliderWidth = 100.0f; - static float kSliderFieldWidth = 30.0f; - static float kSliderFieldPadding = 5.0f; - static float kLineHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; - - float m_WindowHeight = 5 * kLineHeight + EditorGUIUtility.standardVerticalSpacing; - float m_WindowWidth = kLabelWidth + kSliderWidth + kSliderFieldWidth + kSliderFieldPadding + 5.0f; - - - private readonly LookDevView m_LookDevView; - - public LookDevViewsWindow(LookDevView lookDevView) - { - m_LookDevView = lookDevView; - } - - private bool NeedLoD() - { - return m_LookDevView.config.GetObjectLoDCount(LookDevEditionContext.Left) > 1 || m_LookDevView.config.GetObjectLoDCount(LookDevEditionContext.Right) > 1; - } - - private float GetHeight() - { - float height = m_WindowHeight; - if (NeedLoD()) - { - height += kLineHeight; - } - - return height; - } - - public override Vector2 GetWindowSize() - { - float width = m_WindowWidth + ((m_LookDevView.config.lookDevMode == LookDevMode.Single1 || m_LookDevView.config.lookDevMode == LookDevMode.Single2) ? 0 : (m_WindowWidth + kIconSize)); - return new Vector2(width, GetHeight()); - } - - public override void OnGUI(Rect rect) - { - if (m_LookDevView.config == null) - return; - - Rect drawPos = new Rect(0, 0, rect.width, GetHeight()); - - DrawOneView(drawPos, (m_LookDevView.config.lookDevMode == LookDevMode.Single2) ? LookDevEditionContext.Right : LookDevEditionContext.Left); - - drawPos.x += m_WindowWidth; - - drawPos.x += kIconSize; - DrawOneView(drawPos, LookDevEditionContext.Right); - - // Use mouse move so we get hover state correctly in the menu item rows - if (Event.current.type == EventType.MouseMove) - Event.current.Use(); - - // Escape closes the window - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) - { - editorWindow.Close(); - GUIUtility.ExitGUI(); - } - } - - private void DrawOneView(Rect drawPos, LookDevEditionContext context) - { - int i = (int)context; - bool drawLinks = ((m_LookDevView.config.lookDevMode != LookDevMode.Single1) && (context == LookDevEditionContext.Left)) || ((m_LookDevView.config.lookDevMode != LookDevMode.Single2) && (context == LookDevEditionContext.Right)); - - GUILayout.BeginArea(drawPos); - - GUILayout.Label(styles.sViewTitle[i], styles.sViewTitleStyles[i]); - - GUILayout.BeginHorizontal(); - { - GUILayout.BeginVertical(GUILayout.Width(m_WindowWidth)); - { - GUILayout.BeginHorizontal(GUILayout.Height(kLineHeight)); - { - GUILayout.Label(styles.sExposure, styles.sMenuItem, GUILayout.Width(kLabelWidth)); - - float fExposureValue = m_LookDevView.config.GetFloatProperty(LookDevProperty.ExposureValue, context); - EditorGUI.BeginChangeCheck(); - float roundedExposureRange = Mathf.Round(m_LookDevView.config.exposureRange); - fExposureValue = Mathf.Clamp(GUILayout.HorizontalSlider(fExposureValue, -roundedExposureRange, roundedExposureRange, GUILayout.Width(kSliderWidth)), -roundedExposureRange, roundedExposureRange); // Clamp is here to return value to the right range if the user decrease the exposure range - // Display in the float field is rounded for display. To 1 decimal in case of negative number to account for the '-' character. - fExposureValue = Mathf.Clamp(EditorGUILayout.FloatField((float)Math.Round(fExposureValue, fExposureValue < 0.0f ? 1 : 2), GUILayout.Width(kSliderFieldWidth)), -roundedExposureRange, roundedExposureRange); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.UpdateFocus(context); - m_LookDevView.config.UpdateFloatProperty(LookDevProperty.ExposureValue, fExposureValue); - } - } - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(GUILayout.Height(kLineHeight)); - { - int iHDRIIndex = -1; - int iHDRICount = m_LookDevView.envLibrary.hdriCount; - - using (new EditorGUI.DisabledScope(iHDRICount <= 1)) - { - GUILayout.Label(styles.sEnvironment, styles.sMenuItem, GUILayout.Width(kLabelWidth)); - - if (iHDRICount > 1) - { - int maxHDRIIndex = iHDRICount - 1; - iHDRIIndex = m_LookDevView.config.GetIntProperty(LookDevProperty.HDRI, context); - EditorGUI.BeginChangeCheck(); - iHDRIIndex = (int)GUILayout.HorizontalSlider(iHDRIIndex, 0.0f, (float)maxHDRIIndex, GUILayout.Width(kSliderWidth)); - iHDRIIndex = Mathf.Clamp(EditorGUILayout.IntField(iHDRIIndex, GUILayout.Width(kSliderFieldWidth)), 0, maxHDRIIndex); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.UpdateFocus(context); - m_LookDevView.config.UpdateIntProperty(LookDevProperty.HDRI, iHDRIIndex); - } - } - else - { - GUILayout.HorizontalSlider(0.0f, 0.0f, 0.0f, GUILayout.Width(kSliderWidth)); - GUILayout.Label(styles.sZero, styles.sMenuItem); - } - } - } - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(GUILayout.Height(kLineHeight)); - { - GUILayout.Label(styles.sShadingMode, styles.sMenuItem, GUILayout.Width(kLabelWidth)); - - int shadingMode = m_LookDevView.config.GetIntProperty(LookDevProperty.ShadingMode, context); - EditorGUI.BeginChangeCheck(); - shadingMode = EditorGUILayout.IntPopup("", shadingMode, styles.sShadingModeStrings, styles.sShadingModeValues, GUILayout.Width(kSliderFieldWidth + kSliderWidth + 4.0f)); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.UpdateFocus(context); - m_LookDevView.config.UpdateIntProperty(LookDevProperty.ShadingMode, shadingMode); - } - } - GUILayout.EndHorizontal(); - - GUILayout.BeginHorizontal(GUILayout.Height(kLineHeight)); - { - GUILayout.Label(styles.sRotation, styles.sMenuItem, GUILayout.Width(kLabelWidth)); - - float envRotation = m_LookDevView.config.GetFloatProperty(LookDevProperty.EnvRotation, context); - EditorGUI.BeginChangeCheck(); - envRotation = GUILayout.HorizontalSlider(envRotation, 0.0f, 720.0f, GUILayout.Width(kSliderWidth)); - envRotation = Mathf.Clamp(EditorGUILayout.FloatField((float)Math.Round(envRotation, 0), GUILayout.Width(kSliderFieldWidth)), 0.0f, 720.0f); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.UpdateFocus(context); - m_LookDevView.config.UpdateFloatProperty(LookDevProperty.EnvRotation, envRotation); - } - } - GUILayout.EndHorizontal(); - - if (NeedLoD()) - { - GUILayout.BeginHorizontal(GUILayout.Height(kLineHeight)); - { - if (m_LookDevView.config.GetObjectLoDCount(context) > 1) - { - int lodIndex = m_LookDevView.config.GetIntProperty(LookDevProperty.LoDIndex, context); - - GUILayout.Label(lodIndex == -1 ? styles.sLoDAuto : styles.sLoD, styles.sMenuItem, GUILayout.Width(kLabelWidth)); - - EditorGUI.BeginChangeCheck(); - - int maxLoDIndex = m_LookDevView.config.GetObjectLoDCount(context) - 1; - - // We need a specific handling here in case of linked property, because even if it is linked the two meshes can have different number of LOD - // We handle that by taking the min of the number of mesh if the property is link - if ((m_LookDevView.config.lookDevMode != LookDevMode.Single1 && m_LookDevView.config.lookDevMode != LookDevMode.Single2) && m_LookDevView.config.IsPropertyLinked(LookDevProperty.LoDIndex)) - { - maxLoDIndex = Math.Min(m_LookDevView.config.GetObjectLoDCount(LookDevEditionContext.Left), m_LookDevView.config.GetObjectLoDCount(LookDevEditionContext.Right)) - 1; - } - - lodIndex = Mathf.Clamp(lodIndex, -1, maxLoDIndex); - - lodIndex = (int)GUILayout.HorizontalSlider(lodIndex, -1, maxLoDIndex, GUILayout.Width(kSliderWidth)); - lodIndex = EditorGUILayout.IntField(lodIndex, GUILayout.Width(kSliderFieldWidth)); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.UpdateFocus(context); - m_LookDevView.config.UpdateIntProperty(LookDevProperty.LoDIndex, lodIndex); - } - } - } - GUILayout.EndHorizontal(); - } - } - GUILayout.EndVertical(); - - if (drawLinks) - { - GUILayout.BeginVertical(GUILayout.Width(kIconSize)); - { - LookDevProperty[] properties = { LookDevProperty.ExposureValue, LookDevProperty.HDRI, LookDevProperty.ShadingMode, LookDevProperty.EnvRotation, LookDevProperty.LoDIndex }; - int propertyCount = 4 + (NeedLoD() ? 1 : 0); - for (int propertyIndex = 0; propertyIndex < propertyCount; ++propertyIndex) - { - bool linked = false; - EditorGUI.BeginChangeCheck(); - bool isLink = m_LookDevView.config.IsPropertyLinked(properties[propertyIndex]); - linked = GUILayout.Toggle(isLink, GetGUIContentLink(isLink), styles.sToolBarButton, GUILayout.Height(kLineHeight)); - if (EditorGUI.EndChangeCheck()) - { - m_LookDevView.config.UpdatePropertyLink(properties[propertyIndex], linked); - } - } - } - GUILayout.EndVertical(); - } - } - GUILayout.EndHorizontal(); - GUILayout.EndArea(); - } - } -} diff --git a/Editor/Mono/MaterialProperty.cs b/Editor/Mono/MaterialProperty.cs deleted file mode 100644 index 65abf1352c..0000000000 --- a/Editor/Mono/MaterialProperty.cs +++ /dev/null @@ -1,229 +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.Runtime.InteropServices; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - // match MonoMaterialProperty layout! - [StructLayout(LayoutKind.Sequential)] - public sealed class MaterialProperty - { - public enum PropType - { - Color, - Vector, - Float, - Range, - Texture, - } - - [Obsolete("Use UnityEngine.Rendering.TextureDimension instead", false)] - public enum TexDim - { - Unknown = -1, - None = 0, - Tex2D = 2, - Tex3D = 3, - Cube = 4, - Any = 6, - } - - [Flags] - public enum PropFlags - { - None = 0, - HideInInspector = (1 << 0), - PerRendererData = (1 << 1), - NoScaleOffset = (1 << 2), - Normal = (1 << 3), - HDR = (1 << 4), - Gamma = (1 << 5), - NonModifiableTextureData = (1 << 6), - } - - public delegate bool ApplyPropertyCallback(MaterialProperty prop, int changeMask, object previousValue); - - private Object[] m_Targets; - private ApplyPropertyCallback m_ApplyPropertyCallback; - private string m_Name; - private string m_DisplayName; - private System.Object m_Value; - private Vector4 m_TextureScaleAndOffset; - private Vector2 m_RangeLimits; - private PropType m_Type; - private PropFlags m_Flags; - private UnityEngine.Rendering.TextureDimension m_TextureDimension; - private int m_MixedValueMask; - - - public Object[] targets { get { return m_Targets; } } - public PropType type { get { return m_Type; } } - public string name { get { return m_Name; } } - public string displayName { get { return m_DisplayName; } } - public PropFlags flags { get { return m_Flags; } } - public UnityEngine.Rendering.TextureDimension textureDimension { get { return m_TextureDimension; } } - public Vector2 rangeLimits { get { return m_RangeLimits; } } - public bool hasMixedValue { get { return (m_MixedValueMask & 1) != 0; } } - public ApplyPropertyCallback applyPropertyCallback { get { return m_ApplyPropertyCallback; } set { m_ApplyPropertyCallback = value; } } - - // Textures have 5 different mixed values for texture + UV scale/offset - internal int mixedValueMask { get { return m_MixedValueMask; } } - - public void ReadFromMaterialPropertyBlock(MaterialPropertyBlock block) - { - ShaderUtil.ApplyMaterialPropertyBlockToMaterialProperty(block, this); - } - - public void WriteToMaterialPropertyBlock(MaterialPropertyBlock materialblock, int changedPropertyMask) - { - ShaderUtil.ApplyMaterialPropertyToMaterialPropertyBlock(this, changedPropertyMask, materialblock); - } - - public Color colorValue - { - get - { - if (m_Type == PropType.Color) - return (Color)m_Value; - return Color.black; - } - set - { - if (m_Type != PropType.Color) - return; - if (!hasMixedValue && value == (Color)m_Value) - return; - - ApplyProperty(value); - } - } - - public Vector4 vectorValue - { - get - { - if (m_Type == PropType.Vector) - return (Vector4)m_Value; - return Vector4.zero; - } - set - { - if (m_Type != PropType.Vector) - return; - if (!hasMixedValue && value == (Vector4)m_Value) - return; - - ApplyProperty(value); - } - } - - internal static bool IsTextureOffsetAndScaleChangedMask(int changedMask) - { - changedMask >>= 1; - return changedMask != 0; - } - - public float floatValue - { - get - { - if (m_Type == PropType.Float || m_Type == PropType.Range) - return (float)m_Value; - return 0.0f; - } - set - { - if (m_Type != PropType.Float && m_Type != PropType.Range) - return; - if (!hasMixedValue && value == (float)m_Value) - return; - - ApplyProperty(value); - } - } - - public Texture textureValue - { - get - { - if (m_Type == PropType.Texture) - return (Texture)m_Value; - return null; - } - set - { - if (m_Type != PropType.Texture) - return; - if (!hasMixedValue && value == (Texture)m_Value) - return; - - m_MixedValueMask &= ~1; - object previousValue = m_Value; - m_Value = value; - - ApplyProperty(previousValue, 1); - } - } - - public Vector4 textureScaleAndOffset - { - get - { - if (m_Type == PropType.Texture) - return m_TextureScaleAndOffset; - return Vector4.zero; - } - set - { - if (m_Type != PropType.Texture) - return; - if (!hasMixedValue && value == m_TextureScaleAndOffset) - return; - - m_MixedValueMask &= 1; - int changedMask = 0; - for (int c = 1; c < 5; c++) - changedMask |= 1 << c; - - object previousValue = m_TextureScaleAndOffset; - m_TextureScaleAndOffset = value; - ApplyProperty(previousValue, changedMask); - } - } - - private void ApplyProperty(object newValue) - { - m_MixedValueMask = 0; - object previousValue = m_Value; - m_Value = newValue; - ApplyProperty(previousValue, 1); - } - - private void ApplyProperty(object previousValue, int changedPropertyMask) - { - if (targets == null || targets.Length == 0) - throw new ArgumentException("No material targets provided"); - - Object[] mats = targets; - string targetTitle; - if (mats.Length == 1) - targetTitle = mats[0].name; - else - targetTitle = mats.Length + " " + ObjectNames.NicifyVariableName(ObjectNames.GetClassName(mats[0])) + "s"; - - //@TODO: Maybe all this logic should be moved to C++ - // reduces api surface... - bool didApply = false; - if (m_ApplyPropertyCallback != null) - didApply = m_ApplyPropertyCallback(this, changedPropertyMask, previousValue); - - if (!didApply) - ShaderUtil.ApplyProperty(this, changedPropertyMask, "Modify " + displayName + " of " + targetTitle); - } - } -} // namespace UnityEngine.Rendering diff --git a/Editor/Mono/Menu.bindings.cs b/Editor/Mono/Menu.bindings.cs index aaa3b83298..c8cbee328f 100644 --- a/Editor/Mono/Menu.bindings.cs +++ b/Editor/Mono/Menu.bindings.cs @@ -16,10 +16,13 @@ public sealed class Menu [NativeMethod("MenuController::GetChecked", true)] public static extern bool GetChecked(string menuPath); - [FreeFunction("MenuController::GetMenuItemShortcuts")] - internal static extern void GetMenuItemShortcuts(List outItemNames, List outItemShortcuts); + [FreeFunction("MenuController::GetMenuItemDefaultShortcuts")] + internal static extern void GetMenuItemDefaultShortcuts(List outItemNames, List outItemDefaultShortcuts); [FreeFunction("MenuController::SetMenuItemHotkey")] internal static extern void SetHotkey(string menuPath, string hotkey); + + [FreeFunction("MenuController::ExtractSubmenus")] + internal static extern string[] ExtractSubmenus(string menuPath); } } diff --git a/Editor/Mono/MenuCommand.cs b/Editor/Mono/MenuCommand.cs deleted file mode 100644 index c7c2b8eb6d..0000000000 --- a/Editor/Mono/MenuCommand.cs +++ /dev/null @@ -1,29 +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.Runtime.InteropServices; -using UnityEngine; -using UnityEngine.Scripting; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - // Used to extract the context for a [[MenuItem]]. MenuCommand objects are passed to custom menu item functions defined using the [[MenuItem]] attribute. - // Keep in sync with MenuCommandBinding in Runtime\Scripting\ManagedAttributeManager.h - [StructLayout(LayoutKind.Sequential)] - [RequiredByNativeCode] - public sealed class MenuCommand - { - // Context is the object that is the target of a menu command. - public Object context; - // An integer for passing custom information to a menu item. - public int userData; - - // Creates a new MenuCommand object. - public MenuCommand(Object inContext, int inUserData) { context = inContext; userData = inUserData; } - // Creates a new MenuCommand object. - public MenuCommand(Object inContext) { context = inContext; userData = 0; } - } -} diff --git a/Editor/Mono/MenuItem.cs b/Editor/Mono/MenuItem.cs deleted file mode 100644 index 1951b37469..0000000000 --- a/Editor/Mono/MenuItem.cs +++ /dev/null @@ -1,43 +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.Scripting; - -namespace UnityEditor -{ - // The MenuItem attribute allows you to add menu items to the main menu and inspector context menus. - [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] - [RequiredByNativeCode] - public sealed class MenuItem : Attribute - { - // Creates a menu item and invokes the static function following it, when the menu item is selected. - public MenuItem(string itemName) : this(itemName, false) {} - - // Creates a menu item and invokes the static function following it, when the menu item is selected. - public MenuItem(string itemName, bool isValidateFunction) : this(itemName, isValidateFunction, itemName.StartsWith("GameObject/Create Other") ? 10 : 1000) {} - // The special treatment of "GameObject/Other" is to ensure that legacy scripts that don't set a priority don't create a - // "Create Other" menu at the very bottom of the GameObject menu (thus preventing the items from being propagated to the - // scene hierarchy dropdown and context menu). - - // Creates a menu item and invokes the static function following it, when the menu item is selected. - public MenuItem(string itemName, bool isValidateFunction, int priority) : this(itemName, isValidateFunction, priority, false) {} - - // Creates a menu item and invokes the static function following it, when the menu item is selected. - internal MenuItem(string itemName, bool isValidateFunction, int priority, bool internalMenu) - { - if (internalMenu) - menuItem = "internal:" + itemName; - else - menuItem = itemName; - validate = isValidateFunction; - this.priority = priority; - } - - public string menuItem; - public bool validate; - public int priority; - } -} diff --git a/Editor/Mono/NumericFieldDraggerUtility.cs b/Editor/Mono/NumericFieldDraggerUtility.cs deleted file mode 100644 index 87ec27bbe0..0000000000 --- a/Editor/Mono/NumericFieldDraggerUtility.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 System; -using UnityEngine; - -namespace UnityEditor -{ - class NumericFieldDraggerUtility - { - internal static float Acceleration(bool shiftPressed, bool altPressed) - { - return (shiftPressed ? 4 : 1) * (altPressed ? .25f : 1); - } - - static bool s_UseYSign = false; - - internal static float NiceDelta(Vector2 deviceDelta, float acceleration) - { - deviceDelta.y = -deviceDelta.y; - - if (Mathf.Abs(Mathf.Abs(deviceDelta.x) - Mathf.Abs(deviceDelta.y)) / Mathf.Max(Mathf.Abs(deviceDelta.x), Mathf.Abs(deviceDelta.y)) > .1f) - { - if (Mathf.Abs(deviceDelta.x) > Mathf.Abs(deviceDelta.y)) - s_UseYSign = false; - else - s_UseYSign = true; - } - - if (s_UseYSign) - return Mathf.Sign(deviceDelta.y) * deviceDelta.magnitude * acceleration; - else - return Mathf.Sign(deviceDelta.x) * deviceDelta.magnitude * acceleration; - } - - const float kDragSensitivity = .03f; - - internal static double CalculateFloatDragSensitivity(double value) - { - if (double.IsInfinity(value) || double.IsNaN(value)) - { - return 0.0; - } - return Math.Max(1, Math.Pow(Math.Abs(value), 0.5)) * kDragSensitivity; - } - - internal static long CalculateIntDragSensitivity(long value) - { - return (long)Math.Max(1, Math.Pow(Math.Abs((double)value), 0.5) * kDragSensitivity); - } - } -} diff --git a/Editor/Mono/ObjectListGroup.cs b/Editor/Mono/ObjectListGroup.cs deleted file mode 100644 index 62b19915ce..0000000000 --- a/Editor/Mono/ObjectListGroup.cs +++ /dev/null @@ -1,283 +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 UnityEditor; -using UnityEditorInternal; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using Math = System.Math; -using IndexOutOfRangeException = System.IndexOutOfRangeException; - - -namespace UnityEditor -{ - internal partial class ObjectListArea - { - /* Abstract base class for each group of assets (e.g. Local, AssetStore) used in the ObjectListArea - */ - abstract class Group - { - readonly protected float kGroupSeparatorHeight = EditorStyles.toolbar.fixedHeight; - protected string m_GroupSeparatorTitle; - - protected static int[] s_Empty; - public ObjectListArea m_Owner; - public VerticalGrid m_Grid = new VerticalGrid(); - public float m_Height; - - public float Height { get { return m_Height; } } - abstract public int ItemCount { get; } - abstract public bool ListMode { get; set; } - abstract public bool NeedsRepaint { get; protected set; } - - public bool Visible = true; // Visibility toggled in GUI - public int ItemsAvailable = 0; // Calculated from total asset count - public int ItemsWantedShown = 0; // Rows requested to be displayed - protected bool m_Collapsable = true; - public double m_LastClickedDrawTime = 0; - - public Group(ObjectListArea owner, string groupTitle) - { - m_GroupSeparatorTitle = groupTitle; - if (s_Empty == null) - s_Empty = new int[0]; - m_Owner = owner; - Visible = visiblePreference; - } - - public bool visiblePreference - { - get - { - if (string.IsNullOrEmpty(m_GroupSeparatorTitle)) - return true; - return EditorPrefs.GetBool(m_GroupSeparatorTitle, true); - } - set - { - if (string.IsNullOrEmpty(m_GroupSeparatorTitle)) - return; - EditorPrefs.SetBool(m_GroupSeparatorTitle, value); - } - } - - - // Called before repaints in order to prepare internal assets for rendering - abstract public void UpdateAssets(); - - // Called when height of this group should be recalculated - abstract public void UpdateHeight(); - - abstract protected void DrawInternal(int itemIdx, int endItem, float yOffset); - - // Called when the filter has changed - abstract public void UpdateFilter(HierarchyType hierarchyType, SearchFilter searchFilter, bool showFoldersFirst); - - protected virtual float GetHeaderHeight() - { - return kGroupSeparatorHeight; - } - - protected virtual void HandleUnusedDragEvents(float yOffset) {} - - int FirstVisibleRow(float yOffset, Vector2 scrollPos) - { - if (!Visible) - return -1; - - // Skip rows that is outside the offset rect - float yRelOffset = scrollPos.y - (yOffset + GetHeaderHeight()); - - int invisibleRows = 0; - if (yRelOffset > 0f) - { - // Initial rows hidden - float itemHeight = m_Grid.itemSize.y + m_Grid.verticalSpacing; - invisibleRows = (int)Mathf.Max(0, Mathf.Floor(yRelOffset / itemHeight)); - } - return invisibleRows; - } - - bool IsInView(float yOffset, Vector2 scrollPos, float scrollViewHeight) - { - if ((scrollPos.y + scrollViewHeight) < yOffset) - return false; // after visible area - - if ((yOffset + Height) < scrollPos.y) - return false; // before visible area - - return true; - } - - // Main draw method of a group that is called from outside - public void Draw(float yOffset, Vector2 scrollPos, ref int rowsInUse) - { - NeedsRepaint = false; - - // We need to always draw the header as it uses controlIDs (and we cannot cull gui elements using controlID) - bool isRepaint = Event.current.type == EventType.Repaint || Event.current.type == EventType.Layout; - - if (!isRepaint) - DrawHeader(yOffset, m_Collapsable); // logic here, draw on top below - - if (!IsInView(yOffset, scrollPos, m_Owner.m_VisibleRect.height)) - return; - - int invisibleRows = FirstVisibleRow(yOffset, scrollPos); - int beginItem = invisibleRows * m_Grid.columns; - int totalItemCount = ItemCount; - if (beginItem >= 0 && beginItem < totalItemCount) - { - int itemIdx = beginItem; - // Limit by items avail and max items to show - // (plus an extra row to allow half a row in top and bottom at the same time) - int endItem = Math.Min(totalItemCount, m_Grid.rows * m_Grid.columns); - - // Also limit to what can possible be in view in order to limit draws - float itemHeight = m_Grid.itemSize.y + m_Grid.verticalSpacing; - int rowsInVisibleRect = (int)Math.Ceiling(m_Owner.m_VisibleRect.height / itemHeight); - - //When a row is hidden behind the header, it is still counted as visible, therefore to avoid - //weird popping in and out for the icons, we make sure that a new row will be rendered even if one - //is considered visible, even though it cannot be seen in the window - rowsInVisibleRect += 1; - - int rowsNotInUse = rowsInVisibleRect - rowsInUse; - if (rowsNotInUse < 0) - rowsNotInUse = 0; - - rowsInUse = Math.Min(rowsInVisibleRect, Mathf.CeilToInt((endItem - beginItem) / (float)m_Grid.columns)); - - endItem = rowsNotInUse * m_Grid.columns + beginItem; - if (endItem > totalItemCount) - endItem = totalItemCount; - - DrawInternal(itemIdx, endItem, yOffset); - } - - if (isRepaint) - DrawHeader(yOffset, m_Collapsable); - - // Always handle drag events in the case where we have no items we still want to be able to drag into the group. - HandleUnusedDragEvents(yOffset); - } - - protected void DrawObjectIcon(Rect position, Texture icon) - { - if (icon == null) - return; - - int size = icon.width; - - FilterMode temp = icon.filterMode; - icon.filterMode = FilterMode.Point; - GUI.DrawTexture(new Rect(position.x + ((int)position.width - size) / 2, position.y + ((int)position.height - size) / 2, size, size), icon, ScaleMode.ScaleToFit); - icon.filterMode = temp; - } - - protected void DrawDropShadowOverlay(Rect position, bool selected, bool isDropTarget, bool isRenaming) - { - // Draw dropshadow overlay - float fraction = position.width / 128f; - Rect dropShadowRect = new Rect(position.x - 4 * fraction, position.y - 2 * fraction, position.width + 8 * fraction, position.height + 12 * fraction - 0.5f); - s_Styles.iconDropShadow.Draw(dropShadowRect, GUIContent.none, false, false, selected || isDropTarget, m_Owner.HasFocus() || isRenaming || isDropTarget); - } - - protected void DrawHeaderBackground(Rect rect, bool firstHeader) - { - if (Event.current.type != EventType.Repaint) - return; - - // Draw the group bar background - GUI.Label(rect, GUIContent.none, firstHeader ? s_Styles.groupHeaderTop : s_Styles.groupHeaderMiddle); - } - - protected float GetHeaderYPosInScrollArea(float yOffset) - { - float y = yOffset; - float yScrollPos = m_Owner.m_State.m_ScrollPosition.y; - if (yScrollPos > yOffset) - { - y = Mathf.Min(yScrollPos, yOffset + Height - kGroupSeparatorHeight); - } - return y; - } - - virtual protected void DrawHeader(float yOffset, bool collapsable) - { - const int foldoutSpacing = 3; - Rect rect = new Rect(0, GetHeaderYPosInScrollArea(yOffset), m_Owner.GetVisibleWidth(), kGroupSeparatorHeight - 1); - - DrawHeaderBackground(rect, yOffset == 0); - - // Draw the group toggle - rect.x += 7; - if (collapsable) - { - bool oldVisible = Visible; - Visible = GUI.Toggle(rect, Visible, GUIContent.none, s_Styles.groupFoldout); - if (oldVisible ^ Visible) - visiblePreference = Visible; - } - - // Draw title - GUIStyle textStyle = s_Styles.groupHeaderLabel; - if (collapsable) - rect.x += s_Styles.groupFoldout.fixedWidth + foldoutSpacing; - rect.y += 1; - if (!string.IsNullOrEmpty(m_GroupSeparatorTitle)) - GUI.Label(rect, m_GroupSeparatorTitle, textStyle); - - if (s_Debug) - { - Rect r2 = rect; - r2.x += 120; - GUI.Label(r2, AssetStorePreviewManager.StatsString()); - } - - rect.y -= 1; - - // Only draw counts if we have room for it - if (m_Owner.GetVisibleWidth() > 150) - DrawItemCount(rect); - } - - protected void DrawItemCount(Rect rect) - { - // Draw item count in group - const float rightMargin = 4f; - - string label = ItemsAvailable.ToString() + " Total"; - Vector2 labelDims = s_Styles.groupHeaderLabelCount.CalcSize(new GUIContent(label)); - if (labelDims.x < rect.width) - rect.x = m_Owner.GetVisibleWidth() - labelDims.x - rightMargin; // right align if room - rect.width = labelDims.x; - rect.y += 2; // better y pos for minilabel - GUI.Label(rect, label, s_Styles.groupHeaderLabelCount); - } - - Object[] GetSelectedReferences() - { - return Selection.objects; - } - - static string[] GetMainSelectedPaths() - { - List paths = new List(); - foreach (int instanceID in Selection.instanceIDs) - { - if (AssetDatabase.IsMainAsset(instanceID)) - { - string path = AssetDatabase.GetAssetPath(instanceID); - paths.Add(path); - } - } - - return paths.ToArray(); - } - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/PackageUtility.bindings.cs b/Editor/Mono/PackageUtility.bindings.cs index ddc81d4910..c548a47068 100644 --- a/Editor/Mono/PackageUtility.bindings.cs +++ b/Editor/Mono/PackageUtility.bindings.cs @@ -68,5 +68,8 @@ internal class PackageUtility public static extern void ImportPackageAssets(string packageName, ImportPackageItem[] items, bool performReInstall); [FreeFunction("ImportPackageAssets")] public static extern void ImportPackageAssetsImmediately(string packageName, ImportPackageItem[] items, bool performReInstall); + + [FreeFunction("TickPackageImport")] + public static extern void TickPackageImport(); } } diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemClipboard.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemClipboard.cs deleted file mode 100644 index 076586d287..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemClipboard.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 UnityEngine; - - -namespace UnityEditor -{ - internal class ParticleSystemClipboard - { - static AnimationCurve m_AnimationCurve1; - static AnimationCurve m_AnimationCurve2; - static float m_AnimationCurveScalar; - static Gradient m_Gradient1; - static Gradient m_Gradient2; - - - // Gradient section - - static public bool HasSingleGradient() - { - return m_Gradient1 != null && m_Gradient2 == null; - } - - static public bool HasDoubleGradient() - { - return m_Gradient1 != null && m_Gradient2 != null; - } - - static public void CopyGradient(Gradient gradient1, Gradient gradient2) - { - m_Gradient1 = gradient1; - m_Gradient2 = gradient2; - } - - static public void PasteGradient(SerializedProperty gradientProperty, SerializedProperty gradientProperty2) - { - if (gradientProperty != null && m_Gradient1 != null) - gradientProperty.gradientValue = m_Gradient1; - - if (gradientProperty2 != null && m_Gradient2 != null) - gradientProperty2.gradientValue = m_Gradient2; - } - - // AnimationCurve section - - static public bool HasSingleAnimationCurve() - { - return m_AnimationCurve1 != null && m_AnimationCurve2 == null; - } - - static public bool HasDoubleAnimationCurve() - { - return m_AnimationCurve1 != null && m_AnimationCurve2 != null; - } - - static public void CopyAnimationCurves(AnimationCurve animCurve, AnimationCurve animCurve2, float scalar) - { - m_AnimationCurve1 = animCurve; - m_AnimationCurve2 = animCurve2; - m_AnimationCurveScalar = scalar; - } - - static private void ClampCurve(SerializedProperty animCurveProperty, Rect curveRanges) - { - AnimationCurve clampedCurve = animCurveProperty.animationCurveValue; - Keyframe[] keys = clampedCurve.keys; - for (int i = 0; i < keys.Length; ++i) - { - keys[i].time = Mathf.Clamp(keys[i].time, curveRanges.xMin, curveRanges.xMax); - keys[i].value = Mathf.Clamp(keys[i].value, curveRanges.yMin, curveRanges.yMax); - } - clampedCurve.keys = keys; - animCurveProperty.animationCurveValue = clampedCurve; - } - - static public void PasteAnimationCurves(SerializedProperty animCurveProperty, SerializedProperty animCurveProperty2, SerializedProperty scalarProperty, Rect curveRanges, ParticleSystemCurveEditor particleSystemCurveEditor) - { - if (animCurveProperty != null && m_AnimationCurve1 != null) - { - animCurveProperty.animationCurveValue = m_AnimationCurve1; - ClampCurve(animCurveProperty, curveRanges); - } - - if (animCurveProperty2 != null && m_AnimationCurve2 != null) - { - animCurveProperty2.animationCurveValue = m_AnimationCurve2; - ClampCurve(animCurveProperty2, curveRanges); - } - - if (scalarProperty != null) - scalarProperty.floatValue = m_AnimationCurveScalar; - - // Ensure refresh of systems that uses curves - if (particleSystemCurveEditor != null) - particleSystemCurveEditor.Refresh(); - } - } - - - internal class GradientContextMenu - { - readonly SerializedProperty m_Prop1; - - - static internal void Show(SerializedProperty prop) - { - // Curve context menu - GUIContent copy = EditorGUIUtility.TrTextContent("Copy"); - GUIContent paste = EditorGUIUtility.TrTextContent("Paste"); - - GenericMenu menu = new GenericMenu(); - var gradientMenu = new GradientContextMenu(prop); - menu.AddItem(copy, false, gradientMenu.Copy); - if (ParticleSystemClipboard.HasSingleGradient()) - menu.AddItem(paste, false, gradientMenu.Paste); - else - menu.AddDisabledItem(paste); - - menu.ShowAsContext(); - } - - private GradientContextMenu(SerializedProperty prop1) - { - m_Prop1 = prop1; - } - - private void Copy() - { - Gradient gradient1 = m_Prop1 != null ? m_Prop1.gradientValue : null; - ParticleSystemClipboard.CopyGradient(gradient1, null); - } - - private void Paste() - { - ParticleSystemClipboard.PasteGradient(m_Prop1, null); - if (m_Prop1 != null) - m_Prop1.serializedObject.ApplyModifiedProperties(); - UnityEditorInternal.GradientPreviewCache.ClearCache(); - } - } - - - internal class AnimationCurveContextMenu - { - readonly SerializedProperty m_Prop1; - readonly SerializedProperty m_Prop2; - readonly SerializedProperty m_Scalar; - readonly ParticleSystemCurveEditor m_ParticleSystemCurveEditor; - readonly Rect m_CurveRanges; - - static internal void Show(Rect position, SerializedProperty property, SerializedProperty property2, SerializedProperty scalar, Rect curveRanges, ParticleSystemCurveEditor curveEditor) - { - // Curve context menu - GUIContent copy = EditorGUIUtility.TrTextContent("Copy"); - GUIContent paste = EditorGUIUtility.TrTextContent("Paste"); - - GenericMenu menu = new GenericMenu(); - - bool isRegion = property != null && property2 != null; - bool validPaste = (isRegion && ParticleSystemClipboard.HasDoubleAnimationCurve()) || (!isRegion && ParticleSystemClipboard.HasSingleAnimationCurve()); - - AnimationCurveContextMenu obj = new AnimationCurveContextMenu(property, property2, scalar, curveRanges, curveEditor); - menu.AddItem(copy, false, obj.Copy); - if (validPaste) - menu.AddItem(paste, false, obj.Paste); - else - menu.AddDisabledItem(paste); - - menu.DropDown(position); - } - - private AnimationCurveContextMenu(SerializedProperty prop1, SerializedProperty prop2, SerializedProperty scalar, Rect curveRanges, ParticleSystemCurveEditor owner) - { - m_Prop1 = prop1; - m_Prop2 = prop2; - m_Scalar = scalar; - m_ParticleSystemCurveEditor = owner; - m_CurveRanges = curveRanges; - } - - private void Copy() - { - AnimationCurve animCurve1 = m_Prop1 != null ? m_Prop1.animationCurveValue : null; - AnimationCurve animCurve2 = m_Prop2 != null ? m_Prop2.animationCurveValue : null; - float scalar = m_Scalar != null ? m_Scalar.floatValue : 1.0f; - ParticleSystemClipboard.CopyAnimationCurves(animCurve1, animCurve2, scalar); - } - - private void Paste() - { - ParticleSystemClipboard.PasteAnimationCurves(m_Prop1, m_Prop2, m_Scalar, m_CurveRanges, m_ParticleSystemCurveEditor); - if (m_Prop1 != null) - m_Prop1.serializedObject.ApplyModifiedProperties(); - if (m_Prop2 != null) - m_Prop2.serializedObject.ApplyModifiedProperties(); - if (m_Scalar != null) - m_Scalar.serializedObject.ApplyModifiedProperties(); - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ClampVelocityModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ClampVelocityModuleUI.cs deleted file mode 100644 index c85b21d202..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ClampVelocityModuleUI.cs +++ /dev/null @@ -1,120 +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; - - -namespace UnityEditor -{ - class ClampVelocityModuleUI : ModuleUI - { - SerializedMinMaxCurve m_X; - SerializedMinMaxCurve m_Y; - SerializedMinMaxCurve m_Z; - SerializedMinMaxCurve m_Magnitude; - SerializedProperty m_SeparateAxes; - SerializedProperty m_InWorldSpace; - SerializedProperty m_Dampen; - SerializedMinMaxCurve m_Drag; - SerializedProperty m_MultiplyDragByParticleSize; - SerializedProperty m_MultiplyDragByParticleVelocity; - - class Texts - { - public GUIContent x = EditorGUIUtility.TextContent("X"); - public GUIContent y = EditorGUIUtility.TextContent("Y"); - public GUIContent z = EditorGUIUtility.TextContent("Z"); - public GUIContent dampen = EditorGUIUtility.TrTextContent("Dampen", "Controls how much the velocity that exceeds the velocity limit should be dampened. A value of 0.5 will dampen the exceeding velocity by 50%."); - public GUIContent magnitude = EditorGUIUtility.TrTextContent("Speed", "The speed limit of particles over the particle lifetime."); - public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the velocity limit separately for each axis."); - public GUIContent space = EditorGUIUtility.TrTextContent("Space", "Specifies if the velocity values are in local space (rotated with the transform) or world space."); - public string[] spaces = { "Local", "World" }; - public GUIContent drag = EditorGUIUtility.TrTextContent("Drag", "Control the amount of drag applied to each particle during its lifetime."); - public GUIContent multiplyDragByParticleSize = EditorGUIUtility.TrTextContent("Multiply by Size", "Adjust the drag based on the size of the particles."); - public GUIContent multiplyDragByParticleVelocity = EditorGUIUtility.TrTextContent("Multiply by Velocity", "Adjust the drag based on the velocity of the particles."); - } - static Texts s_Texts; - - - public ClampVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "ClampVelocityModule", displayName) - { - m_ToolTip = "Controls the velocity limit and damping of each particle during its lifetime."; - } - - protected override void Init() - { - // Already initialized? - if (m_X != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_X = new SerializedMinMaxCurve(this, s_Texts.x, "x"); - m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y"); - m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "z"); - m_Magnitude = new SerializedMinMaxCurve(this, s_Texts.magnitude, "magnitude"); - m_SeparateAxes = GetProperty("separateAxis"); - m_InWorldSpace = GetProperty("inWorldSpace"); - m_Dampen = GetProperty("dampen"); - m_Drag = new SerializedMinMaxCurve(this, s_Texts.drag, "drag"); - m_MultiplyDragByParticleSize = GetProperty("multiplyDragByParticleSize"); - m_MultiplyDragByParticleVelocity = GetProperty("multiplyDragByParticleVelocity"); - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - EditorGUI.BeginChangeCheck(); - bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); - if (EditorGUI.EndChangeCheck()) - { - // Remove old curves from curve editor - if (separateAxes) - { - m_Magnitude.RemoveCurveFromEditor(); - } - else - { - m_X.RemoveCurveFromEditor(); - m_Y.RemoveCurveFromEditor(); - m_Z.RemoveCurveFromEditor(); - } - } - - // Keep states in sync - if (!m_X.stateHasMultipleDifferentValues) - { - m_Y.SetMinMaxState(m_X.state, separateAxes); - m_Z.SetMinMaxState(m_X.state, separateAxes); - } - - if (separateAxes) - { - GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); - EditorGUI.indentLevel++; - GUIBoolAsPopup(s_Texts.space, m_InWorldSpace, s_Texts.spaces); - EditorGUI.indentLevel--; - } - else - { - GUIMinMaxCurve(s_Texts.magnitude, m_Magnitude); - } - - EditorGUI.indentLevel++; - GUIFloat(s_Texts.dampen, m_Dampen); - EditorGUI.indentLevel--; - - GUIMinMaxCurve(s_Texts.drag, m_Drag); - EditorGUI.indentLevel++; - GUIToggle(s_Texts.multiplyDragByParticleSize, m_MultiplyDragByParticleSize); - GUIToggle(s_Texts.multiplyDragByParticleVelocity, m_MultiplyDragByParticleVelocity); - EditorGUI.indentLevel--; - } - - override public void UpdateCullingSupportedString(ref string text) - { - text += "\nLimit Velocity over Lifetime module is enabled."; - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ColorByVelocityModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ColorByVelocityModuleUI.cs deleted file mode 100644 index b37f5d39c9..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ColorByVelocityModuleUI.cs +++ /dev/null @@ -1,48 +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; - - -namespace UnityEditor -{ - class ColorByVelocityModuleUI : ModuleUI - { - class Texts - { - public GUIContent color = EditorGUIUtility.TrTextContent("Color", "Controls the color of each particle based on its speed."); - public GUIContent velocityRange = EditorGUIUtility.TrTextContent("Speed Range", "Remaps speed in the defined range to a color."); - } - static Texts s_Texts; - SerializedMinMaxGradient m_Gradient; - SerializedProperty m_Range; - - public ColorByVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "ColorBySpeedModule", displayName) - { - m_ToolTip = "Controls the color of each particle based on its speed."; - } - - protected override void Init() - { - // Already initialized? - if (m_Gradient != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_Gradient = new SerializedMinMaxGradient(this); - m_Gradient.m_AllowColor = false; - m_Gradient.m_AllowRandomBetweenTwoColors = false; - - m_Range = GetProperty("range"); - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - GUIMinMaxGradient(s_Texts.color, m_Gradient, false); - GUIMinMaxRange(s_Texts.velocityRange, m_Range); - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ColorModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ColorModuleUI.cs deleted file mode 100644 index 9aaafdf557..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ColorModuleUI.cs +++ /dev/null @@ -1,43 +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; - - -namespace UnityEditor -{ - class ColorModuleUI : ModuleUI - { - class Texts - { - public GUIContent color = EditorGUIUtility.TrTextContent("Color", "Controls the color of each particle during its lifetime."); - } - static Texts s_Texts; - SerializedMinMaxGradient m_Gradient; - - public ColorModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "ColorModule", displayName) - { - m_ToolTip = "Controls the color of each particle during its lifetime."; - } - - protected override void Init() - { - // Already initialized? - if (m_Gradient != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_Gradient = new SerializedMinMaxGradient(this); - m_Gradient.m_AllowColor = false; - m_Gradient.m_AllowRandomBetweenTwoColors = false; - } - - public override void OnInspectorGUI(InitialModuleUI initial) - { - GUIMinMaxGradient(s_Texts.color, m_Gradient, false); - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ForceModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ForceModuleUI.cs deleted file mode 100644 index 74add0163f..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/ForceModuleUI.cs +++ /dev/null @@ -1,84 +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; - - -namespace UnityEditor -{ - class ForceModuleUI : ModuleUI - { - SerializedMinMaxCurve m_X; - SerializedMinMaxCurve m_Y; - SerializedMinMaxCurve m_Z; - SerializedProperty m_RandomizePerFrame; - SerializedProperty m_InWorldSpace; - - - class Texts - { - public GUIContent x = EditorGUIUtility.TextContent("X"); - public GUIContent y = EditorGUIUtility.TextContent("Y"); - public GUIContent z = EditorGUIUtility.TextContent("Z"); - public GUIContent randomizePerFrame = EditorGUIUtility.TrTextContent("Randomize", "Randomize force every frame. Only available when using random between two constants or random between two curves."); - public GUIContent space = EditorGUIUtility.TrTextContent("Space", "Specifies if the force values are in local space (rotated with the transform) or world space."); - public string[] spaces = {"Local", "World"}; - } - static Texts s_Texts; - - public ForceModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "ForceModule", displayName) - { - m_ToolTip = "Controls the force of each particle during its lifetime."; - } - - protected override void Init() - { - // Already initialized? - if (m_X != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_X = new SerializedMinMaxCurve(this, s_Texts.x, "x", kUseSignedRange); - m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", kUseSignedRange); - m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "z", kUseSignedRange); - m_RandomizePerFrame = GetProperty("randomizePerFrame"); - m_InWorldSpace = GetProperty("inWorldSpace"); - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - MinMaxCurveState state = m_X.state; - GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, m_RandomizePerFrame); - - GUIBoolAsPopup(s_Texts.space, m_InWorldSpace, s_Texts.spaces); - - using (new EditorGUI.DisabledScope((state != MinMaxCurveState.k_TwoScalars) && (state != MinMaxCurveState.k_TwoCurves))) - { - GUIToggle(s_Texts.randomizePerFrame, m_RandomizePerFrame); - } - } - - override public void UpdateCullingSupportedString(ref string text) - { - Init(); - - string failureReason = string.Empty; - if (!m_X.SupportsProcedural(ref failureReason)) - text += "\nForce over Lifetime module curve X: " + failureReason; - - failureReason = string.Empty; - if (!m_Y.SupportsProcedural(ref failureReason)) - text += "\nForce over Lifetime module curve Y: " + failureReason; - - failureReason = string.Empty; - if (!m_Z.SupportsProcedural(ref failureReason)) - text += "\nForce over Lifetime module curve Z: " + failureReason; - - if (m_RandomizePerFrame.boolValue) - text += "\nRandomize is enabled in the Force over Lifetime module."; - } - } // namespace UnityEditor -} diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InheritVelocityModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InheritVelocityModuleUI.cs deleted file mode 100644 index 2a05a8e4e6..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InheritVelocityModuleUI.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 UnityEngine; - -namespace UnityEditor -{ - class InheritVelocityModuleUI : ModuleUI - { - // Keep in sync with InheritVelocityModule.h - enum Modes { Initial = 0, Current = 1 }; - - SerializedProperty m_Mode; - SerializedMinMaxCurve m_Curve; - - class Texts - { - public GUIContent mode = EditorGUIUtility.TrTextContent("Mode", "Specifies whether the emitter velocity is inherited as a one-shot when a particle is born, always using the current emitter velocity, or using the emitter velocity when the particle was born."); - public GUIContent velocity = EditorGUIUtility.TrTextContent("Multiplier", "Controls the amount of emitter velocity inherited during each particle's lifetime."); - - public GUIContent[] modes = new GUIContent[] - { - EditorGUIUtility.TrTextContent("Initial"), - EditorGUIUtility.TrTextContent("Current") - }; - } - static Texts s_Texts; - - public InheritVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "InheritVelocityModule", displayName) - { - m_ToolTip = "Controls the velocity inherited from the emitter, for each particle."; - } - - protected override void Init() - { - // Already initialized? - if (m_Curve != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_Mode = GetProperty("m_Mode"); - m_Curve = new SerializedMinMaxCurve(this, GUIContent.none, "m_Curve", kUseSignedRange); - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - GUIPopup(s_Texts.mode, m_Mode, s_Texts.modes); - GUIMinMaxCurve(s_Texts.velocity, m_Curve); - } - - override public void UpdateCullingSupportedString(ref string text) - { - Init(); - - string failureReason = string.Empty; - if (!m_Curve.SupportsProcedural(ref failureReason)) - text += "\nInherit Velocity module curve: " + failureReason; - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InitialModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InitialModuleUI.cs index 0f20879f08..87217b8985 100644 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InitialModuleUI.cs +++ b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/InitialModuleUI.cs @@ -38,6 +38,7 @@ internal class InitialModuleUI : ModuleUI public SerializedProperty m_AutoRandomSeed; public SerializedProperty m_RandomSeed; public SerializedProperty m_StopAction; + public SerializedProperty m_CullingMode; public SerializedProperty m_RingBufferMode; public SerializedProperty m_RingBufferLoopRange; @@ -68,6 +69,7 @@ class Texts public GUIContent randomSeed = EditorGUIUtility.TrTextContent("Random Seed", "Randomize the look of the Particle System. Using the same seed will make the Particle System play identically each time. After changing this value, restart the Particle System to see the changes, or check the Resimulate box."); public GUIContent emitterVelocity = EditorGUIUtility.TrTextContent("Emitter Velocity", "When the Particle System is moving, should we use its Transform, or Rigidbody Component, to calculate its velocity?"); public GUIContent stopAction = EditorGUIUtility.TrTextContent("Stop Action", "When the Particle System is stopped and all particles have died, should the GameObject automatically disable/destroy itself?"); + public GUIContent cullingMode = EditorGUIUtility.TrTextContent("Culling Mode", "Choose whether to continue simulating the Particle System when offscreen. Catch-up mode pauses offscreen simulations, but performs a large simulation step when they become visible, giving the appearance that they were never paused. Automatic uses Pause mode for looping systems, and AlwaysSimulate if not looping."); public GUIContent ringBufferMode = EditorGUIUtility.TrTextContent("Ring Buffer Mode", "Rather than dying when their lifetime has elapsed, particles will remain alive until the Max Particles buffer is full, at which point new particles will replace the oldest."); public GUIContent ringBufferLoopRange = EditorGUIUtility.TrTextContent("Loop Range", "Particle lifetimes may loop between a fade-in and fade-out time, in order to use curves for the entire time they are alive. Values are in the 0-1 range."); public GUIContent x = EditorGUIUtility.TextContent("X"); @@ -96,6 +98,14 @@ class Texts EditorGUIUtility.TrTextContent("Callback") }; + public GUIContent[] cullingModes = new GUIContent[] + { + EditorGUIUtility.TrTextContent("Automatic"), + EditorGUIUtility.TrTextContent("Pause and Catch-up"), + EditorGUIUtility.TrTextContent("Pause"), + EditorGUIUtility.TrTextContent("Always Simulate") + }; + public GUIContent[] ringBufferModes = new GUIContent[] { EditorGUIUtility.TrTextContent("Disabled"), @@ -146,6 +156,7 @@ protected override void Init() m_AutoRandomSeed = GetProperty0("autoRandomSeed"); m_RandomSeed = GetProperty0("randomSeed"); m_StopAction = GetProperty0("stopAction"); + m_CullingMode = GetProperty0("cullingMode"); m_RingBufferMode = GetProperty0("ringBufferMode"); m_RingBufferLoopRange = GetProperty0("ringBufferLoopRange"); @@ -307,6 +318,7 @@ override public void OnInspectorGUI(InitialModuleUI initial) } GUIPopup(s_Texts.stopAction, m_StopAction, s_Texts.stopActions); + GUIPopup(s_Texts.cullingMode, m_CullingMode, s_Texts.cullingModes); ParticleSystemRingBufferMode ringBufferMode = (ParticleSystemRingBufferMode)GUIPopup(s_Texts.ringBufferMode, m_RingBufferMode, s_Texts.ringBufferModes); if (!m_RingBufferMode.hasMultipleDifferentValues && ringBufferMode == ParticleSystemRingBufferMode.LoopUntilReplaced) diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/LightsModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/LightsModuleUI.cs deleted file mode 100644 index 60920208d0..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/LightsModuleUI.cs +++ /dev/null @@ -1,85 +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; - - -namespace UnityEditor -{ - class LightsModuleUI : ModuleUI - { - class Texts - { - public GUIContent ratio = EditorGUIUtility.TrTextContent("Ratio", "Amount of particles that have a light source attached to them."); - public GUIContent randomDistribution = EditorGUIUtility.TrTextContent("Random Distribution", "Emit lights randomly, or at regular intervals."); - public GUIContent light = EditorGUIUtility.TrTextContent("Light", "Light prefab to be used for spawning particle lights."); - public GUIContent color = EditorGUIUtility.TrTextContent("Use Particle Color", "Check the option to multiply the particle color by the light color. Otherwise, only the color of the light is used."); - public GUIContent range = EditorGUIUtility.TrTextContent("Size Affects Range", "Multiply the range of the light with the size of the particle."); - public GUIContent intensity = EditorGUIUtility.TrTextContent("Alpha Affects Intensity", "Multiply the intensity of the light with the alpha of the particle."); - public GUIContent rangeCurve = EditorGUIUtility.TrTextContent("Range Multiplier", "Apply a custom multiplier to the range of the lights."); - public GUIContent intensityCurve = EditorGUIUtility.TrTextContent("Intensity Multiplier", "Apply a custom multiplier to the intensity of the lights."); - public GUIContent maxLights = EditorGUIUtility.TrTextContent("Maximum Lights", "Limit the amount of lights the system can create. This module makes it very easy to create lots of lights, which can hurt performance."); - } - static Texts s_Texts; - - SerializedProperty m_Ratio; - SerializedProperty m_RandomDistribution; - SerializedProperty m_Light; - SerializedProperty m_UseParticleColor; - SerializedProperty m_SizeAffectsRange; - SerializedProperty m_AlphaAffectsIntensity; - SerializedMinMaxCurve m_Range; - SerializedMinMaxCurve m_Intensity; - SerializedProperty m_MaxLights; - - public LightsModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "LightsModule", displayName) - { - m_ToolTip = "Controls light sources attached to particles."; - } - - protected override void Init() - { - // Already initialized? - if (m_Ratio != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_Ratio = GetProperty("ratio"); - m_RandomDistribution = GetProperty("randomDistribution"); - m_Light = GetProperty("light"); - m_UseParticleColor = GetProperty("color"); - m_SizeAffectsRange = GetProperty("range"); - m_AlphaAffectsIntensity = GetProperty("intensity"); - m_MaxLights = GetProperty("maxLights"); - - m_Range = new SerializedMinMaxCurve(this, s_Texts.rangeCurve, "rangeCurve"); - m_Intensity = new SerializedMinMaxCurve(this, s_Texts.intensityCurve, "intensityCurve"); - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - GUIObject(s_Texts.light, m_Light); - GUIFloat(s_Texts.ratio, m_Ratio); - GUIToggle(s_Texts.randomDistribution, m_RandomDistribution); - GUIToggle(s_Texts.color, m_UseParticleColor); - GUIToggle(s_Texts.range, m_SizeAffectsRange); - GUIToggle(s_Texts.intensity, m_AlphaAffectsIntensity); - GUIMinMaxCurve(s_Texts.rangeCurve, m_Range); - GUIMinMaxCurve(s_Texts.intensityCurve, m_Intensity); - GUIInt(s_Texts.maxLights, m_MaxLights); - - if (m_Light.objectReferenceValue) - { - Light light = (Light)m_Light.objectReferenceValue; - if (light.type != LightType.Point && light.type != LightType.Spot) - { - GUIContent warning = EditorGUIUtility.TrTextContent("Only point and spot lights are supported on particles."); - EditorGUILayout.HelpBox(warning.text, MessageType.Warning, true); - } - } - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs index ff4c3926cd..35f83e7f67 100644 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs +++ b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RendererModuleUI.cs @@ -274,12 +274,15 @@ override public void OnInspectorGUI(InitialModuleUI initial) { if (renderMode != RenderMode.Mesh) GUIFloat(s_Texts.normalDirection, m_NormalDirection); - - if (m_Material != null) // The renderer's material list could be empty - GUIObject(s_Texts.material, m_Material); } } + if (renderMode != RenderMode.None) + { + if (m_Material != null) // The renderer's material list could be empty + GUIObject(s_Texts.material, m_Material); + } + if (m_TrailMaterial != null) // The renderer's material list could be empty GUIObject(s_Texts.trailMaterial, m_TrailMaterial); diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RotationByVelocityModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RotationByVelocityModuleUI.cs deleted file mode 100644 index 445608bb81..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RotationByVelocityModuleUI.cs +++ /dev/null @@ -1,97 +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; - - -namespace UnityEditor -{ - class RotationByVelocityModuleUI : ModuleUI - { - class Texts - { - public GUIContent velocityRange = EditorGUIUtility.TrTextContent("Speed Range", "Maps the speed to a value along the curve, when using one of the curve modes."); - public GUIContent rotation = EditorGUIUtility.TrTextContent("Angular Velocity", "Controls the angular velocity of each particle based on its speed."); - public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the angular velocity limit separately for each axis."); - public GUIContent x = EditorGUIUtility.TextContent("X"); - public GUIContent y = EditorGUIUtility.TextContent("Y"); - public GUIContent z = EditorGUIUtility.TextContent("Z"); - } - static Texts s_Texts; - SerializedMinMaxCurve m_X; - SerializedMinMaxCurve m_Y; - SerializedMinMaxCurve m_Z; - SerializedProperty m_SeparateAxes; - SerializedProperty m_Range; - - public RotationByVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "RotationBySpeedModule", displayName) - { - m_ToolTip = "Controls the angular velocity of each particle based on its speed."; - } - - protected override void Init() - { - // Already initialized? - if (m_Z != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_SeparateAxes = GetProperty("separateAxes"); - m_Range = GetProperty("range"); - m_X = new SerializedMinMaxCurve(this, s_Texts.x, "x", kUseSignedRange, false, m_SeparateAxes.boolValue); - m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", kUseSignedRange, false, m_SeparateAxes.boolValue); - m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "curve", kUseSignedRange); - m_X.m_RemapValue = Mathf.Rad2Deg; - m_Y.m_RemapValue = Mathf.Rad2Deg; - m_Z.m_RemapValue = Mathf.Rad2Deg; - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - EditorGUI.BeginChangeCheck(); - bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); - if (EditorGUI.EndChangeCheck()) - { - // Remove old curves from curve editor - if (!separateAxes) - { - m_X.RemoveCurveFromEditor(); - m_Y.RemoveCurveFromEditor(); - } - } - - // Keep states in sync - if (!m_Z.stateHasMultipleDifferentValues) - { - m_X.SetMinMaxState(m_Z.state, separateAxes); - m_Y.SetMinMaxState(m_Z.state, separateAxes); - } - - MinMaxCurveState state = m_Z.state; - - if (separateAxes) - { - m_Z.m_DisplayName = s_Texts.z; - GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); - } - else - { - m_Z.m_DisplayName = s_Texts.rotation; - GUIMinMaxCurve(s_Texts.rotation, m_Z); - } - - using (new EditorGUI.DisabledScope((state == MinMaxCurveState.k_Scalar) || (state == MinMaxCurveState.k_TwoScalars))) - { - GUIMinMaxRange(s_Texts.velocityRange, m_Range); - } - } - - override public void UpdateCullingSupportedString(ref string text) - { - text += "\nRotation by Speed module is enabled."; - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RotationModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RotationModuleUI.cs deleted file mode 100644 index 4108baa854..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/RotationModuleUI.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; - - -namespace UnityEditor -{ - class RotationModuleUI : ModuleUI - { - SerializedMinMaxCurve m_X; - SerializedMinMaxCurve m_Y; - SerializedMinMaxCurve m_Z; - SerializedProperty m_SeparateAxes; - - class Texts - { - public GUIContent rotation = EditorGUIUtility.TrTextContent("Angular Velocity", "Controls the angular velocity of each particle during its lifetime."); - public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the angular velocity limit separately for each axis."); - public GUIContent x = EditorGUIUtility.TextContent("X"); - public GUIContent y = EditorGUIUtility.TextContent("Y"); - public GUIContent z = EditorGUIUtility.TextContent("Z"); - } - static Texts s_Texts; - - - public RotationModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "RotationModule", displayName) - { - m_ToolTip = "Controls the angular velocity of each particle during its lifetime."; - } - - protected override void Init() - { - // Already initialized? - if (m_Z != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_SeparateAxes = GetProperty("separateAxes"); - m_X = new SerializedMinMaxCurve(this, s_Texts.x, "x", kUseSignedRange, false, m_SeparateAxes.boolValue); - m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", kUseSignedRange, false, m_SeparateAxes.boolValue); - m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "curve", kUseSignedRange); - m_X.m_RemapValue = Mathf.Rad2Deg; - m_Y.m_RemapValue = Mathf.Rad2Deg; - m_Z.m_RemapValue = Mathf.Rad2Deg; - } - - public override void OnInspectorGUI(InitialModuleUI initial) - { - EditorGUI.BeginChangeCheck(); - bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); - if (EditorGUI.EndChangeCheck()) - { - // Remove old curves from curve editor - if (!separateAxes) - { - m_X.RemoveCurveFromEditor(); - m_Y.RemoveCurveFromEditor(); - } - } - - // Keep states in sync - if (!m_Z.stateHasMultipleDifferentValues) - { - m_X.SetMinMaxState(m_Z.state, separateAxes); - m_Y.SetMinMaxState(m_Z.state, separateAxes); - } - - if (separateAxes) - { - m_Z.m_DisplayName = s_Texts.z; - GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); - } - else - { - m_Z.m_DisplayName = s_Texts.rotation; - GUIMinMaxCurve(s_Texts.rotation, m_Z); - } - } - - override public void UpdateCullingSupportedString(ref string text) - { - Init(); - - string failureReason = string.Empty; - if (!m_X.SupportsProcedural(ref failureReason)) - text += "\nRotation over Lifetime module curve X: " + failureReason; - - failureReason = string.Empty; - if (!m_Y.SupportsProcedural(ref failureReason)) - text += "\nRotation over Lifetime module curve Y: " + failureReason; - - failureReason = string.Empty; - if (!m_Z.SupportsProcedural(ref failureReason)) - text += "\nRotation over Lifetime module curve Z: " + failureReason; - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/SizeByVelocityModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/SizeByVelocityModuleUI.cs deleted file mode 100644 index bdd04329a0..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/SizeByVelocityModuleUI.cs +++ /dev/null @@ -1,94 +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; - - -namespace UnityEditor -{ - class SizeByVelocityModuleUI : ModuleUI - { - class Texts - { - public GUIContent velocityRange = EditorGUIUtility.TrTextContent("Speed Range", "Remaps speed in the defined range to a size."); - public GUIContent size = EditorGUIUtility.TrTextContent("Size", "Controls the size of each particle based on its speed."); - public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the angular velocity limit separately for each axis."); - public GUIContent x = new GUIContent("X"); - public GUIContent y = new GUIContent("Y"); - public GUIContent z = new GUIContent("Z"); - } - static Texts s_Texts; - - SerializedMinMaxCurve m_X; - SerializedMinMaxCurve m_Y; - SerializedMinMaxCurve m_Z; - SerializedProperty m_SeparateAxes; - SerializedProperty m_Range; - - public SizeByVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "SizeBySpeedModule", displayName) - { - m_ToolTip = "Controls the size of each particle based on its speed."; - } - - protected override void Init() - { - // Already initialized? - if (m_X != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_SeparateAxes = GetProperty("separateAxes"); - m_Range = GetProperty("range"); - - m_X = new SerializedMinMaxCurve(this, s_Texts.x, "curve"); // use "curve" instead of "x" for backwards compatibility reasons: the old system used to only support one axis, and this was its name - m_X.m_AllowConstant = false; - m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", false, false, m_SeparateAxes.boolValue); - m_Y.m_AllowConstant = false; - m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "z", false, false, m_SeparateAxes.boolValue); - m_Z.m_AllowConstant = false; - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - EditorGUI.BeginChangeCheck(); - bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); - if (EditorGUI.EndChangeCheck()) - { - // Remove old curves from curve editor - if (!separateAxes) - { - m_Y.RemoveCurveFromEditor(); - m_Z.RemoveCurveFromEditor(); - } - } - - // Keep states in sync - if (!m_X.stateHasMultipleDifferentValues) - { - m_Z.SetMinMaxState(m_X.state, separateAxes); - m_Y.SetMinMaxState(m_X.state, separateAxes); - } - - MinMaxCurveState state = m_Z.state; - - if (separateAxes) - { - m_X.m_DisplayName = s_Texts.x; - GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); - } - else - { - m_X.m_DisplayName = s_Texts.size; - GUIMinMaxCurve(s_Texts.size, m_X); - } - - using (new EditorGUI.DisabledScope((state == MinMaxCurveState.k_Scalar) || (state == MinMaxCurveState.k_TwoScalars))) - { - GUIMinMaxRange(s_Texts.velocityRange, m_Range); - } - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/SizeModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/SizeModuleUI.cs deleted file mode 100644 index dc650cdb85..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/SizeModuleUI.cs +++ /dev/null @@ -1,83 +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; - - -namespace UnityEditor -{ - class SizeModuleUI : ModuleUI - { - SerializedMinMaxCurve m_X; - SerializedMinMaxCurve m_Y; - SerializedMinMaxCurve m_Z; - SerializedProperty m_SeparateAxes; - - class Texts - { - public GUIContent size = EditorGUIUtility.TrTextContent("Size", "Controls the size of each particle during its lifetime."); - public GUIContent separateAxes = EditorGUIUtility.TrTextContent("Separate Axes", "If enabled, you can control the angular velocity limit separately for each axis."); - public GUIContent x = EditorGUIUtility.TextContent("X"); - public GUIContent y = EditorGUIUtility.TextContent("Y"); - public GUIContent z = EditorGUIUtility.TextContent("Z"); - } - static Texts s_Texts; - - public SizeModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) - : base(owner, o, "SizeModule", displayName) - { - m_ToolTip = "Controls the size of each particle during its lifetime."; - } - - protected override void Init() - { - // Already initialized? - if (m_X != null) - return; - if (s_Texts == null) - s_Texts = new Texts(); - - m_SeparateAxes = GetProperty("separateAxes"); - m_X = new SerializedMinMaxCurve(this, s_Texts.x, "curve"); - m_Y = new SerializedMinMaxCurve(this, s_Texts.y, "y", false, false, m_SeparateAxes.boolValue); - m_Z = new SerializedMinMaxCurve(this, s_Texts.z, "z", false, false, m_SeparateAxes.boolValue); - m_X.m_AllowConstant = false; - m_Y.m_AllowConstant = false; - m_Z.m_AllowConstant = false; - } - - override public void OnInspectorGUI(InitialModuleUI initial) - { - EditorGUI.BeginChangeCheck(); - bool separateAxes = GUIToggle(s_Texts.separateAxes, m_SeparateAxes); - if (EditorGUI.EndChangeCheck()) - { - // Remove old curves from curve editor - if (!separateAxes) - { - m_Y.RemoveCurveFromEditor(); - m_Z.RemoveCurveFromEditor(); - } - } - - // Keep states in sync - if (!m_X.stateHasMultipleDifferentValues) - { - m_Z.SetMinMaxState(m_X.state, separateAxes); - m_Y.SetMinMaxState(m_X.state, separateAxes); - } - - if (separateAxes) - { - m_X.m_DisplayName = s_Texts.x; - GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_X, s_Texts.y, m_Y, s_Texts.z, m_Z, null); - } - else - { - m_X.m_DisplayName = s_Texts.size; - GUIMinMaxCurve(s_Texts.size, m_X); - } - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/TrailModuleUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/TrailModuleUI.cs index d0db6cc3c1..bdb29270c0 100644 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/TrailModuleUI.cs +++ b/Editor/Mono/ParticleSystemEditor/ParticleSystemModules/TrailModuleUI.cs @@ -28,6 +28,7 @@ class Texts public GUIContent shadowBias = EditorGUIUtility.TrTextContent("Shadow Bias", "Apply a shadow bias to prevent self-shadowing artifacts. The specified value is the proportion of the trail width at each segment."); public GUIContent ribbonCount = EditorGUIUtility.TrTextContent("Ribbon Count", "Select how many ribbons to render throughout the Particle System."); public GUIContent splitSubEmitterRibbons = EditorGUIUtility.TrTextContent("Split Sub Emitter Ribbons", "When used on a sub emitter, ribbons will connect particles from each parent particle independently."); + public GUIContent attachRibbonsToTransform = EditorGUIUtility.TrTextContent("Attach Ribbons to Transform", "Connect each ribbon to the position of the Transform Component."); public GUIContent[] trailModeOptions = { @@ -62,6 +63,7 @@ class Texts SerializedProperty m_ShadowBias; SerializedProperty m_RibbonCount; SerializedProperty m_SplitSubEmitterRibbons; + SerializedProperty m_AttachRibbonsToTransform; public TrailModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "TrailModule", displayName) @@ -94,6 +96,7 @@ protected override void Init() m_ShadowBias = GetProperty("shadowBias"); m_RibbonCount = GetProperty("ribbonCount"); m_SplitSubEmitterRibbons = GetProperty("splitSubEmitterRibbons"); + m_AttachRibbonsToTransform = GetProperty("attachRibbonsToTransform"); } override public void OnInspectorGUI(InitialModuleUI initial) @@ -113,6 +116,7 @@ override public void OnInspectorGUI(InitialModuleUI initial) { GUIInt(s_Texts.ribbonCount, m_RibbonCount); GUIToggle(s_Texts.splitSubEmitterRibbons, m_SplitSubEmitterRibbons); + GUIToggle(s_Texts.attachRibbonsToTransform, m_AttachRibbonsToTransform); } } diff --git a/Editor/Mono/ParticleSystemEditor/ParticleSystemUI.cs b/Editor/Mono/ParticleSystemEditor/ParticleSystemUI.cs index 8fa5a25abb..6311362d91 100644 --- a/Editor/Mono/ParticleSystemEditor/ParticleSystemUI.cs +++ b/Editor/Mono/ParticleSystemEditor/ParticleSystemUI.cs @@ -427,7 +427,7 @@ void UpdateParticleSystemInfoString() if (supportsCullingText != m_SupportsCullingText || m_SupportsCullingTextLabel == null) { m_SupportsCullingText = supportsCullingText; - m_SupportsCullingTextLabel = "Automatic culling is disabled because: " + supportsCullingText.Replace("\n", "\n" + s_Texts.bulletPoint); + m_SupportsCullingTextLabel = "Procedural simulation is not supported because: " + supportsCullingText.Replace("\n", "\n" + s_Texts.bulletPoint); } } else diff --git a/Editor/Mono/ParticleSystemEditor/ScriptBindings/ParticleSystemEditor.bindings.cs b/Editor/Mono/ParticleSystemEditor/ScriptBindings/ParticleSystemEditor.bindings.cs deleted file mode 100644 index 3d2aca1d8c..0000000000 --- a/Editor/Mono/ParticleSystemEditor/ScriptBindings/ParticleSystemEditor.bindings.cs +++ /dev/null @@ -1,55 +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.Bindings; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - [NativeHeader("Runtime/ParticleSystem/ParticleSystem.h")] - [NativeHeader("Editor/Src/ParticleSystem/ParticleSystemEditor.h")] - [NativeHeader("ParticleSystemScriptingClasses.h")] - [StaticAccessor("ParticleSystemEditor", StaticAccessorType.DoubleColon)] - internal static class ParticleSystemEditorUtils - { - internal extern static float simulationSpeed { get; set; } - internal extern static float playbackTime { get; set; } - internal extern static bool playbackIsScrubbing { get; set; } - internal extern static bool playbackIsPlaying { get; set; } - internal extern static bool playbackIsPaused { get; set; } - internal extern static bool resimulation { get; set; } - internal extern static UInt32 previewLayers { get; set; } - internal extern static bool renderInSceneView { get; set; } - internal extern static ParticleSystem lockedParticleSystem { get; set; } - - [NativeName("SetPerformCompleteResimulation")] - extern internal static void PerformCompleteResimulation(); - - // Returns the root of the hierarchy of Particle Systems starting from 'ps'. - public static ParticleSystem GetRoot(ParticleSystem ps) - { - if (ps == null) - return null; - - Transform rootTransform = ps.transform; - while (rootTransform.parent && rootTransform.parent.gameObject.GetComponent() != null) - rootTransform = rootTransform.parent; - - return rootTransform.gameObject.GetComponent(); - } - } - - [NativeHeader("Runtime/ParticleSystem/ParticleSystem.h")] - [NativeHeader("Editor/Src/ParticleSystem/ParticleSystemEffect.h")] - [StaticAccessor("ParticleSystemEffect", StaticAccessorType.DoubleColon)] - internal static class ParticleSystemEffectUtils - { - extern internal static string CheckCircularReferences(ParticleSystem subEmitter); - - [NativeName("StopAndClearActive")] - extern internal static void StopEffect(); - } -} diff --git a/Editor/Mono/ParticleSystemEditor/SerializedMinMaxColor.cs b/Editor/Mono/ParticleSystemEditor/SerializedMinMaxColor.cs deleted file mode 100644 index 607fd4f501..0000000000 --- a/Editor/Mono/ParticleSystemEditor/SerializedMinMaxColor.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; - -namespace UnityEditor -{ - class SerializedMinMaxColor - { - public SerializedProperty maxColor; - public SerializedProperty minColor; - public SerializedProperty minMax; - - public SerializedMinMaxColor(SerializedModule m) - { - Init(m, "curve"); - } - - public SerializedMinMaxColor(SerializedModule m, string name) - { - Init(m, name); - } - - void Init(SerializedModule m, string name) - { - maxColor = m.GetProperty(name, "maxColor"); - minColor = m.GetProperty(name, "minColor"); - minMax = m.GetProperty(name, "minMax"); - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/SerializedMinMaxCurve.cs b/Editor/Mono/ParticleSystemEditor/SerializedMinMaxCurve.cs deleted file mode 100644 index 79a6d7d05a..0000000000 --- a/Editor/Mono/ParticleSystemEditor/SerializedMinMaxCurve.cs +++ /dev/null @@ -1,316 +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 -{ - // Must be in sync with ParticleSystemCurves.h - internal enum MinMaxCurveState - { - k_Scalar = 0, - k_Curve = 1, - k_TwoCurves = 2, - k_TwoScalars = 3 - }; - - internal class SerializedMinMaxCurve - { - public SerializedProperty rootProperty; - public SerializedProperty scalar; - public SerializedProperty minScalar; - public SerializedProperty maxCurve; - public SerializedProperty minCurve; - private SerializedProperty minMaxState; - - public ModuleUI m_Module; // Module that owns this SerializedMinMaxCurve - private string m_Name; // Curve name. Used for creating unique name based on ParticleSystem name + Module name + m_Name - public GUIContent m_DisplayName; - private bool m_SignedRange; // True if curve can have negative values - public float m_DefaultCurveScalar; // Used when switching to curve from scalar and scalar is 0. Ensures a valid y axis range (must be positive) - public float m_RemapValue; // Used for remap UI values e.g for rotation: state is in radians but we want UI to show it in degrees - public bool m_AllowConstant; - public bool m_AllowRandom; - public bool m_AllowCurves; - - public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName) - { - Init(m, displayName, "curve", false, false, true); - } - - public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, string name) - { - Init(m, displayName, name, false, false, true); - } - - public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, bool signedRange) - { - Init(m, displayName, "curve", signedRange, false, true); - } - - public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, string name, bool signedRange) - { - Init(m, displayName, name, signedRange, false, true); - } - - public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, string name, bool signedRange, bool useProp0) - { - Init(m, displayName, name, signedRange, useProp0, true); - } - - public SerializedMinMaxCurve(ModuleUI m, GUIContent displayName, string name, bool signedRange, bool useProp0, bool addCurveIfNeeded) - { - Init(m, displayName, name, signedRange, useProp0, addCurveIfNeeded); - } - - void Init(ModuleUI m, GUIContent displayName, string uniqueName, bool signedRange, bool useProp0, bool addCurveIfNeeded) - { - m_Module = m; - m_DisplayName = displayName; - m_Name = uniqueName; - m_SignedRange = signedRange; - m_RemapValue = 1.0f; - m_DefaultCurveScalar = 1.0f; - m_AllowConstant = true; - m_AllowRandom = true; - m_AllowCurves = true; - - rootProperty = useProp0 ? m.GetProperty0(m_Name) : m.GetProperty(m_Name); - scalar = useProp0 ? m.GetProperty0(m_Name, "scalar") : m.GetProperty(m_Name, "scalar"); - minScalar = useProp0 ? m.GetProperty0(m_Name, "minScalar") : m.GetProperty(m_Name, "minScalar"); - maxCurve = useProp0 ? m.GetProperty0(m_Name, "maxCurve") : m.GetProperty(m_Name, "maxCurve"); - minCurve = useProp0 ? m.GetProperty0(m_Name, "minCurve") : m.GetProperty(m_Name, "minCurve"); - minMaxState = useProp0 ? m.GetProperty0(m_Name, "minMaxState") : m.GetProperty(m_Name, "minMaxState"); - - // Reconstruct added curves when we initialize - if (addCurveIfNeeded) - { - if (state == MinMaxCurveState.k_Curve || state == MinMaxCurveState.k_TwoCurves) - { - if (m_Module.m_ParticleSystemUI.m_ParticleEffectUI.IsParticleSystemUIVisible(m_Module.m_ParticleSystemUI)) - m.GetParticleSystemCurveEditor().AddCurveDataIfNeeded(GetUniqueCurveName(), CreateCurveData(Color.black)); - } - } - m.AddToModuleCurves(maxCurve); // It is enough just to add max - } - - public MinMaxCurveState state - { - get { return (MinMaxCurveState)minMaxState.intValue; } - set { SetMinMaxState(value, true); } - } - - public bool stateHasMultipleDifferentValues - { - get { return minMaxState.hasMultipleDifferentValues; } - } - - public bool signedRange - { - get { return m_SignedRange; } - } - - public float maxConstant - { - get - { - return scalar.floatValue; - } - - set - { - if (!signedRange) - value = Mathf.Max(value, 0f); - - scalar.floatValue = value; - } - } - - public float minConstant - { - get - { - return minScalar.floatValue; - } - - set - { - if (!signedRange) - value = Mathf.Max(value, 0f); - - minScalar.floatValue = value; - } - } - - // Callback for Curve Editor to get axis labels - public Vector2 GetAxisScalars() - { - return new Vector2(m_Module.GetXAxisScalar(), scalar.floatValue * m_RemapValue); - } - - // Callback for Curve Editor to set axis labels back - public void SetAxisScalars(Vector2 axisScalars) - { - // X axis: TODO: We do not support changing the X values in the curve editor yet - //m_Module.SetXAxisScalar (axisScalars.x); - - // Y axis: - float remap = (m_RemapValue == 0.0f) ? 1.0f : m_RemapValue; - scalar.floatValue = (axisScalars.y / remap); - } - - public void RemoveCurveFromEditor() - { - ParticleSystemCurveEditor sce = m_Module.GetParticleSystemCurveEditor(); - if (sce.IsAdded(GetMinCurve(), maxCurve)) - sce.RemoveCurve(GetMinCurve(), maxCurve); - } - - public bool OnCurveAreaMouseDown(int button, Rect drawRect, Rect curveRanges) - { - if (button == 0) - { - ToggleCurveInEditor(); - return true; - } - - if (button == 1) - { - SerializedProperty minCurve = GetMinCurve(); - AnimationCurveContextMenu.Show(drawRect, - maxCurve != null ? maxCurve.Copy() : null, - minCurve != null ? minCurve.Copy() : null, - scalar != null ? scalar.Copy() : null, - curveRanges, m_Module.GetParticleSystemCurveEditor()); - return true; - } - - return false; - } - - public ParticleSystemCurveEditor.CurveData CreateCurveData(Color color) - { - System.Diagnostics.Debug.Assert(state != MinMaxCurveState.k_Scalar); // We should not create curve data for scalars - - return new ParticleSystemCurveEditor.CurveData(GetUniqueCurveName(), m_DisplayName, GetMinCurve(), maxCurve, color, m_SignedRange, GetAxisScalars, SetAxisScalars, m_Module.foldout); - } - - SerializedProperty GetMinCurve() - { - return state == MinMaxCurveState.k_TwoCurves ? minCurve : null; - } - - public void ToggleCurveInEditor() - { - ParticleSystemCurveEditor sce = m_Module.GetParticleSystemCurveEditor(); - if (sce.IsAdded(GetMinCurve(), maxCurve)) - sce.RemoveCurve(GetMinCurve(), maxCurve); - else - sce.AddCurve(CreateCurveData(sce.GetAvailableColor())); - } - - public void SetMinMaxState(MinMaxCurveState newState, bool addToCurveEditor) - { - if (newState == state) - return; - - MinMaxCurveState oldState = state; - ParticleSystemCurveEditor sce = m_Module.GetParticleSystemCurveEditor(); - - if (sce.IsAdded(GetMinCurve(), maxCurve)) - { - sce.RemoveCurve(GetMinCurve(), maxCurve); - } - - switch (newState) - { - case MinMaxCurveState.k_Curve: SetCurveRequirements(); break; - case MinMaxCurveState.k_TwoCurves: SetCurveRequirements(); break; - } - - // Assign state AFTER matching data to new state AND removing curve from curveEditor since it uses current 'state' - minMaxState.intValue = (int)newState; - - if (addToCurveEditor) - { - // Add curve to CurveEditor if needed - // Keep added to the editor if it was added before - switch (newState) - { - case MinMaxCurveState.k_TwoCurves: - case MinMaxCurveState.k_Curve: - sce.AddCurve(CreateCurveData(sce.GetAvailableColor())); - break; - case MinMaxCurveState.k_Scalar: - case MinMaxCurveState.k_TwoScalars: - // Scalar do not add anything to the curve editor - break; - default: - Debug.LogError("Unhandled enum value"); - break; - } - } - - // Ensure we draw new icons for properties - UnityEditorInternal.AnimationCurvePreviewCache.ClearCache(); - } - - void SetCurveRequirements() - { - // Abs negative values if we change to curve mode (in curve mode the sign is transfered to the curve) - scalar.floatValue = Mathf.Abs(scalar.floatValue); - - // Ensure proper y-axis value (0 does not create a valid range) - if (scalar.floatValue == 0) - scalar.floatValue = m_DefaultCurveScalar; - } - - public string GetUniqueCurveName() - { - return SerializedModule.Concat(m_Module.GetUniqueModuleName(m_Module.serializedObject.targetObject), m_Name); - } - - static bool AnimationCurveSupportsProcedural(AnimationCurve curve, ref string failureReason) - { - switch (AnimationUtility.IsValidPolynomialCurve(curve)) - { - case AnimationUtility.PolynomialValid.Valid: - return true; - case AnimationUtility.PolynomialValid.InvalidPreWrapMode: - failureReason = "Unsupported curve pre-wrap mode. Loop and ping-pong do not support procedural mode."; - break; - case AnimationUtility.PolynomialValid.InvalidPostWrapMode: - failureReason = "Unsupported curve post-wrap mode. Loop and ping-pong do not support procedural mode."; - break; - case AnimationUtility.PolynomialValid.TooManySegments: - failureReason = "Curve uses too many keys. Procedural mode does not support more than " + AnimationUtility.GetMaxNumPolynomialSegmentsSupported() + " keys"; - if (curve.keys[0].time != 0.0f || curve.keys[curve.keys.Length - 1].time != 1.0f) - failureReason += " (Additional keys are added to curves that do not start at 0, or do not end at 1)"; - failureReason += "."; - break; - } - return false; - } - - public bool SupportsProcedural(ref string failureReason) - { - string maxCurveFailureReason = "Max Curve: "; - bool isMaxCurveValid = AnimationCurveSupportsProcedural(maxCurve.animationCurveValue, ref maxCurveFailureReason); - if (!isMaxCurveValid) - failureReason = maxCurveFailureReason; - - if ((state != MinMaxCurveState.k_TwoCurves) && (state != MinMaxCurveState.k_TwoScalars)) - return isMaxCurveValid; - else - { - string minCurveFailureReason = "Min Curve: "; - bool isMinCurveValid = AnimationCurveSupportsProcedural(minCurve.animationCurveValue, ref minCurveFailureReason); - if (isMinCurveValid) - failureReason += minCurveFailureReason; - return isMaxCurveValid && isMinCurveValid; - } - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/ParticleSystemEditor/SerializedMinMaxGradient.cs b/Editor/Mono/ParticleSystemEditor/SerializedMinMaxGradient.cs deleted file mode 100644 index 46af69c0ce..0000000000 --- a/Editor/Mono/ParticleSystemEditor/SerializedMinMaxGradient.cs +++ /dev/null @@ -1,95 +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; - - -namespace UnityEditor -{ - // Must be in sync with enum in ParticleSystemCurves.h - internal enum MinMaxGradientState - { - k_Color = 0, - k_Gradient = 1, - k_RandomBetweenTwoColors = 2, - k_RandomBetweenTwoGradients = 3, - k_RandomColor = 4 - }; - - internal class SerializedMinMaxGradient - { - public SerializedProperty m_RootProperty; - public SerializedProperty m_MaxGradient; - public SerializedProperty m_MinGradient; - public SerializedProperty m_MaxColor; - public SerializedProperty m_MinColor; - private SerializedProperty m_MinMaxState; - - public bool m_AllowColor; - public bool m_AllowGradient; - public bool m_AllowRandomBetweenTwoColors; - public bool m_AllowRandomBetweenTwoGradients; - public bool m_AllowRandomColor; - - public MinMaxGradientState state - { - get { return (MinMaxGradientState)m_MinMaxState.intValue; } - set { SetMinMaxState(value); } - } - - public bool stateHasMultipleDifferentValues - { - get { return m_MinMaxState.hasMultipleDifferentValues; } - } - - public SerializedMinMaxGradient(SerializedModule m) - { - Init(m, "gradient"); - } - - public SerializedMinMaxGradient(SerializedModule m, string name) - { - Init(m, name); - } - - void Init(SerializedModule m, string name) - { - m_RootProperty = m.GetProperty(name); - m_MaxGradient = m.GetProperty(name, "maxGradient"); - m_MinGradient = m.GetProperty(name, "minGradient"); - m_MaxColor = m.GetProperty(name, "maxColor"); - m_MinColor = m.GetProperty(name, "minColor"); - m_MinMaxState = m.GetProperty(name, "minMaxState"); - - m_AllowColor = true; - m_AllowGradient = true; - m_AllowRandomBetweenTwoColors = true; - m_AllowRandomBetweenTwoGradients = true; - m_AllowRandomColor = false; - } - - private void SetMinMaxState(MinMaxGradientState newState) - { - if (newState == state) - return; - - m_MinMaxState.intValue = (int)newState; - } - - public static Color GetGradientAsColor(SerializedProperty gradientProp) - { - Gradient gradient = gradientProp.gradientValue; - return gradient.constantColor; - } - - public static void SetGradientAsColor(SerializedProperty gradientProp, Color color) - { - Gradient gradient = gradientProp.gradientValue; - gradient.constantColor = color; - - // We have changed a gradient so clear preview cache - UnityEditorInternal.GradientPreviewCache.ClearCache(); - } - } -} // namespace UnityEditor diff --git a/Editor/Mono/PerformanceTools/FrameDebugger.cs b/Editor/Mono/PerformanceTools/FrameDebugger.cs index e7501eb423..2cca28353c 100644 --- a/Editor/Mono/PerformanceTools/FrameDebugger.cs +++ b/Editor/Mono/PerformanceTools/FrameDebugger.cs @@ -127,7 +127,7 @@ internal struct FrameDebuggerEventData public int subShaderIndex; public int shaderPassIndex; public string shaderKeywords; - public int rendererInstanceID; + public int componentInstanceID; public Mesh mesh; public int meshInstanceID; public int meshSubset; diff --git a/Editor/Mono/PerformanceTools/FrameDebuggerTreeView.cs b/Editor/Mono/PerformanceTools/FrameDebuggerTreeView.cs deleted file mode 100644 index 6236993bb5..0000000000 --- a/Editor/Mono/PerformanceTools/FrameDebuggerTreeView.cs +++ /dev/null @@ -1,272 +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.Collections.Generic; -using UnityEngine; -using UnityEditor; -using System.Globalization; -using UnityEditor.IMGUI.Controls; - - -namespace UnityEditorInternal -{ - internal class FrameDebuggerTreeView - { - internal readonly TreeViewController m_TreeView; - internal FDTreeViewDataSource m_DataSource; - private readonly FrameDebuggerWindow m_FrameDebugger; - - public FrameDebuggerTreeView(FrameDebuggerEvent[] frameEvents, TreeViewState treeViewState, FrameDebuggerWindow window, Rect startRect) - { - m_FrameDebugger = window; - m_TreeView = new TreeViewController(window, treeViewState); - m_DataSource = new FDTreeViewDataSource(m_TreeView, frameEvents); - var gui = new FDTreeViewGUI(m_TreeView); - m_TreeView.Init(startRect, m_DataSource, gui, null); - m_TreeView.ReloadData(); - m_TreeView.selectionChangedCallback += SelectionChanged; - } - - void SelectionChanged(int[] selectedIDs) - { - if (selectedIDs.Length < 1) - return; - int id = selectedIDs[0]; - int eventIndex = id; - - // For tree hierarchy nodes, their IDs are not the frame event indices; - // fetch the ID from the node itself in that case. - // IDs for hierarchy nodes are negative and need to stay consistently ordered so - // that tree expanded state behaves well when something in the scene changes. - // - // When selecting a hierarchy node, we want it's last child event to be set as the limit, - // so that rendered state corresponds to "everything up to and including this whole sub-tree". - if (eventIndex <= 0) - { - var item = m_TreeView.FindItem(id) as FDTreeViewItem; - if (item != null) - eventIndex = item.m_EventIndex; - } - // If still has no valid ID, do nothing. - if (eventIndex <= 0) - return; - m_FrameDebugger.ChangeFrameEventLimit(eventIndex); - } - - public void SelectFrameEventIndex(int eventIndex) - { - // Check if we'd end up selecting same "frame event": - // different tree nodes could result in the same frame debugger event - // limit, e.g. a hierarchy node sets last child event as the limit. - // If the limit event is the same, then do not change the currently selected item. - int[] selection = m_TreeView.GetSelection(); - if (selection.Length > 0) - { - var item = m_TreeView.FindItem(selection[0]) as FDTreeViewItem; - if (item != null && eventIndex == item.m_EventIndex) - return; - } - - m_TreeView.SetSelection(new[] { eventIndex }, true); - } - - public void OnGUI(Rect rect) - { - var keyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); - m_TreeView.OnGUI(rect, keyboardControlID); - } - - // Item for TreeView - // ID is different for leaf nodes (actual frame events) vs hierarchy nodes (parent profiler nodes): - // - leaf node IDs are frame event indices (always > 0). - // - hierarchy node IDs are always negative; to get frame event index we want we need to lookup the node and get it from m_EventIndex. - private class FDTreeViewItem : TreeViewItem - { - public FrameDebuggerEvent m_FrameEvent; - public int m_ChildEventCount; - public int m_EventIndex; - public FDTreeViewItem(int id, int depth, FDTreeViewItem parent, string displayName) - : base(id, depth, parent, displayName) - { - m_EventIndex = id; - } - } - - // GUI for TreeView - - private class FDTreeViewGUI : TreeViewGUI - { - const float kSmallMargin = 4; - - public FDTreeViewGUI(TreeViewController treeView) - : base(treeView) - { - } - - protected override Texture GetIconForItem(TreeViewItem item) - { - return null; - } - - protected override void OnContentGUI(Rect rect, int row, TreeViewItem itemRaw, string label, bool selected, bool focused, bool useBoldFont, bool isPinging) - { - if (Event.current.type != EventType.Repaint) - return; - - var item = (FDTreeViewItem)itemRaw; - - // indent - float indent = GetContentIndent(item); - rect.x += indent; - rect.width -= indent; - - string text; - GUIContent gc; - GUIStyle style; - - // child event count - if (item.m_ChildEventCount > 0) - { - Rect r = rect; - r.width -= kSmallMargin; - text = item.m_ChildEventCount.ToString(CultureInfo.InvariantCulture); - gc = EditorGUIUtility.TempContent(text); - style = FrameDebuggerWindow.styles.rowTextRight; - style.Draw(r, gc, false, false, false, false); - // reduce width of available space for the name, so that it does not overlap event count - rect.width -= style.CalcSize(gc).x + kSmallMargin * 2; - } - - // draw event name - if (item.id <= 0) - text = item.displayName; // hierarchy item - else - text = FrameDebuggerWindow.s_FrameEventTypeNames[(int)item.m_FrameEvent.type] + item.displayName; // leaf event - if (string.IsNullOrEmpty(text)) - text = ""; - gc = EditorGUIUtility.TempContent(text); - style = FrameDebuggerWindow.styles.rowText; - style.Draw(rect, gc, false, false, false, selected && focused); - } - - protected override void RenameEnded() - { - } - } - - // Data source for TreeView - - internal class FDTreeViewDataSource : TreeViewDataSource - { - private FrameDebuggerEvent[] m_FrameEvents; - - public FDTreeViewDataSource(TreeViewController treeView, FrameDebuggerEvent[] frameEvents) - : base(treeView) - { - m_FrameEvents = frameEvents; - rootIsCollapsable = false; - showRootItem = false; - } - - public void SetEvents(FrameDebuggerEvent[] frameEvents) - { - var wasEmpty = m_FrameEvents == null || m_FrameEvents.Length < 1; - - m_FrameEvents = frameEvents; - m_NeedRefreshRows = true; - ReloadData(); - - // Only expand whole events tree if it was empty before. - // If we already had something in there, we want to preserve user's expanded items. - if (wasEmpty) - SetExpandedWithChildren(m_RootItem, true); - } - - public override bool IsRenamingItemAllowed(TreeViewItem item) - { - return false; - } - - public override bool CanBeMultiSelected(TreeViewItem item) - { - return false; - } - - // Used while building the tree data source; represents current tree hierarchy level - private class FDTreeHierarchyLevel - { - internal readonly FDTreeViewItem item; - internal readonly List children; - internal FDTreeHierarchyLevel(int depth, int id, string name, FDTreeViewItem parent) - { - item = new FDTreeViewItem(id, depth, parent, name); - children = new List(); - } - } - private static void CloseLastHierarchyLevel(List eventStack, int prevFrameEventIndex) - { - var idx = eventStack.Count - 1; - eventStack[idx].item.children = eventStack[idx].children; - eventStack[idx].item.m_EventIndex = prevFrameEventIndex; - if (eventStack[idx].item.parent != null) - ((FDTreeViewItem)eventStack[idx].item.parent).m_ChildEventCount += eventStack[idx].item.m_ChildEventCount; - eventStack.RemoveAt(idx); - } - - public override void FetchData() - { - var rootLevel = new FDTreeHierarchyLevel(0, 0, string.Empty, null); - - // Hierarchy levels of a tree being built - var eventStack = new List(); - eventStack.Add(rootLevel); - - int hierarchyIDCounter = -1; - for (var i = 0; i < m_FrameEvents.Length; ++i) - { - // This will be a slash-delimited string, e.g. Foo/Bar/Baz. - // Add "/" in front to account for the single (invisible) root item - // that the TreeView always has. - string context = "/" + (FrameDebuggerUtility.GetFrameEventInfoName(i) ?? string.Empty); - string[] names = context.Split('/'); - // find matching hierarchy level - int level = 0; - while (level < eventStack.Count && level < names.Length) - { - if (names[level] != eventStack[level].item.displayName) - break; - ++level; - } - // close all the further levels from previous events in the stack - while (eventStack.Count > 0 && eventStack.Count > level) - { - CloseLastHierarchyLevel(eventStack, i); - } - // add all further levels for current event - for (var j = level; j < names.Length; ++j) - { - var parent = eventStack[eventStack.Count - 1]; - var newLevel = new FDTreeHierarchyLevel(eventStack.Count - 1, --hierarchyIDCounter, names[j], parent.item); - parent.children.Add(newLevel.item); - eventStack.Add(newLevel); - } - // add leaf event to current level - var eventGo = FrameDebuggerUtility.GetFrameEventGameObject(i); - var displayName = eventGo ? " " + eventGo.name : string.Empty; - FDTreeHierarchyLevel parentEvent = eventStack[eventStack.Count - 1]; - var leafEventID = i + 1; - var item = new FDTreeViewItem(leafEventID, eventStack.Count - 1, parentEvent.item, displayName); - item.m_FrameEvent = m_FrameEvents[i]; - parentEvent.children.Add(item); - ++parentEvent.item.m_ChildEventCount; - } - while (eventStack.Count > 0) - { - CloseLastHierarchyLevel(eventStack, m_FrameEvents.Length); - } - m_RootItem = rootLevel.item; - } - } - } -} diff --git a/Editor/Mono/PlatformSupport/ReorderableTextureList.cs b/Editor/Mono/PlatformSupport/ReorderableTextureList.cs deleted file mode 100644 index 1f09c608d9..0000000000 --- a/Editor/Mono/PlatformSupport/ReorderableTextureList.cs +++ /dev/null @@ -1,159 +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 UnityEditor; -using System; -using System.Collections; -using System.Collections.Generic; -using UnityEditorInternal; - -namespace UnityEditor.PlatformSupport -{ - class ReorderableIconLayerList - { - UnityEditorInternal.ReorderableList m_List; - - public delegate void ChangedCallbackDelegate(ReorderableIconLayerList list); - - // Used to notify about element order and content changes. The textures list - // must not be changed during the execution of the callback. - public ChangedCallbackDelegate onChangedCallback = null; - - public List textures - { - get { return (List)m_List.list; } - set { m_List.list = value; } - } - - public List previewTextures { get; set; } - - public string headerString = ""; - - const int kSlotSize = 86; - const int kIconSpacing = 6; - - public int m_ImageWidth = 20; - public int m_ImageHeight = 20; - public int minItems = 1; - public int maxItems = 5; - - - public void SetElementLabels(params string[] labels) - { - m_useCustomLayerLabel = true; - m_layerLabels = labels; - } - - private bool m_useCustomLayerLabel; - private string[] m_layerLabels; - - string GetElementLabel(int index) - { - if (m_useCustomLayerLabel) - return m_layerLabels[index]; - - string namestr = LocalizationDatabase.GetLocalizedString("Layer {0}"); - string label = String.Format(namestr, index); - - return label; - } - - public ReorderableIconLayerList(bool draggable = true, bool showControls = true) - { - m_List = new UnityEditorInternal.ReorderableList(new List(), typeof(Texture2D), draggable, true, showControls, showControls); - m_List.onAddCallback = OnAdd; - m_List.onRemoveCallback = OnRemove; - m_List.onReorderCallback = OnChange; - m_List.drawElementCallback = OnElementDraw; - m_List.drawHeaderCallback = OnHeaderDraw; - m_List.onCanAddCallback = OnCanAdd; - m_List.onCanRemoveCallback = OnCanRemove; - - UpdateElementHeight(); - } - - public void SetImageSize(int width, int height) - { - m_ImageWidth = width; - m_ImageHeight = height; - UpdateElementHeight(); - } - - void UpdateElementHeight() - { - m_List.elementHeight = kSlotSize * ((float)m_ImageHeight / m_ImageWidth); - } - - bool OnCanAdd(UnityEditorInternal.ReorderableList list) - { - return list.count < maxItems; - } - - bool OnCanRemove(UnityEditorInternal.ReorderableList list) - { - if (list.count <= minItems) - return false; - return true; - } - - void OnAdd(UnityEditorInternal.ReorderableList list) - { - textures.Add(null); - m_List.index = textures.Count - 1; - OnChange(list); - } - - void OnRemove(UnityEditorInternal.ReorderableList list) - { - textures.RemoveAt(list.index); - list.index = 0; - OnChange(list); - } - - void OnChange(UnityEditorInternal.ReorderableList list) - { - if (onChangedCallback != null) - onChangedCallback(this); - } - - void OnElementDraw(Rect rect, int index, bool isActive, bool isFocused) - { - string label = GetElementLabel(index); - - float width = Mathf.Min(rect.width, EditorGUIUtility.labelWidth + 4 + kSlotSize + kIconSpacing); - GUI.Label(new Rect(rect.x, rect.y, width - kSlotSize - kIconSpacing, 20), label); - - // Texture slot - int slotWidth = kSlotSize; - int slotHeight = (int)((float)m_ImageHeight / m_ImageWidth * kSlotSize); // take into account the aspect ratio - var textureRect = new Rect(rect.x + rect.width - slotWidth - slotWidth - kIconSpacing, rect.y, slotWidth, slotHeight); - - EditorGUI.BeginChangeCheck(); - textures[index] = (Texture2D)EditorGUI.ObjectField(textureRect, textures[index], typeof(Texture2D), false); - if (EditorGUI.EndChangeCheck()) - OnChange(m_List); - - // Preview - Rect previewRect = new Rect(rect.x + rect.width - slotWidth, rect.y, slotWidth, slotHeight); - - GUI.Box(previewRect, ""); - - Texture2D closestIcon = previewTextures[index]; - - if (closestIcon != null) - GUI.DrawTexture(PlatformIconField.GetContentRect(previewRect, 1, 1), previewTextures[index]); - } - - void OnHeaderDraw(Rect rect) - { - GUI.Label(rect, LocalizationDatabase.GetLocalizedString(headerString), EditorStyles.label); - } - - public void DoLayoutList() - { - m_List.DoLayoutList(); - } - } -} // namespace UnityEditor.AppleTV diff --git a/Editor/Mono/Playables/Playables.bindings.cs b/Editor/Mono/Playables/Playables.bindings.cs deleted file mode 100644 index c34fc288d1..0000000000 --- a/Editor/Mono/Playables/Playables.bindings.cs +++ /dev/null @@ -1,34 +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.Bindings; -using UnityEngine.Playables; -using UnityEngine.Scripting; - -namespace UnityEditor.Playables -{ - [NativeHeader("Editor/Src/Playables/Playables.bindings.h")] - static public class Utility - { - static public event Action graphCreated; - static public event Action destroyingGraph; - - [RequiredByNativeCode] - static private void OnPlayableGraphCreated(PlayableGraph graph) - { - if (graphCreated != null) - graphCreated(graph); - } - - [RequiredByNativeCode] - static private void OnDestroyingPlayableGraph(PlayableGraph graph) - { - if (destroyingGraph != null) - destroyingGraph(graph); - } - - extern static public PlayableGraph[] GetAllGraphs(); - } -} diff --git a/Editor/Mono/PlayerConnectionLogReceiver.cs b/Editor/Mono/PlayerConnectionLogReceiver.cs deleted file mode 100644 index 8631666802..0000000000 --- a/Editor/Mono/PlayerConnectionLogReceiver.cs +++ /dev/null @@ -1,92 +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 UnityEditor; -using UnityEditorInternal; -using System.Linq; -using UnityEngine.Networking.PlayerConnection; -using UnityEditor.Networking.PlayerConnection; - -namespace UnityEditor -{ - internal class PlayerConnectionLogReceiver : ScriptableSingleton - { - static Guid logMessageId { get { return new Guid("394ada03-8ba0-4f26-b001-1a6cdeb05a62"); } } - static Guid cleanLogMessageId { get { return new Guid("3ded2dda-cdf2-46d8-a3f6-01741741e7a9"); } } - const string prefsKey = "PlayerConnectionLoggingState"; - - internal enum ConnectionState - { - Disconnected, - CleanLog, - FullLog - } - - [SerializeField] - ConnectionState state = ConnectionState.Disconnected; - - void OnEnable() - { - State = (ConnectionState)EditorPrefs.GetInt(prefsKey, (int)ConnectionState.CleanLog); - } - - internal ConnectionState State - { - get - { - return state; - } - set - { - if (state == value) - return; - - switch (state) - { - case ConnectionState.CleanLog: - EditorConnection.instance.Unregister(cleanLogMessageId, LogMessage); - break; - - case ConnectionState.FullLog: - EditorConnection.instance.Unregister(logMessageId, LogMessage); - break; - } - state = value; - switch (state) - { - case ConnectionState.CleanLog: - EditorConnection.instance.Register(cleanLogMessageId, LogMessage); - break; - - case ConnectionState.FullLog: - EditorConnection.instance.Register(logMessageId, LogMessage); - break; - } - EditorPrefs.SetInt(prefsKey, (int)state); - } - } - - void LogMessage(MessageEventArgs messageEventArgs) - { - var body = messageEventArgs.data.Skip(4).ToArray(); - string text = System.Text.Encoding.UTF8.GetString(body); - - var logType = (LogType)messageEventArgs.data[0]; - if (!Enum.IsDefined(typeof(LogType), logType)) - logType = LogType.Log; - var oldStackTraceType = Application.GetStackTraceLogType(logType); - - // We don't want stack traces from editor code in player log messages. - Application.SetStackTraceLogType(logType, StackTraceLogType.None); - - string name = ProfilerDriver.GetConnectionIdentifier(messageEventArgs.playerId); - - text = "" + name + " " + text; - Debug.unityLogger.Log(logType, text); - Application.SetStackTraceLogType(logType, oldStackTraceType); - } - } -} diff --git a/Editor/Mono/PlayerSettings.bindings.cs b/Editor/Mono/PlayerSettings.bindings.cs index 9f9d15dda8..fb1edb4611 100644 --- a/Editor/Mono/PlayerSettings.bindings.cs +++ b/Editor/Mono/PlayerSettings.bindings.cs @@ -1098,5 +1098,11 @@ public static extern bool enableMetalAPIValidation [StaticAccessor("GetPlayerSettings().GetEditorOnly()")] internal static extern bool RelaunchProjectIfScriptRuntimeVersionHasChanged(); + + [StaticAccessor("GetPlayerSettings()")] + public static extern bool GetWsaHolographicRemotingEnabled(); + + [StaticAccessor("GetPlayerSettings()")] + public static extern void SetWsaHolographicRemotingEnabled(bool enabled); } } diff --git a/Editor/Mono/PlayerSettingsAndroid.bindings.cs b/Editor/Mono/PlayerSettingsAndroid.bindings.cs index dc0c0acbec..e904f27cff 100644 --- a/Editor/Mono/PlayerSettingsAndroid.bindings.cs +++ b/Editor/Mono/PlayerSettingsAndroid.bindings.cs @@ -67,6 +67,9 @@ public enum AndroidSdkVersions // Android 8.1, "Oreo", API level 27 AndroidApiLevel27 = 27, + + // Android 9.0, "Pie", API level 28 + AndroidApiLevel28 = 28, } // Preferred application install location @@ -396,14 +399,6 @@ public static extern bool startInFullscreen [NativeMethod("SetAndroidStartInFullscreen")] set; } - - public static extern int jvmMaxHeapSize - { - [NativeMethod("GetAndroidJvmMaxHeapSize")] - get; - [NativeMethod("SetAndroidJvmMaxHeapSize")] - set; - } } } } diff --git a/Editor/Mono/PlayerSettingsMacOS.bindings.cs b/Editor/Mono/PlayerSettingsMacOS.bindings.cs deleted file mode 100644 index cae03b1091..0000000000 --- a/Editor/Mono/PlayerSettingsMacOS.bindings.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; -using UnityEngine.Bindings; - -namespace UnityEditor -{ - public partial class PlayerSettings : UnityEngine.Object - { - [NativeHeader("Runtime/Misc/PlayerSettings.h")] - [StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)] - public class macOS - { - public static string buildNumber - { - get { return PlayerSettings.GetBuildNumber(BuildTargetGroup.Standalone); } - set { PlayerSettings.SetBuildNumber(BuildTargetGroup.Standalone, value); } - } - - [NativeProperty("MacAppStoreCategory")] - extern internal static string applicationCategoryType { get; set; } - } - } -} diff --git a/Editor/Mono/PlayerSettingsSplashScreen.cs b/Editor/Mono/PlayerSettingsSplashScreen.cs deleted file mode 100644 index 8cf3e3b99d..0000000000 --- a/Editor/Mono/PlayerSettingsSplashScreen.cs +++ /dev/null @@ -1,31 +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 -{ - public partial class PlayerSettings : UnityEngine.Object - { - public partial class SplashScreen - { - public enum AnimationMode - { - Static = 0, - Dolly = 1, - Custom = 2 - } - - public enum DrawMode - { - UnityLogoBelow = 0, - AllSequential = 1 - } - - public enum UnityLogoStyle - { - DarkOnLight = 0, - LightOnDark = 1 - } - } - } -} diff --git a/Editor/Mono/PlayerSettingsSwitch.bindings.cs b/Editor/Mono/PlayerSettingsSwitch.bindings.cs index f435d72098..076266ecd8 100644 --- a/Editor/Mono/PlayerSettingsSwitch.bindings.cs +++ b/Editor/Mono/PlayerSettingsSwitch.bindings.cs @@ -49,7 +49,8 @@ public enum Languages Korean, } - public enum StartupUserAccount + public enum + StartupUserAccount { None = 0, Required = 1, @@ -367,6 +368,9 @@ extern public static string[] localCommunicationIds [NativeProperty("switchDataLossConfirmation", TargetType.Field)] extern public static bool isDataLossConfirmationEnabled { get; set; } + [NativeProperty("switchUserAccountLockEnabled", TargetType.Field)] + extern public static bool isUserAccountLockEnabled { get; set; } + [Obsolete("isDataLossConfirmation was renamed to isDataLossConfirmationEnabled")] [NativeProperty("switchDataLossConfirmation", TargetType.Field)] extern public static bool isDataLossConfirmation { get; set; } diff --git a/Editor/Mono/PluginDesc.cs b/Editor/Mono/PluginDesc.cs deleted file mode 100644 index 6d859b998d..0000000000 --- a/Editor/Mono/PluginDesc.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 UnityEngine; -using UnityEditor; - -namespace UnityEditorInternal -{ - internal struct PluginDesc - { - public string pluginPath; - public CPUArch architecture; - } - - internal enum CPUArch - { - Any, - x86, - ARMv7 - } -} diff --git a/Editor/Mono/Plugins/PluginsHelper.cs b/Editor/Mono/Plugins/PluginsHelper.cs deleted file mode 100644 index 764f85c5e5..0000000000 --- a/Editor/Mono/Plugins/PluginsHelper.cs +++ /dev/null @@ -1,35 +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.Modules; -using UnityEngine; -using UnityEditor; - -namespace UnityEditorInternal -{ - internal class PluginsHelper - { - public static bool CheckFileCollisions(BuildTarget buildTarget) - { - // Checks that plugins don't collide with each other - IPluginImporterExtension pluginImporterExtension = null; - if (ModuleManager.IsPlatformSupported(buildTarget)) - pluginImporterExtension = ModuleManager.GetPluginImporterExtension(buildTarget); - if (pluginImporterExtension == null) - { - // Some platforms don't have platform specific settings for plugins, but we still wan't to check that plugins don't collide, use default path in this case - if (BuildPipeline.GetBuildTargetGroup(buildTarget) == BuildTargetGroup.Standalone) - pluginImporterExtension = new DesktopPluginImporterExtension(); - else - pluginImporterExtension = new DefaultPluginImporterExtension(null); - } - - if (pluginImporterExtension.CheckFileCollisions(BuildPipeline.GetBuildTargetName(buildTarget))) - return true; - - return false; - } - } -} diff --git a/Editor/Mono/Prefabs/PrefabImporterEditor.cs b/Editor/Mono/Prefabs/PrefabImporterEditor.cs index b5cc37005b..d95d7175aa 100644 --- a/Editor/Mono/Prefabs/PrefabImporterEditor.cs +++ b/Editor/Mono/Prefabs/PrefabImporterEditor.cs @@ -15,6 +15,8 @@ internal class PrefabImporterEditor : AssetImporterEditor { static GUIContent s_OpenContent = EditorGUIUtility.TrTextContent("Open Prefab"); static GUIContent s_BaseContent = EditorGUIUtility.TrTextContent("Base"); + static string s_LocalizedTitleMultiplePrefabs = L10n.Tr("Prefab Assets"); + static string s_LocalizedTitleSinglePrefab = L10n.Tr("Prefab Asset"); int m_HasMixedBaseVariants = -1; @@ -41,6 +43,17 @@ void CacheHasMixedBaseVariants() public override bool showImportedObject { get { return false; } } + internal override string targetTitle + { + get + { + if (assetTargets == null || assetTargets.Length == 1 || !m_AllowMultiObjectAccess) + return assetTarget != null ? assetTarget.name : s_LocalizedTitleSinglePrefab; + else + return assetTargets.Length + " " + s_LocalizedTitleMultiplePrefabs; + } + } + internal override void OnHeaderControlsGUI() { var variantBase = PrefabUtility.GetCorrespondingObjectFromSource(assetTarget); diff --git a/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverridesWindow.cs b/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverridesWindow.cs index e14e7d536a..1d23d08821 100644 --- a/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverridesWindow.cs +++ b/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverridesWindow.cs @@ -17,19 +17,28 @@ internal class PrefabOverridesWindow : PopupWindowContent const float k_HeaderHeight = 32f; const float k_ButtonWidth = 120; const float k_HeaderLeftMargin = 6; + const float k_NoOverridesLabelHeight = 26f; + const float k_ApplyButtonHeight = 32f; + const float k_HelpBoxHeight = 40f; + GameObject[] m_SelectedGameObjects = null; + + // TreeView not used when there are multiple Prefabs. TreeViewState m_TreeViewState; PrefabOverridesTreeView m_TreeView; - GameObject m_SelectedGameObject; GUIContent m_StageContent = new GUIContent(); GUIContent m_InstanceContent = new GUIContent(); GUIContent m_RevertAllContent = new GUIContent(); GUIContent m_ApplyAllContent = new GUIContent(); - bool m_Immutable; + bool m_AnyOverrides; + bool m_Disconnected; bool m_InvalidComponentOnInstance; + bool m_ModelPrefab; + bool m_Immutable; bool m_InvalidComponentOnAsset; + static class Styles { public static GUIContent revertAllContent = EditorGUIUtility.TrTextContent("Revert All", "Revert all overrides."); @@ -49,46 +58,76 @@ static Styles() internal PrefabOverridesWindow(GameObject selectedGameObject) { - m_SelectedGameObject = selectedGameObject; + m_SelectedGameObjects = new GameObject[] { selectedGameObject }; m_TreeViewState = new TreeViewState(); m_TreeView = new PrefabOverridesTreeView(selectedGameObject, m_TreeViewState); - GameObject prefabAssetRoot = PrefabUtility.GetCorrespondingObjectFromSource(m_SelectedGameObject); + GameObject prefabAssetRoot = PrefabUtility.GetCorrespondingObjectFromSource(selectedGameObject); - m_TreeView.SetApplyTarget(m_SelectedGameObject, prefabAssetRoot, AssetDatabase.GetAssetPath(prefabAssetRoot)); + m_TreeView.SetApplyTarget(selectedGameObject, prefabAssetRoot, AssetDatabase.GetAssetPath(prefabAssetRoot)); - UpdateText(prefabAssetRoot); + UpdateTextSingle(prefabAssetRoot); + UpdateStatusChecks(selectedGameObject); + } - m_Immutable = PrefabUtility.IsPartOfImmutablePrefab(prefabAssetRoot); - m_InvalidComponentOnInstance = PrefabUtility.HasInvalidComponent(m_SelectedGameObject); - m_InvalidComponentOnAsset = PrefabUtility.HasInvalidComponent(prefabAssetRoot); + internal PrefabOverridesWindow(GameObject[] selectedGameObjects) + { + m_SelectedGameObjects = selectedGameObjects; + UpdateTextMultiple(); + for (int i = 0; i < m_SelectedGameObjects.Length; i++) + UpdateStatusChecks(m_SelectedGameObjects[i]); } - bool IsDisconnected() + void UpdateStatusChecks(GameObject prefabInstanceRoot) { - return PrefabUtility.IsDisconnectedFromPrefabAsset(m_SelectedGameObject); + if (PrefabUtility.HasPrefabInstanceAnyOverrides(prefabInstanceRoot, false)) + m_AnyOverrides = true; + if (PrefabUtility.IsDisconnectedFromPrefabAsset(prefabInstanceRoot)) + m_Disconnected = true; + if (PrefabUtility.HasInvalidComponent(prefabInstanceRoot)) + m_InvalidComponentOnInstance = true; + + GameObject prefabAssetRoot = PrefabUtility.GetCorrespondingObjectFromSource(prefabInstanceRoot); + + if (PrefabUtility.IsPartOfModelPrefab(prefabAssetRoot)) + m_ModelPrefab = true; + if (PrefabUtility.IsPartOfImmutablePrefab(prefabAssetRoot)) + m_Immutable = true; + if (PrefabUtility.HasInvalidComponent(prefabAssetRoot)) + m_InvalidComponentOnAsset = true; } bool IsShowingActionButton() { - if (m_TreeView.hasModifications || IsDisconnected()) - return true; + return m_AnyOverrides || m_Disconnected; + } - return false; + bool HasMultiSelection() + { + return m_SelectedGameObjects.Length > 1; + } + + bool DisplayingTreeView() + { + return m_AnyOverrides && !HasMultiSelection(); } public override Vector2 GetWindowSize() { var height = k_HeaderHeight; - if (!IsDisconnected()) - height += k_TreeViewPadding.top + m_TreeView.totalHeight + k_TreeViewPadding.bottom; + if (!IsShowingActionButton()) + { + height += k_NoOverridesLabelHeight; + } + else + { + if (DisplayingTreeView()) + height += k_TreeViewPadding.top + m_TreeView.totalHeight + k_TreeViewPadding.bottom; - const float applyButtonHeight = 32f; - if (IsShowingActionButton()) - height += applyButtonHeight; - if (m_TreeView.hasModifications || IsDisconnected()) - height += 40; + if (IsShowingActionButton()) + height += k_ApplyButtonHeight + k_HelpBoxHeight; + } // Width should be no smaller than minimum width, but we could potentially improve // width handling by making it expand if needed based on tree view content. @@ -99,6 +138,13 @@ public override Vector2 GetWindowSize() public override void OnGUI(Rect rect) { + // Escape closes the window + if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + { + editorWindow.Close(); + GUIUtility.ExitGUI(); + } + Rect headerRect = GUILayoutUtility.GetRect(20, 10000, k_HeaderHeight, k_HeaderHeight); EditorGUI.DrawRect(headerRect, headerBgColor); @@ -120,20 +166,36 @@ public override void OnGUI(Rect rect) GUILayout.Space(k_TreeViewPadding.top); - if (!IsDisconnected()) + // If we know there are no overrides and thus no meaningful actions we just show that and nothing more. + if (!IsShowingActionButton()) { - Rect treeViewRect = GUILayoutUtility.GetRect(100, 1000, 0, 1000); - m_TreeView.OnGUI(treeViewRect); + EditorGUILayout.LabelField("No Overrides"); + return; } - if (IsShowingActionButton()) + // Display tree view and/or instructions related to it. + if (HasMultiSelection()) { - if (IsDisconnected()) + if (m_InvalidComponentOnAsset || m_InvalidComponentOnInstance || m_ModelPrefab || m_Immutable) + EditorGUILayout.HelpBox( + "Multiple Prefabs selected. Cannot show overrides.\nApplying is not possible for one or more Prefabs. Select individual Prefabs for details.", + MessageType.Info); + else + EditorGUILayout.HelpBox( + "Multiple Prefabs selected. Cannot show overrides.", + MessageType.Info); + } + else + { + if (m_Disconnected) { EditorGUILayout.HelpBox("Disconnected. Cannot show overrides.", MessageType.Warning); } - else if (m_TreeView.hasModifications) + else if (m_AnyOverrides) { + Rect treeViewRect = GUILayoutUtility.GetRect(100, 1000, 0, 1000); + m_TreeView.OnGUI(treeViewRect); + if (m_InvalidComponentOnAsset) EditorGUILayout.HelpBox( "Click on individual items to review and revert.\nThe Prefab file contains an invalid script. Applying is not possible. Enter Prefab Mode and remove the script.", @@ -142,7 +204,7 @@ public override void OnGUI(Rect rect) EditorGUILayout.HelpBox( "Click on individual items to review and revert.\nThe Prefab instance contains an invalid script. Applying is not possible. Remove the script.", MessageType.Info); - else if (PrefabUtility.IsPartOfModelPrefab(m_SelectedGameObject)) + else if (m_ModelPrefab) EditorGUILayout.HelpBox( "Click on individual items to review and revert.\nApplying to a model Prefab is not possible.", MessageType.Info); @@ -154,54 +216,93 @@ public override void OnGUI(Rect rect) EditorGUILayout.HelpBox("Click on individual items to review, revert and apply.", MessageType.Info); } + } - GUILayout.BeginHorizontal(); - - GUILayout.FlexibleSpace(); - - using (new EditorGUI.DisabledScope(m_InvalidComponentOnAsset)) + // Display action buttons (Revert All and Apply All) + GUILayout.BeginHorizontal(); + GUILayout.FlexibleSpace(); + using (new EditorGUI.DisabledScope(m_InvalidComponentOnAsset)) + { + if (GUILayout.Button(m_RevertAllContent, GUILayout.Width(k_ButtonWidth))) { - if (GUILayout.Button(m_RevertAllContent, GUILayout.Width(k_ButtonWidth))) + if (RevertAll() && editorWindow != null) { - PrefabUtility.RevertPrefabInstance(m_SelectedGameObject, InteractionMode.UserAction); - - if (editorWindow != null) - { - editorWindow.Close(); - GUIUtility.ExitGUI(); - } + editorWindow.Close(); + GUIUtility.ExitGUI(); } + } - using (new EditorGUI.DisabledScope(m_Immutable || m_InvalidComponentOnInstance)) + using (new EditorGUI.DisabledScope(m_Immutable || m_InvalidComponentOnInstance)) + { + if (GUILayout.Button(m_ApplyAllContent, GUILayout.Width(k_ButtonWidth))) { - if (GUILayout.Button(m_ApplyAllContent, GUILayout.Width(k_ButtonWidth))) + if (ApplyAll() && editorWindow != null) { - string assetPath = - PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_SelectedGameObject); - if (PrefabUtility.PromptAndCheckoutPrefabIfNeeded(assetPath, PrefabUtility.SaveVerb.Apply)) - { - PrefabUtility.ApplyPrefabInstance(m_SelectedGameObject, InteractionMode.UserAction); - - if (editorWindow != null) - { - editorWindow.Close(); - GUIUtility.ExitGUI(); - } - } + editorWindow.Close(); + GUIUtility.ExitGUI(); } } } } + GUILayout.EndHorizontal(); + } - // Escape closes the window - if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) + bool ApplyAll() + { + // Collect Prefab Asset paths and also check if there's more than one of the same. + HashSet prefabAssetPaths = new HashSet(); + bool multipleOfSame = false; + for (int i = 0; i < m_SelectedGameObjects.Length; i++) { - editorWindow.Close(); - GUIUtility.ExitGUI(); + string prefabAssetPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(m_SelectedGameObjects[i]); + if (prefabAssetPaths.Contains(prefabAssetPath)) + multipleOfSame = true; + else + prefabAssetPaths.Add(prefabAssetPath); } + + // If more than one instance of the same Prefab Asset, show dialog to user. + if (multipleOfSame && !EditorUtility.DisplayDialog( + "Multiple instances of same Prefab Asset", + "Multiple instances of the same Prefab Asset were detected. Potentially conflicting overrides will be applied sequentially and will overwrite each other.", + "OK", + "Cancel")) + return false; + + // Make sure assets are checked out in version control. + if (!PrefabUtility.PromptAndCheckoutPrefabIfNeeded(prefabAssetPaths.ToArray(), PrefabUtility.SaveVerb.Apply)) + return false; + + // Apply sequentially. + for (int i = 0; i < m_SelectedGameObjects.Length; i++) + PrefabUtility.ApplyPrefabInstance(m_SelectedGameObjects[i], InteractionMode.UserAction); + + return true; + } + + bool RevertAll() + { + for (int i = 0; i < m_SelectedGameObjects.Length; i++) + PrefabUtility.RevertPrefabInstance(m_SelectedGameObjects[i], InteractionMode.UserAction); + + return true; + } + + void UpdateTextSingle(GameObject prefabAsset) + { + Texture2D icon = (Texture2D)AssetDatabase.GetCachedIcon(AssetDatabase.GetAssetPath(prefabAsset)); + string name = prefabAsset.name; + UpdateText(icon, name); + } + + void UpdateTextMultiple() + { + Texture icon = EditorGUIUtility.IconContent("Prefab Icon").image; + string name = "(Multiple Prefabs)"; + UpdateText(icon, name); } - void UpdateText(GameObject prefabAsset) + void UpdateText(Texture assetIcon, string assetName) { var stage = SceneManagement.StageNavigationManager.instance.currentItem; if (stage.isMainStage) @@ -215,8 +316,8 @@ void UpdateText(GameObject prefabAsset) m_StageContent.text = stage.displayName; } - m_InstanceContent.image = (Texture2D)AssetDatabase.GetCachedIcon(AssetDatabase.GetAssetPath(prefabAsset)); - m_InstanceContent.text = prefabAsset.name; + m_InstanceContent.image = assetIcon; + m_InstanceContent.text = assetName; m_RevertAllContent.text = Styles.revertAllContent.text; m_RevertAllContent.tooltip = Styles.revertAllContent.tooltip; @@ -226,7 +327,7 @@ void UpdateText(GameObject prefabAsset) applyAllContent = Styles.applyAllToBaseContent; m_ApplyAllContent.text = applyAllContent.text; - m_ApplyAllContent.tooltip = string.Format(applyAllContent.tooltip, prefabAsset.name); + m_ApplyAllContent.tooltip = string.Format(applyAllContent.tooltip, assetName); } } } diff --git a/Editor/Mono/Prefabs/PrefabUtility.bindings.cs b/Editor/Mono/Prefabs/PrefabUtility.bindings.cs index 7953e088d2..728dd0a803 100644 --- a/Editor/Mono/Prefabs/PrefabUtility.bindings.cs +++ b/Editor/Mono/Prefabs/PrefabUtility.bindings.cs @@ -30,6 +30,7 @@ public sealed partial class PrefabUtility extern private static Object GetCorrespondingObjectFromSourceAtPath_internal([NotNull] Object obj, string prefabAssetPath); // Retrieves the prefab object representation. + [Obsolete("Use GetPrefabInstanceHandle for Prefab instances. Handles for Prefab Assets has been discontinued.")] [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static Object GetPrefabObject(Object targetObject); @@ -56,6 +57,9 @@ public sealed partial class PrefabUtility [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static void SetPropertyModifications(Object targetPrefab, PropertyModification[] modifications); + [FreeFunction] + extern public static bool HasPrefabInstanceAnyOverrides(GameObject instanceRoot, bool includeDefaultOverrides); + // Instantiate an asset that is referenced by a prefab and use it on the prefab instance. [FreeFunction] [NativeHeader("Editor/Src/Prefabs/AttachedPrefabAsset.h")] @@ -72,12 +76,13 @@ public sealed partial class PrefabUtility extern public static void MergeAllPrefabInstances(Object targetObject); // Disconnects the prefab instance from its parent prefab. + [Obsolete("The concept of disconnecting Prefab instances has been deprecated.")] [FreeFunction] extern public static void DisconnectPrefabInstance(Object targetObject); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] - extern public static GameObject[] UnpackPrefabInstanceAndReturnNewOutermostRoots(GameObject root, PrefabUnpackMode unpackMode); + extern public static GameObject[] UnpackPrefabInstanceAndReturnNewOutermostRoots(GameObject instanceRoot, PrefabUnpackMode unpackMode); [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] @@ -88,6 +93,7 @@ public sealed partial class PrefabUtility extern public static void LoadPrefabContentsIntoPreviewScene(string prefabPath, Scene scene); // Connect the source prefab to the game object, which replaces the instance content with the content of the prefab + [Obsolete("Use RevertPrefabInstance. Prefabs instances can no longer be connected to Prefab Assets they are not an instance of to begin with.")] [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] [NativeThrows] extern public static GameObject ConnectGameObjectToPrefab([NotNull] GameObject go, [NotNull] GameObject sourcePrefab); @@ -105,26 +111,35 @@ public sealed partial class PrefabUtility // Connects the game object to the prefab that it was last connected to. [FreeFunction] + [Obsolete("Use RevertPrefabInstance.")] extern public static bool ReconnectToLastPrefab(GameObject go); // Resets the properties of the component or game object to the parent prefab state + [Obsolete("Use RevertObjectOverride.")] [StaticAccessor("PrefabUtilityBindings", StaticAccessorType.DoubleColon)] extern public static bool ResetToPrefabState(Object obj); + // Resets the properties of the component or game object to the parent prefab state + [NativeMethod("PrefabUtilityBindings::ResetToPrefabState", IsFreeFunction = true)] + extern private static bool RevertObjectOverride_Internal(Object obj); + [FreeFunction] extern public static bool IsAddedComponentOverride([NotNull] Object component); // Resets the properties of all objects in the prefab, including child game objects and components that were added to the prefab instance + [Obsolete("Use the overload that takes an InteractionMode parameter.")] [FreeFunction] extern public static bool RevertPrefabInstance([NotNull] GameObject go); + // Resets the properties of all objects in the prefab, including child game objects and components that were added to the prefab instance + [NativeMethod("RevertPrefabInstance", IsFreeFunction = true)] + extern private static bool RevertPrefabInstance_Internal([NotNull] GameObject go); + // Helper function to find the prefab root of an object [FreeFunction] [Obsolete("Use GetOutermostPrefabInstanceRoot if source is a Prefab instance or source.transform.root.gameObject if source is a Prefab Asset object.")] extern public static GameObject FindPrefabRoot([NotNull] GameObject source); -#pragma warning disable 0618 // Type or member is obsolete - internal static GameObject CreateVariant(GameObject assetRoot, string path) { if (assetRoot == null) @@ -146,11 +161,11 @@ internal static GameObject CreateVariant(GameObject assetRoot, string path) if (!Paths.IsValidAssetPath(path, ".prefab")) throw new ArgumentException("Given path is not valid: '" + path + "'"); - return CreateVariant_Internal(assetRoot, path, ReplacePrefabOptions.Default); + return CreateVariant_Internal(assetRoot, path); } [NativeMethod("CreateVariant", IsFreeFunction = true)] - extern private static GameObject CreateVariant_Internal([NotNull] GameObject original, string path, ReplacePrefabOptions replaceOptions); + extern private static GameObject CreateVariant_Internal([NotNull] GameObject original, string path); private enum PrefabCreationFlags { @@ -158,6 +173,8 @@ private enum PrefabCreationFlags CreateVariant = 1, } + // TODO: Having an non-obsolete method that takes an obsolete enum types as parameter is no good. +#pragma warning disable 0618 // Type or member is obsolete private static GameObject SavePrefab(GameObject inputObject, string path, ReplacePrefabOptions replaceOptions, PrefabCreationFlags creationFlags) { if (inputObject == null) @@ -175,13 +192,17 @@ private static GameObject SavePrefab(GameObject inputObject, string path, Replac throw new ArgumentException("Given path does not exist: '" + path + "'"); string prefabGUID = AssetDatabase.AssetPathToGUID(path); - if (!VerifyNestingFromScript(new GameObject[] {inputObject}, prefabGUID, PrefabUtility.GetPrefabObject(inputObject))) + if (!VerifyNestingFromScript(new GameObject[] {inputObject}, prefabGUID, PrefabUtility.GetPrefabInstanceHandle(inputObject))) throw new ArgumentException("Cyclic nesting detected"); return SavePrefab_Internal(inputObject, path, replaceOptions, creationFlags); } +#pragma warning restore 0618 // Type or member is obsolete + + // TODO: Having an non-obsolete method that takes an obsolete enum types as parameter is no good. [NativeMethod("SavePrefab", IsFreeFunction = true)] +#pragma warning disable 0618 // Type or member is obsolete extern private static GameObject SavePrefab_Internal([NotNull] GameObject root, string path, ReplacePrefabOptions replaceOptions, PrefabCreationFlags createOptions); #pragma warning restore 0618 // Type or member is obsolete @@ -201,7 +222,7 @@ internal static void AddGameObjectsToPrefabAndConnect(GameObject[] gameObjects, Object targetPrefabInstance = null; - var targetPrefabObject = PrefabUtility.GetPrefabObject(targetPrefab); + var targetPrefabObject = PrefabUtility.GetPrefabAssetHandle(targetPrefab); foreach (GameObject go in gameObjects) { @@ -232,7 +253,7 @@ internal static void AddGameObjectsToPrefabAndConnect(GameObject[] gameObjects, if (PrefabUtility.IsPartOfNonAssetPrefabInstance(go)) { var correspondingGO = PrefabUtility.GetCorrespondingObjectFromSource(go); - var correspondingGOPrefabObject = PrefabUtility.GetPrefabObject(correspondingGO); + var correspondingGOPrefabObject = PrefabUtility.GetPrefabAssetHandle(correspondingGO); if (targetPrefabObject == correspondingGOPrefabObject) throw new ArgumentException("GameObject is already part of target prefab"); } @@ -299,6 +320,11 @@ internal static void AddGameObjectsToPrefabAndConnect(GameObject[] gameObjects, [FreeFunction] extern public static bool IsPartOfVariantPrefab([NotNull] Object componentOrGameObject); + // Returns true if the object is from a Prefab Asset which is not editable, or an instance of such a Prefab + // Examples are Model Prefabs and Prefabs in read-only folders. + [FreeFunction] + extern public static bool IsPartOfImmutablePrefab([NotNull] Object componentOrGameObject); + [FreeFunction] extern public static bool IsDisconnectedFromPrefabAsset([NotNull] Object componentOrGameObject); diff --git a/Editor/Mono/Prefabs/PrefabUtility.cs b/Editor/Mono/Prefabs/PrefabUtility.cs index 8279a9f737..695db44170 100644 --- a/Editor/Mono/Prefabs/PrefabUtility.cs +++ b/Editor/Mono/Prefabs/PrefabUtility.cs @@ -296,10 +296,7 @@ public static void RevertPrefabInstance(GameObject instanceRoot, InteractionMode CheckInstanceIsNotPersistent(instanceRoot); - // The concept of disconnecting are being deprecated. For now use FindRootGameObjectWithSameParentPrefab - // to re-connect existing disconnected prefabs. - #pragma warning disable 0618 // Type or member is obsolete - GameObject prefabInstanceRoot = FindRootGameObjectWithSameParentPrefab(instanceRoot); + GameObject prefabInstanceRoot = GetOutermostPrefabInstanceRoot(instanceRoot); var actionName = "Revert Prefab Instance"; HashSet hierarchy = null; @@ -313,13 +310,13 @@ public static void RevertPrefabInstance(GameObject instanceRoot, InteractionMode if (isDisconnected) { - ReconnectToLastPrefab(prefabInstanceRoot); + RevertPrefabInstance_Internal(prefabInstanceRoot); if (action == InteractionMode.UserAction) Undo.RegisterCreatedObjectUndo(GetPrefabInstanceHandle(prefabInstanceRoot), actionName); } - RevertPrefabInstance(prefabInstanceRoot); + RevertPrefabInstance_Internal(prefabInstanceRoot); if (action == InteractionMode.UserAction) { @@ -333,10 +330,7 @@ public static void ApplyPrefabInstance(GameObject instanceRoot, InteractionMode CheckInstanceIsNotPersistent(instanceRoot); - // The concept of disconnecting are being deprecated. For now use FindRootGameObjectWithSameParentPrefab - // to re-connect existing disconnected prefabs. - #pragma warning disable 0618 // Type or member is obsolete - GameObject prefabInstanceRoot = FindRootGameObjectWithSameParentPrefab(instanceRoot); + GameObject prefabInstanceRoot = GetOutermostPrefabInstanceRoot(instanceRoot); var actionName = "Apply instance to prefab"; Object correspondingSourceObject = GetCorrespondingObjectFromSource(prefabInstanceRoot); @@ -391,21 +385,91 @@ private static void MapObjectReferencePropertyToSourceIfApplicable(SerializedPro } public static void ApplyPropertyOverride(SerializedProperty instanceProperty, string assetPath, InteractionMode action) - { - ApplyPropertyOverride(instanceProperty, assetPath, action, true); - } - - static void ApplyPropertyOverride(SerializedProperty instanceProperty, string assetPath, InteractionMode action, bool singlePropertyOnly) { DateTime startTime = DateTime.UtcNow; Object prefabInstanceObject = instanceProperty.serializedObject.targetObject; + CheckInstanceIsNotPersistent(prefabInstanceObject); + + ApplyPropertyOverrides(prefabInstanceObject, instanceProperty, assetPath, action); + + Analytics.SendApplyEvent( + Analytics.ApplyScope.PropertyOverride, + prefabInstanceObject, + assetPath, + action, + startTime, + IsPropertyOverrideDefaultOverrideComparedToAnySource(instanceProperty) + ); + } + + // This method is called both from ApplyPropertyOverride (one time) and ApplyObjectOverride (many times). + // In the former case, optionalSingleInstanceProperty is passed along as is the only property that should be processed. + // In the latter, all properties in the prefabInstanceObject are iterated. + // An alternative approach was considered where the method takes an array of SerializedProperties, + // but since there can be thousands of those in a component, and they would each have to be copied from the iterator, + // it's better to handle properties inline as the iterator iterates over them. + // This does mean that we need to cache the SerializedObjects that end up being touched. + // Those are that of the prefabInstanceObject itself, and the chain of corresponding object + // all the way to the Prefab at the specified assetPath. + // Since calling ApplyModifiedProperties on a SerializedObject can trigger a whole chain of imports, + // we don't want to create and call ApplyModifiedProperties more than once for each SerializedObject, hence the caching. + // We also can't swap the inner and outer loop, iterating the chain of corresponding objects in the outer loop + // and the SerializedProperties in the inner loop, since we only process overridden properties, so it would + // again require storing information about that for each property in some kind of list, which we want to avoid. + static void ApplyPropertyOverrides(Object prefabInstanceObject, SerializedProperty optionalSingleInstanceProperty, string assetPath, InteractionMode action) + { + bool singleProperty = optionalSingleInstanceProperty != null; Object prefabSourceObject = GetCorrespondingObjectFromSourceAtPath(prefabInstanceObject, assetPath); if (prefabSourceObject == null) return; - if (IsPropertyOverrideDefaultOverrideComparedToAnySource(instanceProperty) && IsObjectOnRootInAsset(prefabInstanceObject, assetPath)) + SerializedObject prefabSourceSerializedObject = new SerializedObject(prefabSourceObject); + + // Cache SerializedObjects used. + List serializedObjects = new List(); + + bool isObjectOnRootInAsset = IsObjectOnRootInAsset(prefabInstanceObject, assetPath); + if (singleProperty) + { + if (optionalSingleInstanceProperty.prefabOverride) + ApplySingleProperty(optionalSingleInstanceProperty, prefabSourceSerializedObject, assetPath, isObjectOnRootInAsset, true, serializedObjects, action); + } + else + { + SerializedObject so = new SerializedObject(prefabInstanceObject); + SerializedProperty property = so.GetIterator(); + while (property.Next(property.hasChildren)) + { + if (property.prefabOverride) + ApplySingleProperty(property, prefabSourceSerializedObject, assetPath, isObjectOnRootInAsset, false, serializedObjects, action); + } + } + + // Write modified value to prefab source object. + for (int i = 0; i < serializedObjects.Count; i++) + { + serializedObjects[i].ApplyModifiedProperties(); + if (action == InteractionMode.UserAction) + Undo.FlushUndoRecordObjects(); // flush'es ensure that SavePrefab() on undo/redo on the source happens in the right order + } + } + + // Since method is called for each overridden property in a component. + // That may be thousands of times if a component has lots of array data. + // We provide as much information as possible to the method as parameters + // so we don't have to recalculate it for each call. + static void ApplySingleProperty( + SerializedProperty instanceProperty, + SerializedObject prefabSourceSerializedObject, + string assetPath, + bool isObjectOnRootInAsset, + bool singlePropertyOnly, + List serializedObjects, + InteractionMode action) + { + if (isObjectOnRootInAsset && IsPropertyOverrideDefaultOverrideComparedToAnySource(instanceProperty)) { if (singlePropertyOnly) { @@ -414,12 +478,14 @@ static void ApplyPropertyOverride(SerializedProperty instanceProperty, string as if (action == InteractionMode.AutomatedAction) Debug.LogWarning("Cannot apply default-override property, since it is protected from being applied or reverted."); else - EditorUtility.DisplayDialog("Cannot apply default-override property", "Default-override properties are protected from being applied or reverted.", "OK"); + EditorUtility.DisplayDialog( + "Cannot apply default-override property", + "Default-override properties are protected from being applied or reverted.", + "OK"); } return; } - SerializedObject prefabSourceSerializedObject = new SerializedObject(prefabSourceObject); prefabSourceSerializedObject.CopyFromSerializedProperty(instanceProperty); SerializedProperty sourceProperty = prefabSourceSerializedObject.FindProperty(instanceProperty.propertyPath); @@ -438,47 +504,46 @@ static void ApplyPropertyOverride(SerializedProperty instanceProperty, string as if (action == InteractionMode.AutomatedAction) Debug.LogWarning("Cannot apply reference to scene object that is not part of apply target prefab."); else - EditorUtility.DisplayDialog("Cannot apply reference to object in scene", "A reference to an object in the scene cannot be applied to the Prefab asset.", "OK"); + EditorUtility.DisplayDialog( + "Cannot apply reference to object in scene", + "A reference to an object in the scene cannot be applied to the Prefab asset.", + "OK"); } return; } } - // Write modified value to prefab source object. - prefabSourceSerializedObject.ApplyModifiedProperties(); - - if (action == InteractionMode.UserAction) - Undo.FlushUndoRecordObjects(); // flush'es ensure that SavePrefab() on undo/redo on the source happens in the right order + // Apply target SerializedObject should get ApplyModifiedProperties called first. + if (serializedObjects.Count == 0) + serializedObjects.Add(prefabSourceSerializedObject); - // Clear overrides for property in prefab instance and outer prefabs that are using(nesting) the prefab source. + // Clear overrides for property in Prefab instance and outer Prefabs that are using(nesting) the Prefab source. // Otherwise applied modification would appear to jump back to the value it had before applying. + Object prefabInstanceObject = instanceProperty.serializedObject.targetObject; + Object prefabSourceObject = prefabSourceSerializedObject.targetObject; Object outerPrefabObject = prefabInstanceObject; + int sourceIndex = 1; while (outerPrefabObject != prefabSourceObject) { - SerializedObject outerPrefabSerializedObject = new SerializedObject(outerPrefabObject); + SerializedObject outerPrefabSerializedObject; + if (sourceIndex >= serializedObjects.Count) + { + outerPrefabSerializedObject = new SerializedObject(outerPrefabObject); + serializedObjects.Add(outerPrefabSerializedObject); + } + else + { + outerPrefabSerializedObject = serializedObjects[sourceIndex]; + } + SerializedProperty outerPrefabProp = outerPrefabSerializedObject.FindProperty(instanceProperty.propertyPath); if (outerPrefabProp.prefabOverride) { outerPrefabProp.prefabOverride = false; - outerPrefabSerializedObject.ApplyModifiedProperties(); - - if (action == InteractionMode.UserAction) - Undo.FlushUndoRecordObjects(); } - outerPrefabObject = PrefabUtility.GetCorrespondingObjectFromSource(outerPrefabObject); - } - // If this method is called as part of ApplyObjectOverride, we don't want to send analytics here too. - if (singlePropertyOnly) - { - Analytics.SendApplyEvent( - Analytics.ApplyScope.PropertyOverride, - prefabInstanceObject, - assetPath, - action, - startTime, - IsPropertyOverrideDefaultOverrideComparedToAnySource(instanceProperty) - ); + outerPrefabObject = PrefabUtility.GetCorrespondingObjectFromSource(outerPrefabObject); + sourceIndex++; } } @@ -498,13 +563,7 @@ public static void ApplyObjectOverride(Object instanceComponentOrGameObject, str CheckInstanceIsNotPersistent(instanceComponentOrGameObject); - SerializedObject so = new SerializedObject(instanceComponentOrGameObject); - SerializedProperty property = so.GetIterator(); - while (property.Next(property.hasChildren)) - { - if (property.prefabOverride) - ApplyPropertyOverride(property, assetPath, action, false); - } + ApplyPropertyOverrides(instanceComponentOrGameObject, null, assetPath, action); Analytics.SendApplyEvent( Analytics.ApplyScope.ObjectOverride, @@ -525,7 +584,7 @@ public static void RevertObjectOverride(Object instanceComponentOrGameObject, In if (action == InteractionMode.UserAction) Undo.RegisterCompleteObjectUndo(instanceComponentOrGameObject, "Revert component property overrides"); - PrefabUtility.ResetToPrefabState(instanceComponentOrGameObject); + PrefabUtility.RevertObjectOverride_Internal(instanceComponentOrGameObject); } public static void ApplyAddedComponent(Component component, string assetPath, InteractionMode action) @@ -598,7 +657,7 @@ private static bool IsPrefabInstanceObjectOf(Object instance, Object source) return true; } - if (GetPrefabObject(o) == source) + if (GetPrefabAssetHandle(o) == source) { return true; } @@ -641,7 +700,7 @@ public static void ApplyRemovedComponent(GameObject instanceGameObject, Componen SavePrefabAsset(prefabAsset); } - var prefabInstanceObject = PrefabUtility.GetPrefabObject(instanceGameObject); + var prefabInstanceObject = PrefabUtility.GetPrefabInstanceHandle(instanceGameObject); if (action == InteractionMode.UserAction) Undo.RegisterCompleteObjectUndo(prefabInstanceObject, actionName); @@ -682,7 +741,7 @@ public static void RevertRemovedComponent(GameObject instanceGameObject, Compone CheckInstanceIsNotPersistent(instanceGameObject); var actionName = "Revert Prefab removed component"; - var prefabInstanceObject = PrefabUtility.GetPrefabObject(instanceGameObject); + var prefabInstanceObject = PrefabUtility.GetPrefabInstanceHandle(instanceGameObject); if (action == InteractionMode.UserAction) Undo.RegisterCompleteObjectUndo(instanceGameObject, actionName); @@ -928,7 +987,7 @@ public static Object GetPrefabParent(Object obj) } // Creates an empty prefab at given path. - // TODO Steen Lund 2017 11 28 This needs to be marked OBSOLETE + [Obsolete("The concept of creating a completely empty Prefab has been discontinued. You can however use SaveAsPrefabAsset with an empty GameObject.")] public static Object CreateEmptyPrefab(string path) { // This is here to simulate previous behaviour @@ -944,8 +1003,6 @@ public static Object CreateEmptyPrefab(string path) return PrefabUtility.GetPrefabObject(assetObject); } -#pragma warning disable CS0618 // Type or member is obsolete - public static GameObject SavePrefabAsset(GameObject asset) { if (asset == null) @@ -966,24 +1023,26 @@ public static GameObject SavePrefabAsset(GameObject asset) if (root != asset) throw new ArgumentException("GameObject to save Prefab from must be a Prefab root"); +#pragma warning disable CS0618 // Type or member is obsolete return SavePrefab(root, path, ReplacePrefabOptions.Default, PrefabCreationFlags.None); +#pragma warning restore CS0618 // Type or member is obsolete } - private static void SaveAsPrefabAssetArgumentCheck(GameObject root) + private static void SaveAsPrefabAssetArgumentCheck(GameObject instanceRoot) { - if (root == null) + if (instanceRoot == null) throw new ArgumentNullException("Parameter root is null"); - if (EditorUtility.IsPersistent(root)) + if (EditorUtility.IsPersistent(instanceRoot)) throw new ArgumentException("Can't save persistent object as a Prefab asset"); - if (IsPrefabAssetMissing(root)) + if (IsPrefabAssetMissing(instanceRoot)) throw new ArgumentException("Can't save Prefab instance with missing asset as a Prefab. You may unpack the instance and save the unpacked GameObjects as a Prefab."); - var instanceRoot = GetOutermostPrefabInstanceRoot(root); - if (instanceRoot) + var actualInstanceRoot = GetOutermostPrefabInstanceRoot(instanceRoot); + if (actualInstanceRoot) { - if (instanceRoot != root) + if (actualInstanceRoot != instanceRoot) throw new ArgumentException("Can't save part of a Prefab instance as a Prefab"); } } @@ -994,37 +1053,41 @@ private static bool IsPrefabInstanceRoot(GameObject gameObject) return instanceRoot != null && instanceRoot == gameObject; } - public static GameObject SaveAsPrefabAsset(GameObject root, string assetPath) + public static GameObject SaveAsPrefabAsset(GameObject instanceRoot, string assetPath) { - SaveAsPrefabAssetArgumentCheck(root); + SaveAsPrefabAssetArgumentCheck(instanceRoot); PrefabCreationFlags creationFlags = PrefabCreationFlags.None; - if (IsPrefabInstanceRoot(root)) + if (IsPrefabInstanceRoot(instanceRoot)) creationFlags = PrefabCreationFlags.CreateVariant; - return SavePrefab(root, assetPath, ReplacePrefabOptions.Default, creationFlags); +#pragma warning disable CS0618 // Type or member is obsolete + return SavePrefab(instanceRoot, assetPath, ReplacePrefabOptions.Default, creationFlags); +#pragma warning restore CS0618 // Type or member is obsolete } - public static GameObject SaveAsPrefabAssetAndConnect(GameObject root, string assetPath, InteractionMode action) + public static GameObject SaveAsPrefabAssetAndConnect(GameObject instanceRoot, string assetPath, InteractionMode action) { - SaveAsPrefabAssetArgumentCheck(root); + SaveAsPrefabAssetArgumentCheck(instanceRoot); var actionName = "Connect to Prefab"; if (action == InteractionMode.UserAction) { - Undo.RegisterFullObjectHierarchyUndo(root, actionName); + Undo.RegisterFullObjectHierarchyUndo(instanceRoot, actionName); } PrefabCreationFlags creationFlags = PrefabCreationFlags.None; - if (IsPrefabInstanceRoot(root)) + if (IsPrefabInstanceRoot(instanceRoot)) creationFlags = PrefabCreationFlags.CreateVariant; - var assetRoot = SavePrefab(root, assetPath, ReplacePrefabOptions.ConnectToPrefab, creationFlags); +#pragma warning disable CS0618 // Type or member is obsolete + var assetRoot = SavePrefab(instanceRoot, assetPath, ReplacePrefabOptions.ConnectToPrefab, creationFlags); +#pragma warning restore CS0618 // Type or member is obsolete if (action == InteractionMode.UserAction) { - Undo.RegisterCreatedObjectUndo(GetPrefabInstanceHandle(root), actionName); + Undo.RegisterCreatedObjectUndo(GetPrefabInstanceHandle(instanceRoot), actionName); } return assetRoot; @@ -1049,7 +1112,7 @@ internal static void ApplyPrefabInstance(GameObject instance) { // The concept of disconnecting are being deprecated. For now use FindRootGameObjectWithSameParentPrefab // to re-connect existing disconnected prefabs. - var validRoot = PrefabUtility.FindValidUploadPrefabInstanceRoot(instance); + var validRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(instance); var ok = validRoot == instance; if (!ok && PrefabUtility.GetCorrespondingObjectFromOriginalSource(instance) != PrefabUtility.GetCorrespondingObjectFromSource(instance)) throw new ArgumentException("Can't save Prefab from an object that originates from a nested Prefab"); @@ -1063,11 +1126,17 @@ internal static void ApplyPrefabInstance(GameObject instance) var assetObject = GetCorrespondingObjectFromSource(instance); string path = AssetDatabase.GetAssetPath(assetObject); + +#pragma warning disable CS0618 // Type or member is obsolete SavePrefab(instance, path, ReplacePrefabOptions.ConnectToPrefab, PrefabCreationFlags.None); +#pragma warning restore CS0618 // Type or member is obsolete } + // TOOO: Remove entirely once regular methods handle merging + // based on both ids and names on a smarter and more granular level. internal static GameObject ReplacePrefabAssetNameBased(GameObject root, string targetPrefab, bool connectToInstance) { +#pragma warning disable CS0618 // Type or member is obsolete var options = ReplacePrefabOptions.ReplaceNameBased; if (connectToInstance) options |= ReplacePrefabOptions.ConnectToPrefab; @@ -1076,8 +1145,7 @@ internal static GameObject ReplacePrefabAssetNameBased(GameObject root, string t if (IsPartOfNonAssetPrefabInstance(root)) { - var instanceRoot = PrefabUtility.GetPrefabInstanceRootGameObject(root); - if (root != instanceRoot) + if (!IsOutermostPrefabInstanceRoot(root)) throw new ArgumentException("Can't replace with part of Prefab instance. Please specify instance root object or a non-instance object."); createOptions = PrefabCreationFlags.CreateVariant; @@ -1087,22 +1155,26 @@ internal static GameObject ReplacePrefabAssetNameBased(GameObject root, string t throw new ArgumentException("Argument connectToInstance is true but root object is an asset not an instance"); return SavePrefab(root, targetPrefab, options, createOptions); - } - #pragma warning restore CS0618 // Type or member is obsolete + } - //[Obsolete("CreatePrefab() has been deprecated. Use SavePrefab() instead (UnityUpgradable) -> SavePrefab(go, path, ReplacePrefabOptions.Default)")] + // Can't use UnityUpgradable since it doesn't currently support swapping parameter order. + [Obsolete("Use SaveAsPrefabAsset instead.")] public static GameObject CreatePrefab(string path, GameObject go) { return SaveAsPrefabAsset(go, path); } - //[Obsolete("CreatePrefab() has been deprecated. Use SavePrefab() instead (UnityUpgradable) -> SavePrefab(go, path, options)")] -#pragma warning disable CS0618 // Type or member is obsolete + [Obsolete("Use SaveAsPrefabAsset or SaveAsPrefabAssetAndConnect instead.")] public static GameObject CreatePrefab(string path, GameObject go, ReplacePrefabOptions options) { if (options == ReplacePrefabOptions.ConnectToPrefab) return SaveAsPrefabAssetAndConnect(go, path, InteractionMode.AutomatedAction); + else if ((options & ReplacePrefabOptions.ReplaceNameBased) != 0) + { + bool connectToPrefab = (options & ReplacePrefabOptions.ConnectToPrefab) != 0; + return ReplacePrefabAssetNameBased(go, path, connectToPrefab); + } else return SaveAsPrefabAsset(go, path); } @@ -1119,11 +1191,13 @@ public static Object InstantiatePrefab(Object assetComponentOrGameObject, Scene return InstantiatePrefab_internal(assetComponentOrGameObject, destinationScene); } + [Obsolete("Use SaveAsPrefabAsset with a path instead.")] public static GameObject ReplacePrefab(GameObject go, Object targetPrefab) { return ReplacePrefab(go, targetPrefab, ReplacePrefabOptions.Default); } + [Obsolete("Use SaveAsPrefabAsset or SaveAsPrefabAssetAndConnect with a path instead.")] public static GameObject ReplacePrefab(GameObject go, Object targetPrefab, ReplacePrefabOptions replaceOptions) { var targetPrefabObject = PrefabUtility.GetPrefabObject(targetPrefab); @@ -1163,8 +1237,6 @@ public static GameObject ReplacePrefab(GameObject go, Object targetPrefab, Repla return SavePrefab(go, assetPath, replaceOptions, PrefabCreationFlags.None); } -#pragma warning restore CS0618 // Type or member is obsolete - // Returns the corresponding object from its immediate source, or null if it can't be found. public static TObject GetCorrespondingObjectFromSource(TObject componentOrGameObject) where TObject : Object { @@ -1211,7 +1283,6 @@ private static Object GetCorrespondingObjectFromOriginalSource_Internal(Object i } // Given an object, returns its prefab type (None, if it's not a prefab) -#pragma warning disable CS0618 // Type or member is obsolete [Obsolete("Use GetPrefabAssetType and GetPrefabInstanceStatus to get the full picture about Prefab types.")] public static PrefabType GetPrefabType(Object target) { @@ -1251,8 +1322,6 @@ public static PrefabType GetPrefabType(Object target) return PrefabType.PrefabInstance; } -#pragma warning restore CS0618 // Type or member is obsolete - // Called after prefab instances in the scene have been updated public delegate void PrefabInstanceUpdated(GameObject instance); public static PrefabInstanceUpdated prefabInstanceUpdated; @@ -1301,44 +1370,55 @@ internal enum SaveVerb Save, Apply } + internal static bool PromptAndCheckoutPrefabIfNeeded(string assetPath, SaveVerb saveVerb) { + return PromptAndCheckoutPrefabIfNeeded(new string[] { assetPath }, saveVerb); + } + + internal static bool PromptAndCheckoutPrefabIfNeeded(string[] assetPaths, SaveVerb saveVerb) + { + string prefabNoun = assetPaths.Length > 1 ? "Prefabs" : "Prefab"; bool result = Provider.PromptAndCheckoutIfNeeded( - new string[] { assetPath }, + assetPaths, String.Format( - "The version control requires you to check out the Prefab before {0} changes.", - saveVerb == SaveVerb.Save ? "saving" : "applying") + "The version control requires you to check out the {1} before {0} changes.", + saveVerb == SaveVerb.Save ? "saving" : "applying", + prefabNoun + ) ); if (!result) EditorUtility.DisplayDialog( String.Format( - "Could not {0} Prefab", - saveVerb == SaveVerb.Save ? "save" : "apply to"), + "Could not {0} {1}", + saveVerb == SaveVerb.Save ? "save" : "apply to", + prefabNoun), String.Format( - "It was not possible to check out the Prefab so the {0} operation has been canceled.", - saveVerb == SaveVerb.Save ? "save" : "apply"), + "It was not possible to check out the {1} so the {0} operation has been canceled.", + saveVerb == SaveVerb.Save ? "save" : "apply", + prefabNoun), "OK"); return result; } - public static void UnpackPrefabInstance(GameObject root, PrefabUnpackMode unpackMode, InteractionMode action) + public static void UnpackPrefabInstance(GameObject instanceRoot, PrefabUnpackMode unpackMode, InteractionMode action) { - if (!IsPartOfNonAssetPrefabInstance(root)) + if (!IsPartOfNonAssetPrefabInstance(instanceRoot)) throw new ArgumentException("UnpackPrefabInstance must be called with a Prefab instance."); - if (GetPrefabInstanceRootGameObject(root) != root) + if (!IsOutermostPrefabInstanceRoot(instanceRoot)) throw new ArgumentException("UnpackPrefabInstance must be called with a root Prefab instance GameObject."); if (action == InteractionMode.UserAction) { var undoActionName = "Unpack Prefab instance"; - Undo.RegisterFullObjectHierarchyUndo(root, undoActionName); - var instanceRoots = UnpackPrefabInstanceAndReturnNewOutermostRoots(root, unpackMode); - foreach (var instanceRoot in instanceRoots) + Undo.RegisterFullObjectHierarchyUndo(instanceRoot, undoActionName); + var newInstanceRoots = UnpackPrefabInstanceAndReturnNewOutermostRoots(instanceRoot, unpackMode); + foreach (var newInstanceRoot in newInstanceRoots) { - var prefabInstance = PrefabUtility.GetPrefabInstanceHandle(instanceRoot); + var prefabInstance = PrefabUtility.GetPrefabInstanceHandle(newInstanceRoot); if (prefabInstance) { Undo.RegisterCreatedObjectUndo(prefabInstance, undoActionName); @@ -1347,28 +1427,10 @@ public static void UnpackPrefabInstance(GameObject root, PrefabUnpackMode unpack } else { - UnpackPrefabInstanceAndReturnNewOutermostRoots(root, unpackMode); + UnpackPrefabInstanceAndReturnNewOutermostRoots(instanceRoot, unpackMode); } } - public static bool IsPartOfImmutablePrefab(Object gameObjectOrComponent) - { - if (IsPartOfModelPrefab(gameObjectOrComponent)) - return true; - - // If prefab instance, get the prefab asset. - if (!EditorUtility.IsPersistent(gameObjectOrComponent)) - gameObjectOrComponent = GetCorrespondingObjectFromSource(gameObjectOrComponent); - - string prefabAssetPath = AssetDatabase.GetAssetPath(gameObjectOrComponent); - bool isRootFolder, isReadonly; - bool validPath = AssetDatabase.GetAssetFolderInfo(prefabAssetPath, out isRootFolder, out isReadonly); - if (validPath && isReadonly) - return true; - - return false; - } - internal static bool HasInvalidComponent(Object gameObjectOrComponent) { if (gameObjectOrComponent == null) @@ -1447,13 +1509,13 @@ public static GameObject LoadPrefabContents(string assetPath) return roots[0]; } - public static void UnloadPrefabContents(GameObject root) + public static void UnloadPrefabContents(GameObject contentsRoot) { - if (!EditorSceneManager.IsPreviewSceneObject(root)) + if (!EditorSceneManager.IsPreviewSceneObject(contentsRoot)) { throw new ArgumentException("Specified object is not part of Prefab contents"); } - var scene = root.scene; + var scene = contentsRoot.scene; EditorSceneManager.ClosePreviewScene(scene); } diff --git a/Editor/Mono/PreferencesWindow/PreferencesSettingsProviders.cs b/Editor/Mono/PreferencesWindow/PreferencesSettingsProviders.cs index b99d96e3a3..a17eef3271 100644 --- a/Editor/Mono/PreferencesWindow/PreferencesSettingsProviders.cs +++ b/Editor/Mono/PreferencesWindow/PreferencesSettingsProviders.cs @@ -37,6 +37,12 @@ internal static class Constants internal class Styles { public static readonly GUIContent browse = EditorGUIUtility.TrTextContent("Browse..."); + public static readonly GUIStyle clearBindingButton = new GUIStyle(GUI.skin.button); + + static Styles() + { + clearBindingButton.margin.top = 0; + } } internal class GeneralProperties @@ -711,6 +717,9 @@ private void ShowShortcutConfiguration(int controlID, ShortcutEntry selectedShor { GUILayout.Label("Key:"); e = EditorGUILayout.KeyEventField(e); + + if (GUILayout.Button("Clear", Styles.clearBindingButton)) + e.keyCode = KeyCode.None; } using (new GUILayout.HorizontalScope()) @@ -732,7 +741,9 @@ private void ShowShortcutConfiguration(int controlID, ShortcutEntry selectedShor if (m_ValidKeyChange) { // TODO: Don't clobber secondary+ combinations - var newCombination = new List { new KeyCombination(e) }; + var newCombination = new List(); + if (e.keyCode != KeyCode.None) + newCombination.Add(new KeyCombination(e)); shortcutController.profileManager.ModifyShortcutEntry(selectedShortcut.identifier, newCombination); shortcutController.profileManager.PersistChanges(); } diff --git a/Editor/Mono/PresetLibraries/CurvePresetsContentsForPopupWindow.cs b/Editor/Mono/PresetLibraries/CurvePresetsContentsForPopupWindow.cs deleted file mode 100644 index 3ee2cdba01..0000000000 --- a/Editor/Mono/PresetLibraries/CurvePresetsContentsForPopupWindow.cs +++ /dev/null @@ -1,147 +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 UnityEditorInternal; -using UnityEngine; - -namespace UnityEditor -{ - internal enum CurveLibraryType - { - Unbounded, - NormalizedZeroToOne - } - - - internal class CurvePresetsContentsForPopupWindow : PopupWindowContent - { - PresetLibraryEditor m_CurveLibraryEditor; - PresetLibraryEditorState m_CurveLibraryEditorState; - AnimationCurve m_Curve; - CurveLibraryType m_CurveLibraryType; - bool m_WantsToClose = false; - System.Action m_PresetSelectedCallback; - - public AnimationCurve curveToSaveAsPreset {get {return m_Curve; } set {m_Curve = value; }} - - public CurvePresetsContentsForPopupWindow(AnimationCurve animCurve, CurveLibraryType curveLibraryType, System.Action presetSelectedCallback) - { - m_CurveLibraryType = curveLibraryType; - m_Curve = animCurve; - m_PresetSelectedCallback = presetSelectedCallback; - } - - public static string GetBasePrefText(CurveLibraryType curveLibraryType) - { - return GetExtension(curveLibraryType); - } - - public string currentPresetLibrary - { - get - { - InitIfNeeded(); - return m_CurveLibraryEditor.currentLibraryWithoutExtension; - } - set - { - InitIfNeeded(); - m_CurveLibraryEditor.currentLibraryWithoutExtension = value; - } - } - - static string GetExtension(CurveLibraryType curveLibraryType) - { - switch (curveLibraryType) - { - case CurveLibraryType.NormalizedZeroToOne: return PresetLibraryLocations.GetCurveLibraryExtension(true); - case CurveLibraryType.Unbounded: return PresetLibraryLocations.GetCurveLibraryExtension(false); - default: - Debug.LogError("Enum not handled!"); - return "curves"; - } - } - - public override void OnClose() - { - m_CurveLibraryEditorState.TransferEditorPrefsState(false); - } - - public PresetLibraryEditor GetPresetLibraryEditor() - { - return m_CurveLibraryEditor; - } - - public void InitIfNeeded() - { - if (m_CurveLibraryEditorState == null) - { - m_CurveLibraryEditorState = new PresetLibraryEditorState(GetBasePrefText(m_CurveLibraryType)); - m_CurveLibraryEditorState.TransferEditorPrefsState(true); - } - - if (m_CurveLibraryEditor == null) - { - var saveLoadHelper = new ScriptableObjectSaveLoadHelper(GetExtension(m_CurveLibraryType), SaveType.Text); - m_CurveLibraryEditor = new PresetLibraryEditor(saveLoadHelper, m_CurveLibraryEditorState, ItemClickedCallback); - m_CurveLibraryEditor.addDefaultPresets += AddDefaultPresetsToLibrary; - m_CurveLibraryEditor.presetsWasReordered += OnPresetsWasReordered; - m_CurveLibraryEditor.previewAspect = 4f; - m_CurveLibraryEditor.minMaxPreviewHeight = new Vector2(24f, 24f); - m_CurveLibraryEditor.showHeader = true; - } - } - - void OnPresetsWasReordered() - { - InternalEditorUtility.RepaintAllViews(); - } - - public override void OnGUI(Rect rect) - { - InitIfNeeded(); - - m_CurveLibraryEditor.OnGUI(rect, m_Curve); - - if (m_WantsToClose) - editorWindow.Close(); - } - - void ItemClickedCallback(int clickCount, object presetObject) - { - AnimationCurve curve = presetObject as AnimationCurve; - if (curve == null) - Debug.LogError("Incorrect object passed " + presetObject); - - m_PresetSelectedCallback(curve); - } - - public override Vector2 GetWindowSize() - { - return new Vector2(240, 330); - } - - void AddDefaultPresetsToLibrary(PresetLibrary presetLibrary) - { - CurvePresetLibrary curveDefaultLib = presetLibrary as CurvePresetLibrary; - if (curveDefaultLib == null) - { - Debug.Log("Incorrect preset library, should be a CurvePresetLibrary but was a " + presetLibrary.GetType()); - return; - } - - List defaults = new List(); - defaults.Add(new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f))); - defaults.Add(new AnimationCurve(CurveEditorWindow.GetLinearKeys())); - defaults.Add(new AnimationCurve(CurveEditorWindow.GetEaseInKeys())); - defaults.Add(new AnimationCurve(CurveEditorWindow.GetEaseOutKeys())); - defaults.Add(new AnimationCurve(CurveEditorWindow.GetEaseInOutKeys())); - - foreach (AnimationCurve preset in defaults) - curveDefaultLib.Add(preset, ""); - } - } -} diff --git a/Editor/Mono/PresetLibraries/DoubleCurvePresetsContentsForPopupWindow.cs b/Editor/Mono/PresetLibraries/DoubleCurvePresetsContentsForPopupWindow.cs deleted file mode 100644 index 57c1b70d37..0000000000 --- a/Editor/Mono/PresetLibraries/DoubleCurvePresetsContentsForPopupWindow.cs +++ /dev/null @@ -1,163 +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.Collections.Generic; -using UnityEngine; - -namespace UnityEditor -{ - class DoubleCurvePresetsContentsForPopupWindow : PopupWindowContent - { - PresetLibraryEditor m_CurveLibraryEditor; - PresetLibraryEditorState m_CurveLibraryEditorState; - DoubleCurve m_DoubleCurve; - bool m_WantsToClose = false; - - public DoubleCurve doubleCurveToSave - { - get {return m_DoubleCurve; } - set {m_DoubleCurve = value; } - } - - System.Action m_PresetSelectedCallback; - - public DoubleCurvePresetsContentsForPopupWindow(DoubleCurve doubleCurveToSave, System.Action presetSelectedCallback) - { - m_DoubleCurve = doubleCurveToSave; - m_PresetSelectedCallback = presetSelectedCallback; - } - - public override void OnClose() - { - m_CurveLibraryEditorState.TransferEditorPrefsState(false); - } - - public PresetLibraryEditor GetPresetLibraryEditor() - { - return m_CurveLibraryEditor; - } - - bool IsSingleCurve(DoubleCurve doubleCurve) - { - return doubleCurve.minCurve == null || doubleCurve.minCurve.length == 0; - } - - string GetEditorPrefBaseName() - { - return PresetLibraryLocations.GetParticleCurveLibraryExtension(m_DoubleCurve.IsSingleCurve(), m_DoubleCurve.signedRange); - } - - public void InitIfNeeded() - { - if (m_CurveLibraryEditorState == null) - { - m_CurveLibraryEditorState = new PresetLibraryEditorState(GetEditorPrefBaseName()); - m_CurveLibraryEditorState.TransferEditorPrefsState(true); - } - - if (m_CurveLibraryEditor == null) - { - var extension = PresetLibraryLocations.GetParticleCurveLibraryExtension(m_DoubleCurve.IsSingleCurve(), m_DoubleCurve.signedRange); - var saveLoadHelper = new ScriptableObjectSaveLoadHelper(extension, SaveType.Text); - m_CurveLibraryEditor = new PresetLibraryEditor(saveLoadHelper, m_CurveLibraryEditorState, ItemClickedCallback); - m_CurveLibraryEditor.addDefaultPresets += AddDefaultPresetsToLibrary; - m_CurveLibraryEditor.presetsWasReordered = PresetsWasReordered; - m_CurveLibraryEditor.previewAspect = 4f; - m_CurveLibraryEditor.minMaxPreviewHeight = new Vector2(24f, 24f); - m_CurveLibraryEditor.showHeader = true; - } - } - - void PresetsWasReordered() - { - InspectorWindow.RepaintAllInspectors(); - } - - public override void OnGUI(Rect rect) - { - InitIfNeeded(); - - m_CurveLibraryEditor.OnGUI(rect, m_DoubleCurve); - - if (m_WantsToClose) - editorWindow.Close(); - } - - void ItemClickedCallback(int clickCount, object presetObject) - { - DoubleCurve doubleCurve = presetObject as DoubleCurve; - if (doubleCurve == null) - Debug.LogError("Incorrect object passed " + presetObject); - - m_PresetSelectedCallback(doubleCurve); - } - - public override Vector2 GetWindowSize() - { - return new Vector2(240, 330); - } - - void AddDefaultPresetsToLibrary(PresetLibrary presetLibrary) - { - DoubleCurvePresetLibrary doubleCurveDefaultLib = presetLibrary as DoubleCurvePresetLibrary; - if (doubleCurveDefaultLib == null) - { - Debug.Log("Incorrect preset library, should be a DoubleCurvePresetLibrary but was a " + presetLibrary.GetType()); - return; - } - - bool signedRange = m_DoubleCurve.signedRange; - List defaults = new List(); - if (IsSingleCurve(m_DoubleCurve)) - { - defaults = GetUnsignedSingleCurveDefaults(signedRange); - } - else - { - if (signedRange) - { - defaults = GetSignedDoubleCurveDefaults(); - } - else - { - defaults = GetUnsignedDoubleCurveDefaults(); - } - } - - foreach (DoubleCurve preset in defaults) - { - doubleCurveDefaultLib.Add(preset, ""); - } - } - - static List GetUnsignedSingleCurveDefaults(bool signedRange) - { - List defaults = new List(); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetLinearKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetLinearMirrorKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInMirrorKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseOutKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseOutMirrorKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInOutKeys()), signedRange)); - defaults.Add(new DoubleCurve(null, new AnimationCurve(CurveEditorWindow.GetEaseInOutMirrorKeys()), signedRange)); - return defaults; - } - - static List GetUnsignedDoubleCurveDefaults() - { - List defaults = new List(); - defaults.Add(new DoubleCurve(new AnimationCurve(CurveEditorWindow.GetConstantKeys(0f)), new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), false)); - return defaults; - } - - static List GetSignedDoubleCurveDefaults() - { - List defaults = new List(); - defaults.Add(new DoubleCurve(new AnimationCurve(CurveEditorWindow.GetConstantKeys(-1f)), new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), true)); - return defaults; - } - } -} diff --git a/Editor/Mono/PresetLibraries/PopupWindowContentForNewLibrary.cs b/Editor/Mono/PresetLibraries/PopupWindowContentForNewLibrary.cs deleted file mode 100644 index 092c4948c8..0000000000 --- a/Editor/Mono/PresetLibraries/PopupWindowContentForNewLibrary.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 UnityEditorInternal; -using UnityEngine; - -namespace UnityEditor -{ - class PopupWindowContentForNewLibrary : PopupWindowContent - { - string m_NewLibraryName = ""; - int m_SelectedIndexInPopup = 0; - string m_ErrorString = null; - Rect m_WantedSize; - - Func m_CreateLibraryCallback; - - class Texts - { - public GUIContent header = EditorGUIUtility.TrTextContent("Create New Library"); - public GUIContent name = EditorGUIUtility.TrTextContent("Name"); - public GUIContent location = EditorGUIUtility.TrTextContent("Location"); - public GUIContent[] fileLocations = new[] {EditorGUIUtility.TrTextContent("Preferences Folder"), EditorGUIUtility.TrTextContent("Project Folder")}; - public PresetFileLocation[] fileLocationOrder = new[] { PresetFileLocation.PreferencesFolder, PresetFileLocation.ProjectFolder }; // must match order of fileLocations above - } - static Texts s_Texts; - - public PopupWindowContentForNewLibrary(Func createLibraryCallback) - { - m_CreateLibraryCallback = createLibraryCallback; - } - - public override void OnGUI(Rect rect) - { - if (s_Texts == null) - s_Texts = new Texts(); - - KeyboardHandling(editorWindow); - - float labelWidth = 80f; - - Rect size = EditorGUILayout.BeginVertical(); - if (Event.current.type != EventType.Layout) - m_WantedSize = size; - - // Header - GUILayout.BeginHorizontal(); - { - GUILayout.Label(s_Texts.header, EditorStyles.boldLabel); - } GUILayout.EndHorizontal(); - - EditorGUI.BeginChangeCheck(); - { - // Name - GUILayout.BeginHorizontal(); - { - GUILayout.Label(s_Texts.name, GUILayout.Width(labelWidth)); - - EditorGUI.FocusTextInControl("NewLibraryName"); - GUI.SetNextControlName("NewLibraryName"); - m_NewLibraryName = GUILayout.TextField(m_NewLibraryName); - } GUILayout.EndHorizontal(); - - // Location - GUILayout.BeginHorizontal(); - { - GUILayout.Label(s_Texts.location, GUILayout.Width(labelWidth)); - m_SelectedIndexInPopup = EditorGUILayout.Popup(m_SelectedIndexInPopup, s_Texts.fileLocations); - } - GUILayout.EndHorizontal(); - } - if (EditorGUI.EndChangeCheck()) - m_ErrorString = null; - - // Create - GUILayout.BeginHorizontal(); - { - if (!string.IsNullOrEmpty(m_ErrorString)) - { - Color orgColor = GUI.color; - GUI.color = new Color(1, 0.8f, 0.8f); - GUILayout.Label(GUIContent.Temp(m_ErrorString), EditorStyles.helpBox); - GUI.color = orgColor; - } - - GUILayout.FlexibleSpace(); - if (GUILayout.Button(GUIContent.Temp("Create"))) - { - CreateLibraryAndCloseWindow(editorWindow); - } - } GUILayout.EndHorizontal(); - - GUILayout.Space(15); - - EditorGUILayout.EndVertical(); - } - - public override Vector2 GetWindowSize() - { - return new Vector2(350, m_WantedSize.height > 0 ? m_WantedSize.height : 90); - } - - void KeyboardHandling(EditorWindow editorWindow) - { - Event evt = Event.current; - switch (evt.type) - { - case EventType.KeyDown: - switch (evt.keyCode) - { - case KeyCode.KeypadEnter: - case KeyCode.Return: - CreateLibraryAndCloseWindow(editorWindow); - break; - case KeyCode.Escape: - editorWindow.Close(); - break; - } - break; - } - } - - void CreateLibraryAndCloseWindow(EditorWindow editorWindow) - { - PresetFileLocation fileLocation = s_Texts.fileLocationOrder[m_SelectedIndexInPopup]; - m_ErrorString = m_CreateLibraryCallback(m_NewLibraryName, fileLocation); - if (string.IsNullOrEmpty(m_ErrorString)) - editorWindow.Close(); - } - } -} diff --git a/Editor/Mono/PresetLibraries/PresetLibrary.cs b/Editor/Mono/PresetLibraries/PresetLibrary.cs deleted file mode 100644 index ec4d8de16a..0000000000 --- a/Editor/Mono/PresetLibraries/PresetLibrary.cs +++ /dev/null @@ -1,49 +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 System.Collections.Generic; - -namespace UnityEditor -{ - // Derive and implement interface for your own preset library. See GradientPresetLibrary.cs for example. - internal abstract class PresetLibrary : ScriptableObject - { - public abstract int Count(); - public abstract object GetPreset(int index); - public abstract void Add(object presetObject, string presetName); - public abstract void Replace(int index, object newPresetObject); - public abstract void Remove(int index); - public abstract void Move(int index, int destIndex, bool insertAfterDestIndex); - public abstract void Draw(Rect rect, int index); - public abstract void Draw(Rect rect, object presetObject); - public abstract string GetName(int index); - public abstract void SetName(int index, string name); - } - - - internal static class PresetLibraryHelpers - { - public static void MoveListItem(List list, int index, int destIndex, bool insertAfterDestIndex) - { - if (index < 0 || destIndex < 0) - { - Debug.LogError("Invalid preset move"); - return; - } - - if (index == destIndex) - return; - - if (destIndex > index) - destIndex--; - if (insertAfterDestIndex && destIndex < list.Count - 1) - destIndex++; - - var item = list[index]; - list.RemoveAt(index); - list.Insert(destIndex, item); - } - } -} // UnityEditor diff --git a/Editor/Mono/PresetLibraries/PresetLibraryEditorMenu.cs b/Editor/Mono/PresetLibraries/PresetLibraryEditorMenu.cs deleted file mode 100644 index 60151030b2..0000000000 --- a/Editor/Mono/PresetLibraries/PresetLibraryEditorMenu.cs +++ /dev/null @@ -1,130 +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.IO; -using UnityEngine; -using UnityEditorInternal; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal partial class PresetLibraryEditor where T : PresetLibrary - { - class SettingsMenu - { - static PresetLibraryEditor s_Owner; - - class ViewModeData - { - public GUIContent text; - public int itemHeight; - public PresetLibraryEditorState.ItemViewMode viewmode; - } - - public static void Show(Rect activatorRect, PresetLibraryEditor owner) - { - s_Owner = owner; - - GenericMenu menu = new GenericMenu(); - - // View modes - int minItemHeight = (int)s_Owner.minMaxPreviewHeight.x; - int maxItemHeight = (int)s_Owner.minMaxPreviewHeight.y; - List viewModeData; - if (minItemHeight == maxItemHeight) - { - viewModeData = new List - { - new ViewModeData {text = EditorGUIUtility.TrTextContent("Grid"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.Grid}, - new ViewModeData {text = EditorGUIUtility.TrTextContent("List"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.List}, - }; - } - else - { - viewModeData = new List - { - new ViewModeData {text = EditorGUIUtility.TrTextContent("Small Grid"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.Grid}, - new ViewModeData {text = EditorGUIUtility.TrTextContent("Large Grid"), itemHeight = maxItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.Grid}, - new ViewModeData {text = EditorGUIUtility.TrTextContent("Small List"), itemHeight = minItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.List}, - new ViewModeData {text = EditorGUIUtility.TrTextContent("Large List"), itemHeight = maxItemHeight, viewmode = PresetLibraryEditorState.ItemViewMode.List} - }; - } - - for (int i = 0; i < viewModeData.Count; ++i) - { - bool currentSelected = s_Owner.itemViewMode == viewModeData[i].viewmode && (int)s_Owner.previewHeight == viewModeData[i].itemHeight; - menu.AddItem(viewModeData[i].text, currentSelected, ViewModeChange, viewModeData[i]); - } - menu.AddSeparator(""); - - // Available libraries (show user libraries first then project libraries) - List preferencesLibs; - List projectLibs; - PresetLibraryManager.instance.GetAvailableLibraries(s_Owner.m_SaveLoadHelper, out preferencesLibs, out projectLibs); - preferencesLibs.Sort(); - projectLibs.Sort(); - - string currentLibWithExtension = s_Owner.currentLibraryWithoutExtension + "." + s_Owner.m_SaveLoadHelper.fileExtensionWithoutDot; - - string projectFolderTag = " (Project)"; - foreach (string libPath in preferencesLibs) - { - string libName = Path.GetFileNameWithoutExtension(libPath); - menu.AddItem(new GUIContent(libName), currentLibWithExtension == libPath, LibraryModeChange, libPath); - } - foreach (string libPath in projectLibs) - { - string libName = Path.GetFileNameWithoutExtension(libPath); - menu.AddItem(new GUIContent(libName + projectFolderTag), currentLibWithExtension == libPath, LibraryModeChange, libPath); - } - menu.AddSeparator(""); - menu.AddItem(EditorGUIUtility.TrTextContent("Create New Library..."), false, CreateLibrary, 0); - if (HasDefaultPresets()) - { - menu.AddSeparator(""); - menu.AddItem(EditorGUIUtility.TrTextContent("Add Factory Presets To Current Library"), false, AddDefaultPresetsToCurrentLibrary, 0); - } - menu.AddSeparator(""); - menu.AddItem(EditorGUIUtility.TrTextContent("Reveal Current Library Location"), false, RevealCurrentLibrary, 0); - menu.DropDown(activatorRect); - } - - static void ViewModeChange(object userData) - { - ViewModeData viewModeData = (ViewModeData)userData; - s_Owner.itemViewMode = viewModeData.viewmode; - s_Owner.previewHeight = viewModeData.itemHeight; - } - - static void LibraryModeChange(object userData) - { - string libPath = (string)userData; - s_Owner.currentLibraryWithoutExtension = libPath; - } - - static void CreateLibrary(object userData) - { - s_Owner.wantsToCreateLibrary = true; - } - - static void RevealCurrentLibrary(object userData) - { - s_Owner.RevealCurrentLibrary(); - } - - static bool HasDefaultPresets() - { - return s_Owner.addDefaultPresets != null; - } - - static void AddDefaultPresetsToCurrentLibrary(object userData) - { - if (s_Owner.addDefaultPresets != null) - s_Owner.addDefaultPresets(s_Owner.GetCurrentLib()); - - s_Owner.SaveCurrentLib(); - } - } - } -} // UnityEditor diff --git a/Editor/Mono/PresetLibraries/PresetLibraryManager.cs b/Editor/Mono/PresetLibraries/PresetLibraryManager.cs deleted file mode 100644 index 606c0fdcf7..0000000000 --- a/Editor/Mono/PresetLibraries/PresetLibraryManager.cs +++ /dev/null @@ -1,289 +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.IO; -using UnityEngine; -using System.Collections.Generic; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal enum PresetFileLocation { PreferencesFolder, ProjectFolder } // ProjectFolder: We look in all Editor folders in Assets - - internal static class PresetLibraryLocations - { - public static string defaultLibraryLocation - { - get { return GetDefaultFilePathForFileLocation(PresetFileLocation.PreferencesFolder); } - } - - public static string defaultPresetLibraryPath - { - get { return Path.Combine(defaultLibraryLocation, defaultLibraryName); } - } - - public static string defaultLibraryName - { - get { return "Default"; } - } - - public static List GetAvailableFilesWithExtensionOnTheHDD(PresetFileLocation fileLocation, string fileExtensionWithoutDot) - { - List folderPaths = GetDirectoryPaths(fileLocation); - List files = GetFilesWithExentionFromFolders(folderPaths, fileExtensionWithoutDot); - for (int i = 0; i < files.Count; ++i) - files[i] = ConvertToUnitySeperators(files[i]); - return files; - } - - public static string GetDefaultFilePathForFileLocation(PresetFileLocation fileLocation) - { - switch (fileLocation) - { - case PresetFileLocation.PreferencesFolder: - return InternalEditorUtility.unityPreferencesFolder + "/Presets/"; - - case PresetFileLocation.ProjectFolder: - return "Assets/Editor/"; - - default: - Debug.LogError("Enum not handled!"); - return ""; - } - } - - static List GetDirectoryPaths(PresetFileLocation fileLocation) - { - List folderPaths = new List(); - switch (fileLocation) - { - case PresetFileLocation.PreferencesFolder: - folderPaths.Add(GetDefaultFilePathForFileLocation(PresetFileLocation.PreferencesFolder)); - break; - - case PresetFileLocation.ProjectFolder: - string[] editorFolders = Directory.GetDirectories("Assets/", "Editor", SearchOption.AllDirectories); - folderPaths.AddRange(editorFolders); - break; - - default: - Debug.LogError("Enum not handled!"); - break; - } - - return folderPaths; - } - - static List GetFilesWithExentionFromFolders(List folderPaths, string fileExtensionWithoutDot) - { - // First get all potential files - var files = new List(); - foreach (string editorFolder in folderPaths) - { - string[] filePaths = Directory.GetFiles(editorFolder, "*." + fileExtensionWithoutDot); - files.AddRange(filePaths); - } - return files; - } - - public static PresetFileLocation GetFileLocationFromPath(string path) - { - if (path.Contains(InternalEditorUtility.unityPreferencesFolder)) - return PresetFileLocation.PreferencesFolder; - if (path.Contains("Assets/")) - return PresetFileLocation.ProjectFolder; - - Debug.LogError("Could not determine preset file location type " + path); - return PresetFileLocation.ProjectFolder; - } - - static string ConvertToUnitySeperators(string path) - { - return path.Replace('\\', '/'); - } - - static public string GetParticleCurveLibraryExtension(bool singleCurve, bool signedRange) - { - string extension = "particle"; - if (singleCurve) - extension += "Curves"; - else - extension += "DoubleCurves"; - - if (signedRange) - extension += "Signed"; - else - extension += ""; - - return extension; - } - - static public string GetCurveLibraryExtension(bool normalized) - { - if (normalized) - return "curvesNormalized"; - return "curves"; - } - } - - - internal class PresetLibraryManager : ScriptableSingleton - { - static string s_LastError = null; - private List m_LibraryCaches = new List(); - - private HideFlags libraryHideFlag - { - get { return HideFlags.DontSave; } // Use of DontSave prevents library from being nulled when going out of playmode - } - - // Returns lists of filepaths for libraries with a given extension found on the HDD - public void GetAvailableLibraries(ScriptableObjectSaveLoadHelper helper, out List preferencesLibs, out List projectLibs) where T : ScriptableObject - { - preferencesLibs = PresetLibraryLocations.GetAvailableFilesWithExtensionOnTheHDD(PresetFileLocation.PreferencesFolder, helper.fileExtensionWithoutDot); - projectLibs = PresetLibraryLocations.GetAvailableFilesWithExtensionOnTheHDD(PresetFileLocation.ProjectFolder, helper.fileExtensionWithoutDot); - } - - string GetLibaryNameFromPath(string filePath) - { - return Path.GetFileNameWithoutExtension(filePath); - } - - public T CreateLibrary(ScriptableObjectSaveLoadHelper helper, string presetLibraryPathWithoutExtension) where T : ScriptableObject - { - string libraryName = GetLibaryNameFromPath(presetLibraryPathWithoutExtension); - if (!InternalEditorUtility.IsValidFileName(libraryName)) - { - string invalid = InternalEditorUtility.GetDisplayStringOfInvalidCharsOfFileName(libraryName); - if (invalid.Length > 0) - s_LastError = string.Format("A library filename cannot contain the following character{0}: {1}", invalid.Length > 1 ? "s" : "", invalid); - else - s_LastError = "Invalid filename"; - return null; - } - - if (GetLibrary(helper, presetLibraryPathWithoutExtension) != null) - { - s_LastError = "Library '" + libraryName + "' already exists! Ensure a unique name."; - return null; - } - - T library = helper.Create(); - library.hideFlags = libraryHideFlag; - LibraryCache set = GetPresetLibraryCache(helper.fileExtensionWithoutDot); - set.loadedLibraries.Add(library); - set.loadedLibraryIDs.Add(presetLibraryPathWithoutExtension); - s_LastError = null; - return library; - } - - public T GetLibrary(ScriptableObjectSaveLoadHelper helper, string presetLibraryPathWithoutExtension) where T : ScriptableObject - { - LibraryCache set = GetPresetLibraryCache(helper.fileExtensionWithoutDot); - - // Did we already load the lib - for (int i = 0; i < set.loadedLibraryIDs.Count; ++i) - { - if (set.loadedLibraryIDs[i] == presetLibraryPathWithoutExtension) - { - if (set.loadedLibraries[i] != null) - return set.loadedLibraries[i] as T; - else - { - // The library has been destroyed. Remove it from the lists so it can be reloaded - set.loadedLibraries.RemoveAt(i); - set.loadedLibraryIDs.RemoveAt(i); - Debug.LogError("Invalid library detected: Reload " + set.loadedLibraryIDs[i] + " from HDD"); - break; - } - } - } - - // Debug.Log ("Not loaded yet " + typeof(T)); - - // Can we find on the hdd - T library = helper.Load(presetLibraryPathWithoutExtension); - - if (library != null) - { - library.hideFlags = libraryHideFlag; // ensure correct hideflag with pre 4.3 versions - set.loadedLibraries.Add(library); - set.loadedLibraryIDs.Add(presetLibraryPathWithoutExtension); - return library; - } - - // Debug.Log ("Not found on hdd"); - - return null; - } - - public void UnloadAllLibrariesFor(ScriptableObjectSaveLoadHelper helper) where T : ScriptableObject - { - for (int i = 0; i < m_LibraryCaches.Count; ++i) - { - if (m_LibraryCaches[i].identifier == helper.fileExtensionWithoutDot) - { - m_LibraryCaches[i].UnloadScriptableObjects(); - m_LibraryCaches.RemoveAt(i); - break; - } - } - } - - public void SaveLibrary(ScriptableObjectSaveLoadHelper helper, T library, string presetLibraryPathWithoutExtension) where T : ScriptableObject - { - bool fileExistedBeforeSaving = File.Exists(presetLibraryPathWithoutExtension + "." + helper.fileExtensionWithoutDot); - - helper.Save(library, presetLibraryPathWithoutExtension); - - if (!fileExistedBeforeSaving) - AssetDatabase.Refresh(); - } - - public string GetLastError() - { - string errorString = s_LastError; - s_LastError = null; - return errorString; - } - - private LibraryCache GetPresetLibraryCache(string identifier) - { - foreach (LibraryCache libraryCache in m_LibraryCaches) - if (libraryCache.identifier == identifier) - return libraryCache; - - // Add if not found - LibraryCache set = new LibraryCache(identifier); - m_LibraryCaches.Add(set); - return set; - } - - private class LibraryCache - { - string m_Identifier; // Identifier for a group of libraries. For now its the file extension - - // Should have been a Dictonary but we cannot serialize those properly yet... - List m_LoadedLibraries = new List(); // 1:1 with m_LoadedLibraryIDs - List m_LoadedLibraryIDs = new List(); // 1:1 with m_LoadedLibraries - - // Interface - public string identifier { get { return m_Identifier; } } - public List loadedLibraries { get { return m_LoadedLibraries; } } - public List loadedLibraryIDs { get { return m_LoadedLibraryIDs; } } // List of paths without extension - public void UnloadScriptableObjects() - { - foreach (ScriptableObject sobj in m_LoadedLibraries) - ScriptableObject.DestroyImmediate(sobj); - m_LoadedLibraries.Clear(); - m_LoadedLibraryIDs.Clear(); - } - - public LibraryCache(string identifier) - { - m_Identifier = identifier; - } - } - } -} diff --git a/Editor/Mono/PresetLibraries/ScriptableObjectSaveLoadHelper.cs b/Editor/Mono/PresetLibraries/ScriptableObjectSaveLoadHelper.cs deleted file mode 100644 index 42eaeab8b9..0000000000 --- a/Editor/Mono/PresetLibraries/ScriptableObjectSaveLoadHelper.cs +++ /dev/null @@ -1,88 +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 UnityEditorInternal; -using System.IO; - -namespace UnityEditor -{ - public enum SaveType { Binary, Text } - - - // Class for making it easy to save and load ScriptableObjects manually (i.e without using the AssetDatabase) - - class ScriptableObjectSaveLoadHelper where T : ScriptableObject - { - public string fileExtensionWithoutDot { get; private set; } - private SaveType saveType { get; set; } - - public ScriptableObjectSaveLoadHelper(string fileExtensionWithoutDot, SaveType saveType) - { - this.saveType = saveType; - this.fileExtensionWithoutDot = fileExtensionWithoutDot.TrimStart('.'); // Ensure no dot - } - - // If 'filePath' does not include an extension the local 'fileExtensionWithoutDot' is used. - public T Load(string filePath) - { - filePath = AppendFileExtensionIfNeeded(filePath); - - // Try to load - if (!string.IsNullOrEmpty(filePath)) - { - Object[] objects = InternalEditorUtility.LoadSerializedFileAndForget(filePath); - if (objects != null && objects.Length > 0) - return objects[0] as T; - } - - return null; - } - - public T Create() - { - T t = ScriptableObject.CreateInstance(); - return t; - } - - // If 'filePath' does not include an extension the local 'fileExtensionWithoutDot' is used. - public void Save(T t, string filePath) - { - if (t == null) - { - Debug.LogError("Cannot save scriptableObject: its null!"); - return; - } - - if (string.IsNullOrEmpty(filePath)) - { - Debug.LogError("Invalid path: '" + filePath + "'"); - return; - } - - // Ensure folder exists - string folderPath = Path.GetDirectoryName(filePath); - if (!Directory.Exists(folderPath)) - { - Directory.CreateDirectory(folderPath); - } - - filePath = AppendFileExtensionIfNeeded(filePath); - - InternalEditorUtility.SaveToSerializedFileAndForget(new[] { t }, filePath, saveType == SaveType.Text); - } - - public override string ToString() - { - return string.Format("{0}, {1}", fileExtensionWithoutDot, saveType); - } - - string AppendFileExtensionIfNeeded(string path) - { - if (!Path.HasExtension(path) && !string.IsNullOrEmpty(fileExtensionWithoutDot)) - return path + "." + fileExtensionWithoutDot; - return path; - } - } -} diff --git a/Editor/Mono/ProjectBrowser.cs b/Editor/Mono/ProjectBrowser.cs index 513ebb2d6e..6229ff1dda 100644 --- a/Editor/Mono/ProjectBrowser.cs +++ b/Editor/Mono/ProjectBrowser.cs @@ -1277,6 +1277,13 @@ void AssetTreeKeyboardInputCallback() OpenAssetSelection(Selection.instanceIDs); } break; + case KeyCode.Delete: + if (Event.current.shift) + { + DeleteSelectedAssets(false); + Event.current.Use(); + } + break; } } } @@ -2266,7 +2273,7 @@ void AssetLabelsDropDown() Rect r = GUILayoutUtility.GetRect(s_Styles.m_FilterByLabel, EditorStyles.toolbarButton); if (EditorGUI.DropdownButton(r, s_Styles.m_FilterByLabel, FocusType.Passive, EditorStyles.toolbarButton)) { - PopupWindow.Show(r, new PopupList(m_AssetLabels), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(r, new PopupList(m_AssetLabels)); } } diff --git a/Editor/Mono/ProjectWindow/ProjectWindowUtil.cs b/Editor/Mono/ProjectWindow/ProjectWindowUtil.cs index f1543afe72..9277fffd56 100644 --- a/Editor/Mono/ProjectWindow/ProjectWindowUtil.cs +++ b/Editor/Mono/ProjectWindow/ProjectWindowUtil.cs @@ -107,15 +107,6 @@ public override void Action(int instanceId, string pathName, string resourceFile } } - internal class DoCreatePrefab : EndNameEditAction - { - public override void Action(int instanceId, string pathName, string resourceFile) - { - Object o = PrefabUtility.CreateEmptyPrefab(pathName); - ProjectWindowUtil.ShowCreatedAsset(o); - } - } - internal class DoCreatePrefabVariant : EndNameEditAction { public override void Action(int instanceId, string pathName, string resourceFile) @@ -257,12 +248,6 @@ public static void CreateScene() StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "New Scene.unity", EditorGUIUtility.FindTexture(typeof(SceneAsset)), null); } - // Create a prefab - public static void CreatePrefab() - { - StartNameEditingIfProjectWindowExists(0, ScriptableObject.CreateInstance(), "New Prefab.prefab", EditorGUIUtility.IconContent("Prefab Icon").image as Texture2D, null); - } - [MenuItem("Assets/Create/Prefab Variant", true)] static bool CreatePrefabVariantValidation() { diff --git a/Editor/Mono/RagdollBuilder.cs b/Editor/Mono/RagdollBuilder.cs deleted file mode 100644 index 785a2c58b7..0000000000 --- a/Editor/Mono/RagdollBuilder.cs +++ /dev/null @@ -1,531 +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 UnityEditor; -using System.Collections; -using System; - -#pragma warning disable 649 - -namespace UnityEditor -{ - class RagdollBuilder : ScriptableWizard - { - public Transform pelvis; - - public Transform leftHips = null; - public Transform leftKnee = null; - public Transform leftFoot = null; - - public Transform rightHips = null; - public Transform rightKnee = null; - public Transform rightFoot = null; - - public Transform leftArm = null; - public Transform leftElbow = null; - - public Transform rightArm = null; - public Transform rightElbow = null; - - public Transform middleSpine = null; - public Transform head = null; - - - public float totalMass = 20; - public float strength = 0.0F; - - Vector3 right = Vector3.right; - Vector3 up = Vector3.up; - Vector3 forward = Vector3.forward; - - Vector3 worldRight = Vector3.right; - Vector3 worldUp = Vector3.up; - Vector3 worldForward = Vector3.forward; - public bool flipForward = false; - - class BoneInfo - { - public string name; - - public Transform anchor; - public CharacterJoint joint; - public BoneInfo parent; - - public float minLimit; - public float maxLimit; - public float swingLimit; - - public Vector3 axis; - public Vector3 normalAxis; - - public float radiusScale; - public Type colliderType; - - public ArrayList children = new ArrayList(); - public float density; - public float summedMass;// The mass of this and all children bodies - } - - ArrayList bones; - BoneInfo rootBone; - - string CheckConsistency() - { - PrepareBones(); - Hashtable map = new Hashtable(); - foreach (BoneInfo bone in bones) - { - if (bone.anchor) - { - if (map[bone.anchor] != null) - { - BoneInfo oldBone = (BoneInfo)map[bone.anchor]; - return String.Format("{0} and {1} may not be assigned to the same bone.", bone.name, oldBone.name); - } - map[bone.anchor] = bone; - } - } - - foreach (BoneInfo bone in bones) - { - if (bone.anchor == null) - return String.Format("{0} has not been assigned yet.\n", bone.name); - } - - return ""; - } - - void OnDrawGizmos() - { - if (pelvis) - { - Gizmos.color = Color.red; Gizmos.DrawRay(pelvis.position, pelvis.TransformDirection(right)); - Gizmos.color = Color.green; Gizmos.DrawRay(pelvis.position, pelvis.TransformDirection(up)); - Gizmos.color = Color.blue; Gizmos.DrawRay(pelvis.position, pelvis.TransformDirection(forward)); - } - } - - [MenuItem("GameObject/3D Object/Ragdoll...", false, 2000)] - static void CreateWizard() - { - ScriptableWizard.DisplayWizard("Create Ragdoll"); - } - - void DecomposeVector(out Vector3 normalCompo, out Vector3 tangentCompo, Vector3 outwardDir, Vector3 outwardNormal) - { - outwardNormal = outwardNormal.normalized; - normalCompo = outwardNormal * Vector3.Dot(outwardDir, outwardNormal); - tangentCompo = outwardDir - normalCompo; - } - - void CalculateAxes() - { - if (head != null && pelvis != null) - up = CalculateDirectionAxis(pelvis.InverseTransformPoint(head.position)); - if (rightElbow != null && pelvis != null) - { - Vector3 removed, temp; - DecomposeVector(out temp, out removed, pelvis.InverseTransformPoint(rightElbow.position), up); - right = CalculateDirectionAxis(removed); - } - - forward = Vector3.Cross(right, up); - if (flipForward) - forward = -forward; - } - - void OnWizardUpdate() - { - errorString = CheckConsistency(); - CalculateAxes(); - - if (errorString.Length != 0) - { - helpString = "Drag all bones from the hierarchy into their slots.\nMake sure your character is in T-Stand.\n"; - } - else - { - helpString = "Make sure your character is in T-Stand.\nMake sure the blue axis faces in the same direction the chracter is looking.\nUse flipForward to flip the direction"; - } - - isValid = errorString.Length == 0; - } - - void PrepareBones() - { - if (pelvis) - { - worldRight = pelvis.TransformDirection(right); - worldUp = pelvis.TransformDirection(up); - worldForward = pelvis.TransformDirection(forward); - } - - bones = new ArrayList(); - - rootBone = new BoneInfo(); - rootBone.name = "Pelvis"; - rootBone.anchor = pelvis; - rootBone.parent = null; - rootBone.density = 2.5F; - bones.Add(rootBone); - - AddMirroredJoint("Hips", leftHips, rightHips, "Pelvis", worldRight, worldForward, -20, 70, 30, typeof(CapsuleCollider), 0.3F, 1.5F); - AddMirroredJoint("Knee", leftKnee, rightKnee, "Hips", worldRight, worldForward, -80, 0, 0, typeof(CapsuleCollider), 0.25F, 1.5F); - - AddJoint("Middle Spine", middleSpine, "Pelvis", worldRight, worldForward, -20, 20, 10, null, 1, 2.5F); - - AddMirroredJoint("Arm", leftArm, rightArm, "Middle Spine", worldUp, worldForward, -70, 10, 50, typeof(CapsuleCollider), 0.25F, 1.0F); - AddMirroredJoint("Elbow", leftElbow, rightElbow, "Arm", worldForward, worldUp, -90, 0, 0, typeof(CapsuleCollider), 0.20F, 1.0F); - - AddJoint("Head", head, "Middle Spine", worldRight, worldForward, -40, 25, 25, null, 1, 1.0F); - } - - void OnWizardCreate() - { - Cleanup(); - BuildCapsules(); - AddBreastColliders(); - AddHeadCollider(); - - BuildBodies(); - BuildJoints(); - CalculateMass(); - } - - BoneInfo FindBone(string name) - { - foreach (BoneInfo bone in bones) - { - if (bone.name == name) - return bone; - } - return null; - } - - void AddMirroredJoint(string name, Transform leftAnchor, Transform rightAnchor, string parent, Vector3 worldTwistAxis, Vector3 worldSwingAxis, float minLimit, float maxLimit, float swingLimit, Type colliderType, float radiusScale, float density) - { - AddJoint("Left " + name, leftAnchor, parent, worldTwistAxis, worldSwingAxis, minLimit, maxLimit, swingLimit, colliderType, radiusScale, density); - AddJoint("Right " + name, rightAnchor, parent, worldTwistAxis, worldSwingAxis, minLimit, maxLimit, swingLimit, colliderType, radiusScale, density); - } - - void AddJoint(string name, Transform anchor, string parent, Vector3 worldTwistAxis, Vector3 worldSwingAxis, float minLimit, float maxLimit, float swingLimit, Type colliderType, float radiusScale, float density) - { - BoneInfo bone = new BoneInfo(); - bone.name = name; - bone.anchor = anchor; - bone.axis = worldTwistAxis; - bone.normalAxis = worldSwingAxis; - bone.minLimit = minLimit; - bone.maxLimit = maxLimit; - bone.swingLimit = swingLimit; - bone.density = density; - bone.colliderType = colliderType; - bone.radiusScale = radiusScale; - - if (FindBone(parent) != null) - bone.parent = FindBone(parent); - else if (name.StartsWith("Left")) - bone.parent = FindBone("Left " + parent); - else if (name.StartsWith("Right")) - bone.parent = FindBone("Right " + parent); - - - bone.parent.children.Add(bone); - bones.Add(bone); - } - - void BuildCapsules() - { - foreach (BoneInfo bone in bones) - { - if (bone.colliderType != typeof(CapsuleCollider)) - continue; - - int direction; - float distance; - if (bone.children.Count == 1) - { - BoneInfo childBone = (BoneInfo)bone.children[0]; - Vector3 endPoint = childBone.anchor.position; - CalculateDirection(bone.anchor.InverseTransformPoint(endPoint), out direction, out distance); - } - else - { - Vector3 endPoint = (bone.anchor.position - bone.parent.anchor.position) + bone.anchor.position; - CalculateDirection(bone.anchor.InverseTransformPoint(endPoint), out direction, out distance); - - if (bone.anchor.GetComponentsInChildren(typeof(Transform)).Length > 1) - { - Bounds bounds = new Bounds(); - foreach (Transform child in bone.anchor.GetComponentsInChildren(typeof(Transform))) - { - bounds.Encapsulate(bone.anchor.InverseTransformPoint(child.position)); - } - - if (distance > 0) - distance = bounds.max[direction]; - else - distance = bounds.min[direction]; - } - } - - CapsuleCollider collider = (CapsuleCollider)bone.anchor.gameObject.AddComponent(); - collider.direction = direction; - - Vector3 center = Vector3.zero; - center[direction] = distance * 0.5F; - collider.center = center; - collider.height = Mathf.Abs(distance); - collider.radius = Mathf.Abs(distance * bone.radiusScale); - } - } - - void Cleanup() - { - foreach (BoneInfo bone in bones) - { - if (!bone.anchor) - continue; - - Component[] joints = bone.anchor.GetComponentsInChildren(typeof(Joint)); - foreach (Joint joint in joints) - DestroyImmediate(joint); - - Component[] bodies = bone.anchor.GetComponentsInChildren(typeof(Rigidbody)); - foreach (Rigidbody body in bodies) - DestroyImmediate(body); - - Component[] colliders = bone.anchor.GetComponentsInChildren(typeof(Collider)); - foreach (Collider collider in colliders) - DestroyImmediate(collider); - } - } - - void BuildBodies() - { - foreach (BoneInfo bone in bones) - { - bone.anchor.gameObject.AddComponent(); - bone.anchor.GetComponent().mass = bone.density; - } - } - - void BuildJoints() - { - foreach (BoneInfo bone in bones) - { - if (bone.parent == null) - continue; - - CharacterJoint joint = bone.anchor.gameObject.AddComponent(); - bone.joint = joint; - - // Setup connection and axis - joint.axis = CalculateDirectionAxis(bone.anchor.InverseTransformDirection(bone.axis)); - joint.swingAxis = CalculateDirectionAxis(bone.anchor.InverseTransformDirection(bone.normalAxis)); - joint.anchor = Vector3.zero; - joint.connectedBody = bone.parent.anchor.GetComponent(); - joint.enablePreprocessing = false; // turn off to handle degenerated scenarios, like spawning inside geometry. - - // Setup limits - SoftJointLimit limit = new SoftJointLimit(); - limit.contactDistance = 0; // default to zero, which automatically sets contact distance. - - limit.limit = bone.minLimit; - joint.lowTwistLimit = limit; - - limit.limit = bone.maxLimit; - joint.highTwistLimit = limit; - - limit.limit = bone.swingLimit; - joint.swing1Limit = limit; - - limit.limit = 0; - joint.swing2Limit = limit; - } - } - - void CalculateMassRecurse(BoneInfo bone) - { - float mass = bone.anchor.GetComponent().mass; - foreach (BoneInfo child in bone.children) - { - CalculateMassRecurse(child); - mass += child.summedMass; - } - bone.summedMass = mass; - } - - void CalculateMass() - { - // Calculate allChildMass by summing all bodies - CalculateMassRecurse(rootBone); - - // Rescale the mass so that the whole character weights totalMass - float massScale = totalMass / rootBone.summedMass; - foreach (BoneInfo bone in bones) - bone.anchor.GetComponent().mass *= massScale; - - // Recalculate allChildMass by summing all bodies - CalculateMassRecurse(rootBone); - } - - static void CalculateDirection(Vector3 point, out int direction, out float distance) - { - // Calculate longest axis - direction = 0; - if (Mathf.Abs(point[1]) > Mathf.Abs(point[0])) - direction = 1; - if (Mathf.Abs(point[2]) > Mathf.Abs(point[direction])) - direction = 2; - - distance = point[direction]; - } - - static Vector3 CalculateDirectionAxis(Vector3 point) - { - int direction = 0; - float distance; - CalculateDirection(point, out direction, out distance); - Vector3 axis = Vector3.zero; - if (distance > 0) - axis[direction] = 1.0F; - else - axis[direction] = -1.0F; - return axis; - } - - static int SmallestComponent(Vector3 point) - { - int direction = 0; - if (Mathf.Abs(point[1]) < Mathf.Abs(point[0])) - direction = 1; - if (Mathf.Abs(point[2]) < Mathf.Abs(point[direction])) - direction = 2; - return direction; - } - - static int LargestComponent(Vector3 point) - { - int direction = 0; - if (Mathf.Abs(point[1]) > Mathf.Abs(point[0])) - direction = 1; - if (Mathf.Abs(point[2]) > Mathf.Abs(point[direction])) - direction = 2; - return direction; - } - - static int SecondLargestComponent(Vector3 point) - { - int smallest = SmallestComponent(point); - int largest = LargestComponent(point); - if (smallest < largest) - { - int temp = largest; - largest = smallest; - smallest = temp; - } - - if (smallest == 0 && largest == 1) - return 2; - else if (smallest == 0 && largest == 2) - return 1; - else - return 0; - } - - Bounds Clip(Bounds bounds, Transform relativeTo, Transform clipTransform, bool below) - { - int axis = LargestComponent(bounds.size); - - if (Vector3.Dot(worldUp, relativeTo.TransformPoint(bounds.max)) > Vector3.Dot(worldUp, relativeTo.TransformPoint(bounds.min)) == below) - { - Vector3 min = bounds.min; - min[axis] = relativeTo.InverseTransformPoint(clipTransform.position)[axis]; - bounds.min = min; - } - else - { - Vector3 max = bounds.max; - max[axis] = relativeTo.InverseTransformPoint(clipTransform.position)[axis]; - bounds.max = max; - } - return bounds; - } - - Bounds GetBreastBounds(Transform relativeTo) - { - // Pelvis bounds - Bounds bounds = new Bounds(); - bounds.Encapsulate(relativeTo.InverseTransformPoint(leftHips.position)); - bounds.Encapsulate(relativeTo.InverseTransformPoint(rightHips.position)); - bounds.Encapsulate(relativeTo.InverseTransformPoint(leftArm.position)); - bounds.Encapsulate(relativeTo.InverseTransformPoint(rightArm.position)); - Vector3 size = bounds.size; - size[SmallestComponent(bounds.size)] = size[LargestComponent(bounds.size)] / 2.0F; - bounds.size = size; - return bounds; - } - - void AddBreastColliders() - { - // Middle spine and pelvis - if (middleSpine != null && pelvis != null) - { - Bounds bounds; - BoxCollider box; - - // Middle spine bounds - bounds = Clip(GetBreastBounds(pelvis), pelvis, middleSpine, false); - box = (BoxCollider)pelvis.gameObject.AddComponent(); - box.center = bounds.center; - box.size = bounds.size; - - bounds = Clip(GetBreastBounds(middleSpine), middleSpine, middleSpine, true); - box = (BoxCollider)middleSpine.gameObject.AddComponent(); - box.center = bounds.center; - box.size = bounds.size; - } - // Only pelvis - else - { - Bounds bounds = new Bounds(); - bounds.Encapsulate(pelvis.InverseTransformPoint(leftHips.position)); - bounds.Encapsulate(pelvis.InverseTransformPoint(rightHips.position)); - bounds.Encapsulate(pelvis.InverseTransformPoint(leftArm.position)); - bounds.Encapsulate(pelvis.InverseTransformPoint(rightArm.position)); - - Vector3 size = bounds.size; - size[SmallestComponent(bounds.size)] = size[LargestComponent(bounds.size)] / 2.0F; - - BoxCollider box = pelvis.gameObject.AddComponent(); - box.center = bounds.center; - box.size = size; - } - } - - void AddHeadCollider() - { - if (head.GetComponent()) - Destroy(head.GetComponent()); - - float radius = Vector3.Distance(leftArm.transform.position, rightArm.transform.position); - radius /= 4; - - SphereCollider sphere = head.gameObject.AddComponent(); - sphere.radius = radius; - Vector3 center = Vector3.zero; - - int direction; - float distance; - CalculateDirection(head.InverseTransformPoint(pelvis.position), out direction, out distance); - if (distance > 0) - center[direction] = -radius; - else - center[direction] = radius; - sphere.center = center; - } - } -} diff --git a/Editor/Mono/RuntimeInitializeOnLoadManager.bindings.cs b/Editor/Mono/RuntimeInitializeOnLoadManager.bindings.cs deleted file mode 100644 index 47cb74b788..0000000000 --- a/Editor/Mono/RuntimeInitializeOnLoadManager.bindings.cs +++ /dev/null @@ -1,50 +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.Runtime.InteropServices; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - [StructLayout(LayoutKind.Sequential)] - internal sealed partial class RuntimeInitializeMethodInfo - { - string m_FullClassName; - string m_MethodName; - int m_OrderNumber = 0; - bool m_IsUnityClass = false; - - internal string fullClassName { get { return m_FullClassName; } set { m_FullClassName = value; } } - internal string methodName { get { return m_MethodName; } set { m_MethodName = value; } } - internal int orderNumber { get { return m_OrderNumber; } set { m_OrderNumber = value; } } - internal bool isUnityClass { get { return m_IsUnityClass; } set { m_IsUnityClass = value; } } - } - - [StructLayout(LayoutKind.Sequential)] - internal sealed partial class RuntimeInitializeClassInfo - { - string m_AssemblyName; - string m_ClassName; - string[] m_MethodNames; - RuntimeInitializeLoadType[] m_LoadTypes; - - internal string assemblyName { get { return m_AssemblyName; } set { m_AssemblyName = value; } } - internal string className { get { return m_ClassName; } set { m_ClassName = value; } } - internal string[] methodNames { get { return m_MethodNames; } set { m_MethodNames = value; } } - internal RuntimeInitializeLoadType[] loadTypes { get { return m_LoadTypes; } set { m_LoadTypes = value; } } - } - - [NativeHeader("Runtime/Misc/RuntimeInitializeOnLoadManager.h")] - [StaticAccessorAttribute("GetRuntimeInitializeOnLoadManager()")] - internal sealed partial class RuntimeInitializeOnLoadManager - { - extern internal static string[] dontStripClassNames { get; } - - [NativeProperty("RuntimeInitializeClassMethodInfos")] - extern internal static RuntimeInitializeMethodInfo[] methodInfos { get; } - - [NativeMethod("UpdateExecutionOrderNumber")] - extern internal static void UpdateMethodExecutionOrders(int[] changedIndices, int[] changedOrder); - } -} diff --git a/Editor/Mono/SceneHierarchy.cs b/Editor/Mono/SceneHierarchy.cs index dec6f48fed..3534c68484 100644 --- a/Editor/Mono/SceneHierarchy.cs +++ b/Editor/Mono/SceneHierarchy.cs @@ -485,8 +485,6 @@ public virtual void OnEnable() EditorSceneManager.newSceneCreated += OnSceneCreated; EditorSceneManager.sceneOpened += OnSceneOpened; - DoPingRequest(); - m_AllowAlphaNumericalSort = EditorPrefs.GetBool("AllowAlphaNumericHierarchy", false) || !InternalEditorUtility.isHumanControllingUs; // Always allow alphasorting when running automated tests so we can test alpha sorting SetUpSortMethodLists(); diff --git a/Editor/Mono/SceneHierarchySortingWindow.cs b/Editor/Mono/SceneHierarchySortingWindow.cs deleted file mode 100644 index 9a6f30a01a..0000000000 --- a/Editor/Mono/SceneHierarchySortingWindow.cs +++ /dev/null @@ -1,150 +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; - -namespace UnityEditor -{ - internal class SceneHierarchySortingWindow : EditorWindow - { - public delegate void OnSelectCallback(InputData element); - - private class Styles - { - public GUIStyle background = "grey_border"; - public GUIStyle menuItem = "MenuItem"; - } - - public class InputData - { - public string m_TypeName; - public string m_Name; - public bool m_Selected; - } - - private static SceneHierarchySortingWindow s_SceneHierarchySortingWindow; - private static long s_LastClosedTime; - private static Styles s_Styles; - - private List m_Data; - private OnSelectCallback m_Callback; - - const float kFrameWidth = 1f; - - private float GetHeight() - { - return EditorGUI.kSingleLineHeight * m_Data.Count; - } - - private float GetWidth() - { - float width = 0f; - - foreach (InputData item in m_Data) - { - float itemWidth = 0; - itemWidth = s_Styles.menuItem.CalcSize(GUIContent.Temp(item.m_Name)).x; - - if (itemWidth > width) - width = itemWidth; - } - return width; - } - - private void OnEnable() - { - AssemblyReloadEvents.beforeAssemblyReload += Close; - hideFlags = HideFlags.DontSave; - wantsMouseMove = true; - } - - private void OnDisable() - { - AssemblyReloadEvents.beforeAssemblyReload -= Close; - s_LastClosedTime = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; - } - - internal static bool ShowAtPosition(Vector2 pos, List data, OnSelectCallback callback) - { - // We could not use realtimeSinceStartUp since it is set to 0 when entering/exitting playmode, we assume an increasing time when comparing time. - long nowMilliSeconds = System.DateTime.Now.Ticks / System.TimeSpan.TicksPerMillisecond; - bool justClosed = nowMilliSeconds < s_LastClosedTime + 50; - if (!justClosed) - { - Event.current.Use(); - if (s_SceneHierarchySortingWindow == null) - s_SceneHierarchySortingWindow = CreateInstance(); - s_SceneHierarchySortingWindow.Init(pos, data, callback); - return true; - } - return false; - } - - private void Init(Vector2 pos, List data, OnSelectCallback callback) - { - // Has to be done before calling Show / ShowWithMode - //pos = GUIUtility.GUIToScreenPoint(pos); - - - Rect buttonRect = new Rect(pos.x, pos.y - 16, 16, 16); // fake a button: we know we are showing it below the bottonRect if possible - buttonRect = GUIUtility.GUIToScreenRect(buttonRect); - data.Sort( - delegate(InputData lhs, InputData rhs) - { - return lhs.m_Name.CompareTo(rhs.m_Name); - }); - m_Data = data; - m_Callback = callback; - - if (s_Styles == null) - s_Styles = new Styles(); - - var windowHeight = 2f * kFrameWidth + GetHeight(); - var windowWidth = 2f * kFrameWidth + GetWidth(); - var windowSize = new Vector2(windowWidth, windowHeight); - - ShowAsDropDown(buttonRect, windowSize); - } - - internal void OnGUI() - { - // We do not use the layout event - if (Event.current.type == EventType.Layout) - return; - - if (Event.current.type == EventType.MouseMove) - Event.current.Use(); - - // Content - Draw(); - - // Background with 1 pixel border - GUI.Label(new Rect(0, 0, position.width, position.height), GUIContent.none, s_Styles.background); - } - - private void Draw() - { - var drawPos = new Rect(kFrameWidth, kFrameWidth, position.width - 2 * kFrameWidth, EditorGUI.kSingleLineHeight); - - foreach (InputData data in m_Data) - { - DrawListElement(drawPos, data); - drawPos.y += EditorGUI.kSingleLineHeight; - } - } - - void DrawListElement(Rect rect, InputData data) - { - EditorGUI.BeginChangeCheck(); - GUI.Toggle(rect, data.m_Selected, EditorGUIUtility.TempContent(data.m_Name), s_Styles.menuItem); - if (EditorGUI.EndChangeCheck()) - { - m_Callback(data); - Close(); - } - } - } -} diff --git a/Editor/Mono/SceneHierarchyStageHandling.cs b/Editor/Mono/SceneHierarchyStageHandling.cs index a633173992..b0dffebe74 100644 --- a/Editor/Mono/SceneHierarchyStageHandling.cs +++ b/Editor/Mono/SceneHierarchyStageHandling.cs @@ -105,8 +105,30 @@ void HandleFirstTimePrefabStageIsOpened(StageNavigationItem stage) { if (stage.isPrefabStage && GetStoredHierarchyState(m_SceneHierarchyWindow, stage) == null) { - var visibleRootID = stage.prefabStage.prefabContentsRoot.GetInstanceID(); - m_SceneHierarchy.SetExpandedRecursive(visibleRootID, true); + SetDefaultExpandedStateForOpenedPrefab(stage.prefabStage.prefabContentsRoot); + } + } + + void SetDefaultExpandedStateForOpenedPrefab(GameObject root) + { + var expandedIDs = new List(); + AddParentsBelowButIgnoreNestedPrefabsRecursive(root.transform, expandedIDs); + expandedIDs.Sort(); + m_SceneHierarchy.treeViewState.expandedIDs = expandedIDs; + } + + void AddParentsBelowButIgnoreNestedPrefabsRecursive(Transform transform, List gameObjectInstanceIDs) + { + gameObjectInstanceIDs.Add(transform.gameObject.GetInstanceID()); + + int count = transform.childCount; + for (int i = 0; i < count; ++i) + { + var child = transform.GetChild(i); + if (child.childCount > 0 && !PrefabUtility.IsAnyPrefabInstanceRoot(child.gameObject)) + { + AddParentsBelowButIgnoreNestedPrefabsRecursive(child, gameObjectInstanceIDs); + } } } diff --git a/Editor/Mono/SceneManagement/SceneSetup.cs b/Editor/Mono/SceneManagement/SceneSetup.cs deleted file mode 100644 index 857c8c5f9e..0000000000 --- a/Editor/Mono/SceneManagement/SceneSetup.cs +++ /dev/null @@ -1,42 +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.Runtime.InteropServices; -using UnityEngine; - -// The setup information for a scene in the SceneManager. - -namespace UnityEditor.SceneManagement -{ - [StructLayout(LayoutKind.Sequential)] - [Serializable] - public class SceneSetup - { - [SerializeField] - private string m_Path = null; - [SerializeField] - private bool m_IsLoaded = false; - [SerializeField] - private bool m_IsActive = false; - - public string path - { - get { return m_Path; } - set { m_Path = value; } - } - - public bool isLoaded - { - get { return m_IsLoaded; } - set { m_IsLoaded = value; } - } - - public bool isActive - { - get { return m_IsActive; } - set { m_IsActive = value; } - } - } -} diff --git a/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.cs b/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.cs index 3bee757397..0b3f63498a 100644 --- a/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.cs +++ b/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.cs @@ -38,6 +38,8 @@ public class PrefabStage HideFlagUtility m_HideFlagUtility; Texture2D m_PrefabFileIcon; bool m_TemporarilyDisableAutoSave; + float m_LastSavingDuration = 0f; + const float kDurationBeforeShowingSavingBadge = 1.0f; bool m_AnalyticsDidUserModify; bool m_AnalyticsDidUserSave; @@ -61,7 +63,7 @@ public GameObject prefabContentsRoot get { if (m_PrefabContentsRoot == null) - throw new InvalidOperationException("Requesting 'prefabContentsRoot' from Awake and OnEnable are not supported"); // The preview scene is not fully loaded when we call Awake and OnEnable on user scripts + throw new InvalidOperationException("Requesting 'prefabContentsRoot' from Awake and OnEnable are not supported"); // The prefab stage's m_PrefabContentsRoot is not yet set when we call Awake and OnEnable on user scripts when loading a prefab return m_PrefabContentsRoot; } } @@ -91,6 +93,12 @@ public string prefabAssetPath get { return m_PrefabAssetPath; } } + internal bool showingSavingLabel + { + get; + private set; + } + internal Texture2D prefabFileIcon { get { return m_PrefabFileIcon; } @@ -261,14 +269,14 @@ bool isTextFieldCaretShowing bool readyToAutoSave { - get { return m_PrefabContentsRoot != null && HasSceneBeenModified() && GUIUtility.hotControl == 0 && !isTextFieldCaretShowing; } + get { return m_PrefabContentsRoot != null && HasSceneBeenModified() && GUIUtility.hotControl == 0 && !isTextFieldCaretShowing && !EditorApplication.isCompiling; } } void HandleAutoSave() { if (autoSave && readyToAutoSave) { - SavePrefabWithVersionControlDialogAndRenameDialog(); + AutoSave(); } } @@ -298,7 +306,7 @@ public void ClearDirtiness() m_InitialSceneDirtyID = m_PreviewScene.dirtyID; } - // Not private so we use it in Tests + // Is internal so we can use it in Tests internal void SavePrefab() { if (!initialized) @@ -313,14 +321,22 @@ internal void SavePrefab() if (prefabSaving != null) prefabSaving(m_PrefabContentsRoot); - ClearDirtiness(); - PrefabUtility.SaveAsPrefabAsset(m_PrefabContentsRoot, m_PrefabAssetPath); + var startTime = EditorApplication.timeSinceStartup; + var prefabAssetRoot = PrefabUtility.SaveAsPrefabAsset(m_PrefabContentsRoot, m_PrefabAssetPath); + m_LastSavingDuration = (float)(EditorApplication.timeSinceStartup - startTime); + + if (prefabAssetRoot != null) + { + ClearDirtiness(); - if (prefabSaved != null) - prefabSaved(m_PrefabContentsRoot); + if (prefabSaved != null) + prefabSaved(m_PrefabContentsRoot); + } if (SceneHierarchy.s_DebugPrefabStage) Debug.Log("SAVE PREFAB ended"); + + showingSavingLabel = false; } internal bool SaveAsNewPrefab(string newPath, bool asCopy) @@ -390,35 +406,53 @@ internal bool SaveAsNewPrefabWithSavePanel() return SaveAsNewPrefab(relativePath, false); } - // Returns true if prefab was saved. - internal bool SavePrefabWithVersionControlDialogAndRenameDialog() + void PerformDelayedAutoSave() { - Assert.IsTrue(m_PrefabContentsRoot != null, "We should have a valid m_PrefabContentsRoot when saving to prefab asset"); - bool editablePrefab = !AnimationMode.InAnimationMode(); + EditorApplication.update -= PerformDelayedAutoSave; + SavePrefabWithVersionControlDialogAndRenameDialog(); + } - //bool editablePrefab = UnityEditor.VersionControl.Provider.PromptAndCheckoutIfNeeded( - // new string[] {context.assetPath}, - // "The version control requires you to check out the prefab before applying changes."); + void AutoSave() + { + showingSavingLabel = m_LastSavingDuration > kDurationBeforeShowingSavingBadge; + if (showingSavingLabel) + { + // Save delayed if we want to show the save badge while saving. + foreach (SceneView sceneView in SceneView.sceneViews) + sceneView.Repaint(); - if (editablePrefab) + EditorApplication.update += PerformDelayedAutoSave; + } + else { - if (!PrefabUtility.PromptAndCheckoutPrefabIfNeeded(m_PrefabAssetPath, PrefabUtility.SaveVerb.Save)) - { - // If user doesn't want to check out prefab asset, or it cannot be, - // it doesn't make sense to keep auto save on. - m_TemporarilyDisableAutoSave = true; - return false; - } + // Save directly if we don't want to show the saving badge + SavePrefabWithVersionControlDialogAndRenameDialog(); + } + } - bool showCancelButton = !autoSave; - if (!CheckRenamedPrefabRootWhenSaving(showCancelButton)) - return false; + // Returns true if prefab was saved. + internal bool SavePrefabWithVersionControlDialogAndRenameDialog() + { + if (m_PrefabContentsRoot == null) + { + Debug.LogError("We should have a valid m_PrefabContentsRoot when saving to prefab asset"); + return false; + } - SavePrefab(); - return true; + if (!PrefabUtility.PromptAndCheckoutPrefabIfNeeded(m_PrefabAssetPath, PrefabUtility.SaveVerb.Save)) + { + // If user doesn't want to check out prefab asset, or it cannot be, + // it doesn't make sense to keep auto save on. + m_TemporarilyDisableAutoSave = true; + return false; } - return false; + bool showCancelButton = !autoSave; + if (!CheckRenamedPrefabRootWhenSaving(showCancelButton)) + return false; + + SavePrefab(); + return true; } // Returns true if we should continue saving diff --git a/Editor/Mono/SceneManagement/StageManager/StageNavigationManager.cs b/Editor/Mono/SceneManagement/StageManager/StageNavigationManager.cs index e23f0caa92..e13f91687a 100644 --- a/Editor/Mono/SceneManagement/StageManager/StageNavigationManager.cs +++ b/Editor/Mono/SceneManagement/StageManager/StageNavigationManager.cs @@ -265,10 +265,6 @@ internal void NavigateBack(Analytics.ChangeType stageChangeAnalytics) var previousStage = m_NavigationHistory.GetPrevious(); SwitchToStage(previousStage, false, true, stageChangeAnalytics); } - else - { - Debug.LogError("Cannot navigate back"); - } } internal void GoToMainStage(bool setPreviousSelection, Analytics.ChangeType stageChangeAnalytics) @@ -469,8 +465,8 @@ static bool OnOpenAsset(int instanceID, int line) if (assetPath.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) { - // The 'line' parameter is used for passing an instance if entered from the Hierarchy or SceneView, otherwise it is -1 - GameObject instanceRoot = line == -1 ? null : (GameObject)EditorUtility.InstanceIDToObject(line); + // The 'line' parameter can be used for passing an instanceID of a prefab instance + GameObject instanceRoot = line == -1 ? null : EditorUtility.InstanceIDToObject(line) as GameObject; PrefabStageUtility.OpenPrefab(assetPath, instanceRoot, Analytics.ChangeType.EnterViaAssetOpened); return true; diff --git a/Editor/Mono/SceneModeWindows/DefaultLightingExplorerExtension.cs b/Editor/Mono/SceneModeWindows/DefaultLightingExplorerExtension.cs index b3f4b6ffa8..c546825ccd 100644 --- a/Editor/Mono/SceneModeWindows/DefaultLightingExplorerExtension.cs +++ b/Editor/Mono/SceneModeWindows/DefaultLightingExplorerExtension.cs @@ -14,7 +14,7 @@ private static class Styles public static readonly GUIContent[] ProjectionStrings = { EditorGUIUtility.TrTextContent("Infinite"), EditorGUIUtility.TrTextContent("Box") }; public static readonly GUIContent[] LightmapEmissiveStrings = { EditorGUIUtility.TrTextContent("Realtime"), EditorGUIUtility.TrTextContent("Baked") }; public static readonly GUIContent Name = EditorGUIUtility.TrTextContent("Name"); - public static readonly GUIContent On = EditorGUIUtility.TrTextContent("On"); + public static readonly GUIContent Enabled = EditorGUIUtility.TrTextContent("Enabled"); public static readonly GUIContent Type = EditorGUIUtility.TrTextContent("Type"); public static readonly GUIContent Shape = EditorGUIUtility.TrTextContent("Shape"); public static readonly GUIContent Mode = EditorGUIUtility.TrTextContent("Mode"); @@ -69,8 +69,8 @@ protected virtual LightingExplorerTableColumn[] GetLightColumns() { return new[] { - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 0: Name - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.On, "m_Enabled", 25), // 1: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.Enabled, "m_Enabled", 50), // 0: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 1: Name new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Enum, Styles.Type, "m_Type", 120, (r, prop, dep) => { // To the user, we will only display it as a area light, but under the hood, we have Rectangle and Disc. This is not to confuse people @@ -168,8 +168,8 @@ protected virtual LightingExplorerTableColumn[] GetReflectionProbeColumns() { return new[] { - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 0: Name - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.On, "m_Enabled", 25), // 1: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.Enabled, "m_Enabled", 50), // 0: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 1: Name new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Int, Styles.Mode, "m_Mode", 70, (r, prop, dep) => { EditorGUI.IntPopup(r, prop, ReflectionProbeEditor.Styles.reflectionProbeMode, ReflectionProbeEditor.Styles.reflectionProbeModeValues, GUIContent.none); @@ -195,8 +195,8 @@ protected virtual LightingExplorerTableColumn[] GetLightProbeColumns() { return new[] { - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 0: Name - new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.On, "m_Enabled", 25), // 1: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Checkbox, Styles.Enabled, "m_Enabled", 50), // 0: Enabled + new LightingExplorerTableColumn(LightingExplorerTableColumn.DataType.Name, Styles.Name, null, 200), // 1: Name }; } diff --git a/Editor/Mono/SceneModeWindows/LightingWindowBakeSettings.cs b/Editor/Mono/SceneModeWindows/LightingWindowBakeSettings.cs index 79ac29a750..3479ab3321 100644 --- a/Editor/Mono/SceneModeWindows/LightingWindowBakeSettings.cs +++ b/Editor/Mono/SceneModeWindows/LightingWindowBakeSettings.cs @@ -71,7 +71,6 @@ internal class LightingWindowBakeSettings SerializedProperty m_PVRFilteringAtrousPositionSigmaAO; SerializedProperty m_BounceScale; - SerializedProperty m_UpdateThreshold; static bool PlayerHasSM20Support() { @@ -131,7 +130,6 @@ private void InitSettings() //dev debug properties m_BounceScale = so.FindProperty("m_GISettings.m_BounceScale"); - m_UpdateThreshold = so.FindProperty("m_GISettings.m_TemporalCoherenceThreshold"); } public void OnEnable() @@ -351,7 +349,6 @@ public void DeveloperBuildSettingsGUI() Lightmapping.filterMode = (FilterMode)EditorGUILayout.EnumPopup(EditorGUIUtility.TempContent("Filter Mode"), Lightmapping.filterMode); EditorGUILayout.Slider(m_BounceScale, 0.0f, 10.0f, Styles.BounceScale); - EditorGUILayout.Slider(m_UpdateThreshold, 0.0f, 1.0f, Styles.UpdateThreshold); if (GUILayout.Button("Clear disk cache", GUILayout.Width(LightingWindow.kButtonWidth))) { @@ -371,6 +368,16 @@ public void DeveloperBuildSettingsGUI() DynamicGI.UpdateEnvironment(); } + private void ClampFilterType(SerializedProperty filter) + { + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + { + // Force unsupported A-Trous filter back to Gaussian. + if (filter.intValue == (int)LightmapEditorSettings.FilterType.ATrous) + filter.intValue = (int)LightmapEditorSettings.FilterType.Gaussian; + } + } + void GeneralLightmapSettingsGUI() { bool bakedGISupported = SupportedRenderingFeatures.IsLightmapBakeTypeSupported(LightmapBakeType.Baked); @@ -390,11 +397,10 @@ void GeneralLightmapSettingsGUI() { EditorGUI.BeginChangeCheck(); - //TODO(RadeonRays) Remove this when GPU lightmapper is public. - - if (Unsupported.IsDeveloperMode() && (Application.platform == RuntimePlatform.WindowsEditor)) + //TODO(RadeonRays): Remove this when GPU lightmapper works on macOS and Linux. + if (Application.platform != RuntimePlatform.WindowsEditor) { - var backendOptions = new[] { "Enlighten", "Progressive CPU", "Progressive GPU (Preview)" }; + var backendOptions = new[] { "Enlighten", "Progressive CPU" }; m_BakeBackend.intValue = EditorGUILayout.Popup(Styles.BakeBackend, m_BakeBackend.intValue, backendOptions); } else @@ -453,7 +459,15 @@ void GeneralLightmapSettingsGUI() { EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(m_PVRFilterTypeDirect, Styles.PVRFilterTypeDirect); + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + EditorGUILayout.HelpBox(Styles.ProgressiveGPUWarning.text, MessageType.Info); + + ClampFilterType(m_PVRFilterTypeDirect); + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + EditorGUILayout.IntPopup(m_PVRFilterTypeDirect, Styles.GPUFilterOptions, Styles.GPUFilterInts, Styles.PVRFilterTypeDirect); + else + EditorGUILayout.PropertyField(m_PVRFilterTypeDirect, Styles.PVRFilterTypeDirect); + DrawFilterSettingField(m_PVRFilteringGaussRadiusDirect, m_PVRFilteringAtrousPositionSigmaDirect, Styles.PVRFilteringGaussRadiusDirect, @@ -462,7 +476,11 @@ void GeneralLightmapSettingsGUI() EditorGUILayout.Space(); - EditorGUILayout.PropertyField(m_PVRFilterTypeIndirect, Styles.PVRFilterTypeIndirect); + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + EditorGUILayout.IntPopup(m_PVRFilterTypeIndirect, Styles.GPUFilterOptions, Styles.GPUFilterInts, Styles.PVRFilterTypeIndirect); + else + EditorGUILayout.PropertyField(m_PVRFilterTypeIndirect, Styles.PVRFilterTypeIndirect); + ClampFilterType(m_PVRFilterTypeIndirect); DrawFilterSettingField(m_PVRFilteringGaussRadiusIndirect, m_PVRFilteringAtrousPositionSigmaIndirect, Styles.PVRFilteringGaussRadiusIndirect, @@ -472,8 +490,11 @@ void GeneralLightmapSettingsGUI() using (new EditorGUI.DisabledScope(!m_AmbientOcclusion.boolValue)) { EditorGUILayout.Space(); - - EditorGUILayout.PropertyField(m_PVRFilterTypeAO, Styles.PVRFilterTypeAO); + if (LightmapEditorSettings.lightmapper == LightmapEditorSettings.Lightmapper.ProgressiveGPU) + EditorGUILayout.IntPopup(m_PVRFilterTypeAO, Styles.GPUFilterOptions, Styles.GPUFilterInts, Styles.PVRFilterTypeAO); + else + EditorGUILayout.PropertyField(m_PVRFilterTypeAO, Styles.PVRFilterTypeAO); + ClampFilterType(m_PVRFilterTypeAO); DrawFilterSettingField(m_PVRFilteringGaussRadiusAO, m_PVRFilteringAtrousPositionSigmaAO, Styles.PVRFilteringGaussRadiusAO, Styles.PVRFilteringAtrousPositionSigmaAO, @@ -688,6 +709,10 @@ static class Styles public static readonly GUIContent PVRFilteringAtrousPositionSigmaIndirect = EditorGUIUtility.TrTextContent("Indirect Sigma", "Controls the threshold of the filter for indirect light stored in the lightmap. A higher value will increase the threshold, reducing noise in the indirect layer of the lightmap. Too high of a value can cause a loss of detail in the lightmap."); public static readonly GUIContent PVRFilteringAtrousPositionSigmaAO = EditorGUIUtility.TrTextContent("Ambient Occlusion Sigma", "Controls the threshold of the filter for ambient occlusion stored in the lightmap. A higher value will increase the threshold, reducing noise in the ambient occlusion layer of the lightmap. Too high of a value can cause a loss of detail in the lightmap."); public static readonly GUIContent PVRCulling = EditorGUIUtility.TrTextContent("Prioritize View", "Specifies whether the lightmapper should prioritize baking texels within the scene view. When disabled, objects outside the scene view will have the same priority as those in the scene view."); + // TODO(RadeonRays): Used for hiding A-trous filtering option until it is implemented. + public static readonly GUIContent[] GPUFilterOptions = new[] { EditorGUIUtility.TrTextContent("Gaussian"), EditorGUIUtility.TrTextContent("None") }; + public static readonly int[] GPUFilterInts = new[] { (int)LightmapEditorSettings.FilterType.Gaussian, (int)LightmapEditorSettings.FilterType.None }; + public static readonly GUIContent ProgressiveGPUWarning = EditorGUIUtility.TrTextContent("A-Trous filtering is not implemented in the Progressive GPU lightmapper yet. Use the CPU lightmapper instead if you need this functionality."); } } } // namespace diff --git a/Editor/Mono/SceneModeWindows/LightingWindowLightmapPreviewTab.cs b/Editor/Mono/SceneModeWindows/LightingWindowLightmapPreviewTab.cs index c07d539564..c80cb9ee41 100644 --- a/Editor/Mono/SceneModeWindows/LightingWindowLightmapPreviewTab.cs +++ b/Editor/Mono/SceneModeWindows/LightingWindowLightmapPreviewTab.cs @@ -31,10 +31,13 @@ internal class LightingWindowLightmapPreviewTab SerializedProperty m_LightingDataAsset; SerializedProperty m_TextureCompression; - class Styles + static class Styles { public static readonly GUIStyle SelectedLightmapHighlight = "LightmapEditorSelectedHighlight"; public static readonly GUIContent LightingDataAsset = EditorGUIUtility.TrTextContent("Lighting Data Asset", "A different LightingData.asset can be assigned here. These assets are generated by baking a scene in the OnDemand mode."); + public static readonly GUIContent OpenPreview = EditorGUIUtility.TrTextContent("Open Preview"); + + public static readonly GUIStyle OpenPreviewStyle = EditorStyles.objectFieldThumb.name + "LightmapPreviewOverlay"; } public LightingWindowLightmapPreviewTab(LightmapType type) @@ -171,28 +174,27 @@ private void LightmapListGUI(LightmapData[] lightmaps, VisualisationGITexture[] private void LightmapField(Texture2D lightmap, int index, Hash128 hash) { Rect rect = GUILayoutUtility.GetRect(100, 100, EditorStyles.objectField); + Rect buttonRect = new Rect(rect.xMax - 70, rect.yMax - 14, 70, 14); if (EditorGUI.Toggle(rect, index == m_SelectedLightmapIndex, EditorStyles.objectFieldThumb)) { m_SelectedLightmapIndex = index; - if (rect.Contains(Event.current.mousePosition)) + if ((buttonRect.Contains(Event.current.mousePosition) && Event.current.clickCount == 1) || + (rect.Contains(Event.current.mousePosition) && Event.current.clickCount == 2)) + { + if (isRealtimeLightmap) + LightmapPreviewWindow.CreateLightmapPreviewWindow(m_SelectedLightmapIndex, true, true); + else + LightmapPreviewWindow.CreateLightmapPreviewWindow(m_SelectedLightmapIndex, false, true); + } + else if (rect.Contains(Event.current.mousePosition) && Event.current.clickCount == 1) { Object actualTargetObject = lightmap; Component com = actualTargetObject as Component; if (com) actualTargetObject = com.gameObject; - - if (Event.current.clickCount == 1) - EditorGUI.PingObjectOrShowPreviewOnClick(actualTargetObject, GUILayoutUtility.GetLastRect()); - - if (Event.current.clickCount == 2) - { - if (isRealtimeLightmap) - LightmapPreviewWindow.CreateLightmapPreviewWindow(m_SelectedLightmapIndex, true, true); - else - LightmapPreviewWindow.CreateLightmapPreviewWindow(m_SelectedLightmapIndex, false, true); - } + EditorGUI.PingObjectOrShowPreviewOnClick(actualTargetObject, GUILayoutUtility.GetLastRect()); } } @@ -201,6 +203,8 @@ private void LightmapField(Texture2D lightmap, int index, Hash128 hash) rect = EditorStyles.objectFieldThumb.padding.Remove(rect); EditorGUI.DrawPreviewTexture(rect, lightmap); + Styles.OpenPreviewStyle.Draw(rect, Styles.OpenPreview, false, false, false, false); + if ((!isRealtimeLightmap && index == m_ActiveGameObjectLightmapIndex) || (isRealtimeLightmap && hash == m_ActiveGameObjectTextureHash)) { Styles.SelectedLightmapHighlight.Draw(rect, false, false, false, false); diff --git a/Editor/Mono/SceneModeWindows/LightmapPreviewWindow.cs b/Editor/Mono/SceneModeWindows/LightmapPreviewWindow.cs index 79645fd7f9..1bc8fb7a3a 100644 --- a/Editor/Mono/SceneModeWindows/LightmapPreviewWindow.cs +++ b/Editor/Mono/SceneModeWindows/LightmapPreviewWindow.cs @@ -37,7 +37,9 @@ internal class LightmapPreviewWindow : EditorWindow Hash128 m_RealtimeTextureHash = new Hash128(); VisualisationGITexture m_CachedTexture; GameObject[] m_CachedTextureObjects; + int m_ActiveGameObjectLightmapIndex = -1; // the object the user selects in the scene + int m_ActiveGameObjectInstanceId = -1; // for instance based non-atlas textures such as baked emissive for Progressive Hash128 m_ActiveGameObjectTextureHash = new Hash128(); // the object the user selects in the scene private float m_ExposureSliderMax = 10f; @@ -93,19 +95,18 @@ static class Styles public static readonly GUIContent TextureNotAvailableRealtime = EditorGUIUtility.TrTextContent("The texture is not available at the moment."); public static readonly GUIContent TextureNotAvailableBaked = EditorGUIUtility.TrTextContent("The texture is not available at the moment.\nPlease try to rebake the current scene or turn on Auto, and make sure that this object is set to Lightmap Static if it's meant to be baked."); public static readonly GUIContent TextureNotAvailableBakedShadowmask = EditorGUIUtility.TrTextContent("The texture is not available at the moment.\nPlease make sure that Mixed Lights affect this GameObject and that it is set to Lightmap Static."); + public static readonly GUIContent TextureNotAvailableBakedAlbedoEmissive = EditorGUIUtility.TrTextContent("The texture is not an index based texture and is not available when using Progressive.\nPlease go to the instance you wish to debug, and select the lightmap on the Mesh Renderer."); public static readonly GUIContent TextureLoading = EditorGUIUtility.TrTextContent("Loading..."); public static readonly GUIContent ExposureIcon = EditorGUIUtility.TrIconContent("SceneViewLighting", "Controls the number of stops to over or under expose the lightmap."); } public int lightmapIndex { - get { return m_LightmapIndex; } set { m_LightmapIndex = value; } } public int instanceID { - get { return m_InstanceID; } set { m_InstanceID = value; } } @@ -115,17 +116,24 @@ public bool isRealtimeLightmap set { m_IsRealtimeLightmap = value; } } + // this seperates between lightsmaps that we opened from a specific index, or the ones that are connected to an object (where the index can change) private bool isIndexBased { - get { return m_LightmapIndex != -1; } + get { return m_InstanceID == -1; } } private string lightmapTitle { get { - return isIndexBased ? ((isRealtimeLightmap ? "Realtime Lightmap Index " : "Lightmap Index ") + lightmapIndex) : - (isRealtimeLightmap ? "Realtime Lightmap" : "Lightmap"); + if (isIndexBased) return ((isRealtimeLightmap ? "Realtime Lightmap Index " : "Lightmap Index ") + m_LightmapIndex); + + var obj = EditorUtility.InstanceIDToObject(m_InstanceID); + + if (obj) + return (isRealtimeLightmap ? "Realtime" : "") + " Lightmap for '" + obj.name + "'"; + + return (isRealtimeLightmap ? "Realtime" : "") + " Lightmap"; } } @@ -199,6 +207,7 @@ private void UpdateActiveGameObjectSelection() (terrain = Selection.activeGameObject.GetComponent()) == null)) { m_ActiveGameObjectLightmapIndex = -1; + m_ActiveGameObjectInstanceId = -1; m_ActiveGameObjectTextureHash = new Hash128(); return; } @@ -214,7 +223,10 @@ private void UpdateActiveGameObjectSelection() m_ActiveGameObjectTextureHash = new Hash128(); } else + { m_ActiveGameObjectLightmapIndex = renderer != null ? renderer.lightmapIndex : terrain.lightmapIndex; + m_ActiveGameObjectInstanceId = renderer != null ? renderer.GetInstanceID() : terrain.GetInstanceID(); + } } private void PreviewSettings() @@ -297,9 +309,11 @@ private void DrawPreview(Rect r) if (m_CachedTexture.textureAvailability == GITextureAvailability.GITextureNotAvailable || m_CachedTexture.textureAvailability == GITextureAvailability.GITextureUnknown) { - if (LightmapVisualizationUtility.IsBakedTextureType(textureType)) + if (!isRealtimeLightmap) { - if (textureType == GITextureType.BakedShadowMask) + if (!LightmapVisualizationUtility.IsAtlasTextureType(textureType) && isIndexBased) + GUI.Label(drawableArea, Styles.TextureNotAvailableBakedAlbedoEmissive, Styles.PreviewLabel); + else if (textureType == GITextureType.BakedShadowMask) GUI.Label(drawableArea, Styles.TextureNotAvailableBakedShadowmask, Styles.PreviewLabel); else GUI.Label(drawableArea, Styles.TextureNotAvailableBaked, Styles.PreviewLabel); @@ -324,8 +338,12 @@ private void DrawPreview(Rect r) case EventType.ValidateCommand: case EventType.ExecuteCommand: - if (Event.current.commandName == EventCommandNames.FrameSelected && (isRealtimeLightmap ? m_RealtimeTextureHash == m_ActiveGameObjectTextureHash : m_LightmapIndex == m_ActiveGameObjectLightmapIndex)) + if (Event.current.commandName == EventCommandNames.FrameSelected && IsSelectedObjectInLightmap(textureType)) { + // There are instance based baked textures where we don't get any STs and can't do the framing + if (!isRealtimeLightmap && !LightmapVisualizationUtility.IsAtlasTextureType(textureType)) + break; + Vector4 lightmapTilingOffset = LightmapVisualizationUtility.GetLightmapTilingOffset(lightmapType); Vector2 min = new Vector2(lightmapTilingOffset.z, lightmapTilingOffset.w); @@ -349,7 +367,7 @@ private void DrawPreview(Rect r) Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y); rect.width = rect.height = Mathf.Max(rect.width, rect.height); rect.x -= (offsetX * min.x); - rect.y += (offsetY * (1 - max.y)); + rect.y += (offsetY * (1 - max.y)); m_ZoomablePreview.shownArea = rect; Event.current.Use(); @@ -377,7 +395,7 @@ private void DrawPreview(Rect r) texture.filterMode = FilterMode.Point; LightmapVisualizationUtility.DrawTextureWithUVOverlay(texture, - (m_ShowUVOverlay && (isRealtimeLightmap ? m_RealtimeTextureHash == m_ActiveGameObjectTextureHash : m_LightmapIndex == m_ActiveGameObjectLightmapIndex)) ? Selection.activeGameObject : null, + (m_ShowUVOverlay && IsSelectedObjectInLightmap(textureType)) ? Selection.activeGameObject : null, m_ShowUVOverlay ? m_CachedTextureObjects : new GameObject[] {}, drawableArea, textureRect, textureType, exposure); texture.filterMode = prevMode; } @@ -395,6 +413,17 @@ private void SelectPreviewTextureIndex(object textureOption) m_SelectedPreviewTextureOptionIndex = Array.IndexOf(options, textureOption); } + private bool IsSelectedObjectInLightmap(GITextureType textureType) + { + if (isRealtimeLightmap) + return (m_ActiveGameObjectTextureHash == m_RealtimeTextureHash); + + if (LightmapVisualizationUtility.IsAtlasTextureType(textureType)) + return (m_ActiveGameObjectLightmapIndex == m_LightmapIndex); + + return (m_ActiveGameObjectInstanceId == m_InstanceID); + } + private GITextureType GetSelectedTextureType() { GUIContent[] options = isRealtimeLightmap ? Styles.RealtimePreviewTextureOptions : Styles.BakedPreviewTextureOptions; @@ -437,7 +466,7 @@ private void UpdateCachedTexture(GITextureType textureType) { Hash128 systemHash; - if (!LightmapEditorSettings.GetInputSystemHash(instanceID, out systemHash)) + if (!LightmapEditorSettings.GetInputSystemHash(m_InstanceID, out systemHash)) return; m_RealtimeTextureHash = systemHash; @@ -446,7 +475,7 @@ private void UpdateCachedTexture(GITextureType textureType) { int lightmapIndex; - if (!LightmapEditorSettings.GetLightmapIndex(instanceID, out lightmapIndex)) + if (!LightmapEditorSettings.GetLightmapIndex(m_InstanceID, out lightmapIndex)) return; m_LightmapIndex = lightmapIndex; @@ -454,14 +483,14 @@ private void UpdateCachedTexture(GITextureType textureType) } Hash128 contentHash = isRealtimeLightmap ? LightmapVisualizationUtility.GetRealtimeGITextureHash(m_RealtimeTextureHash, textureType) : - LightmapVisualizationUtility.GetBakedGITextureHash(m_LightmapIndex, 0, textureType); + LightmapVisualizationUtility.GetBakedGITextureHash(m_LightmapIndex, m_InstanceID, textureType); // if we need to fetch a new texture if (m_CachedTexture.texture == null || m_CachedTexture.type != textureType || m_CachedTexture.contentHash != contentHash || m_CachedTexture.contentHash == new Hash128()) { m_CachedTexture = isRealtimeLightmap ? LightmapVisualizationUtility.GetRealtimeGITexture(m_RealtimeTextureHash, textureType) : - LightmapVisualizationUtility.GetBakedGITexture(m_LightmapIndex, 0, textureType); + LightmapVisualizationUtility.GetBakedGITexture(m_LightmapIndex, m_InstanceID, textureType); } if (!m_ShowUVOverlay) @@ -474,8 +503,10 @@ private void UpdateCachedTexture(GITextureType textureType) if (isRealtimeLightmap) m_CachedTextureObjects = LightmapVisualizationUtility.GetRealtimeGITextureRenderers(m_RealtimeTextureHash); - else + else if (LightmapVisualizationUtility.IsAtlasTextureType(textureType)) m_CachedTextureObjects = LightmapVisualizationUtility.GetBakedGITextureRenderers(m_LightmapIndex); + else // if it's an instance based baked lightmap, we only have 1 object in it + m_CachedTextureObjects = new GameObject[] {}; } private Rect ResizeRectToFit(Rect rect, Rect to) diff --git a/Editor/Mono/SceneModeWindows/TierSettingsWindow.cs b/Editor/Mono/SceneModeWindows/TierSettingsWindow.cs deleted file mode 100644 index c7d0776e5e..0000000000 --- a/Editor/Mono/SceneModeWindows/TierSettingsWindow.cs +++ /dev/null @@ -1,64 +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 Object = UnityEngine.Object; -using EditorGraphicsSettings = UnityEditor.Rendering.EditorGraphicsSettings; -using TierSettingsEditor = UnityEditor.GraphicsSettingsWindow.TierSettingsEditor; - -namespace UnityEditor -{ - internal partial class TierSettingsWindow : EditorWindow - { - static TierSettingsWindow s_Instance; - static public void CreateWindow() - { - s_Instance = EditorWindow.GetWindow(); - s_Instance.minSize = new Vector2(600, 300); - s_Instance.titleContent = EditorGUIUtility.TrTextContent("Tier Settings"); - } - - internal static TierSettingsWindow GetInstance() - { - return s_Instance; - } - - Editor m_TierSettingsEditor; - - void OnEnable() - { - s_Instance = this; - } - - void OnDisable() - { - DestroyImmediate(m_TierSettingsEditor); m_TierSettingsEditor = null; - if (s_Instance == this) - s_Instance = null; - } - - Object graphicsSettings - { - get { return UnityEngine.Rendering.GraphicsSettings.GetGraphicsSettings(); } - } - Editor tierSettingsEditor - { - get - { - Editor.CreateCachedEditor(graphicsSettings, typeof(TierSettingsEditor), ref m_TierSettingsEditor); - ((TierSettingsEditor)m_TierSettingsEditor).verticalLayout = false; - return m_TierSettingsEditor; - } - } - - void OnGUI() - { - tierSettingsEditor.OnInspectorGUI(); - } - } -} diff --git a/Editor/Mono/SceneView/SceneView.cs b/Editor/Mono/SceneView/SceneView.cs index ab9c61444e..9702700750 100644 --- a/Editor/Mono/SceneView/SceneView.cs +++ b/Editor/Mono/SceneView/SceneView.cs @@ -84,7 +84,7 @@ public static SceneView lastActiveSceneView public static SceneView currentDrawingSceneView { get { return s_CurrentDrawingSceneView; } } static readonly PrefColor kSceneViewBackground = new PrefColor("Scene/Background", 0.278431f, 0.278431f, 0.278431f, 0); - static readonly PrefColor kSceneViewPrefabBackground = new PrefColor("Scene/Background for Prefabs", 0.132f, 0.231f, 0.330f, 0); + internal static readonly PrefColor kSceneViewPrefabBackground = new PrefColor("Scene/Background for Prefabs", 0.132f, 0.231f, 0.330f, 0); static readonly PrefColor kSceneViewWire = new PrefColor("Scene/Wireframe", 0.0f, 0.0f, 0.0f, 0.5f); static readonly PrefColor kSceneViewWireOverlay = new PrefColor("Scene/Wireframe Overlay", 0.0f, 0.0f, 0.0f, 0.25f); static readonly PrefColor kSceneViewSelectedOutline = new PrefColor("Scene/Selected Outline", 255.0f / 255.0f, 102.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f); @@ -412,6 +412,9 @@ public float cameraDistance static Shader s_ShowMipsShader; static Shader s_ShowTextureStreamingShader; static Shader s_AuraShader; + static Shader s_BuildFilterShader; + static Material s_FadeMaterial; + static Material s_ApplyFilterMaterial; static Texture2D s_MipColorsTexture; // Handle Dragging of stuff over scene view @@ -741,7 +744,7 @@ void ToolbarDisplayStateGUI() if (EditorGUI.DropdownButton(modeRect, modeContent, FocusType.Passive, EditorStyles.toolbarDropDown)) { Rect rect = GUILayoutUtility.topLevel.GetLast(); - PopupWindow.Show(rect, new SceneRenderModeWindow(this), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(rect, new SceneRenderModeWindow(this)); GUIUtility.ExitGUI(); } @@ -768,7 +771,7 @@ void ToolbarDisplayStateGUI() if (EditorGUI.DropdownButton(fxRightRect, GUIContent.none, FocusType.Passive, GUIStyle.none)) { Rect rect = GUILayoutUtility.topLevel.GetLast(); - PopupWindow.Show(rect, new SceneFXWindow(this), null, ShowMode.PopupMenuWithKeyboardFocus); + PopupWindow.Show(rect, new SceneFXWindow(this)); GUIUtility.ExitGUI(); } @@ -1317,31 +1320,7 @@ private void DoDrawCamera(Rect windowSpaceCameraRect, Rect groupSpaceCameraRect, if (UseSceneFiltering()) { if (evt.type == EventType.Repaint) - { - // First pass: Draw objects which do not meet the search filter with grayscale image effect. - Handles.EnableCameraFx(m_Camera, true); - - Handles.SetCameraFilterMode(m_Camera, Handles.CameraFilterMode.ShowRest); - - float fade = Mathf.Clamp01((float)(EditorApplication.timeSinceStartup - m_StartSearchFilterTime)); - Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode); - Handles.DrawCameraFade(m_Camera, fade); - - // Second pass: Draw aura for objects which do meet search filter, but are occluded. - Handles.EnableCameraFx(m_Camera, false); - Handles.SetCameraFilterMode(m_Camera, Handles.CameraFilterMode.ShowFiltered); - if (!s_AuraShader) - s_AuraShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewAura.shader") as Shader; - m_Camera.SetReplacementShader(s_AuraShader, ""); - Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode); - - // Third pass: Draw objects which do meet filter normally - m_Camera.SetReplacementShader(m_ReplacementShader, m_ReplacementString); - Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode, gridParam); - - if (fade < 1) - Repaint(); - } + RenderFilteredScene(groupSpaceCameraRect); if (evt.type == EventType.Repaint) RenderTexture.active = null; @@ -1368,6 +1347,68 @@ private void DoDrawCamera(Rect windowSpaceCameraRect, Rect groupSpaceCameraRect, } } + void RenderFilteredScene(Rect groupSpaceCameraRect) + { + var oldRenderingPath = m_Camera.renderingPath; + + // First pass: Draw the scene normally in destination render texture, save color buffer for later + DoClearCamera(groupSpaceCameraRect); + Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode); + + var colorDesc = m_SceneTargetTexture.descriptor; + colorDesc.depthBufferBits = 0; + var colorRT = RenderTexture.GetTemporary(colorDesc); + colorRT.name = "SavedColorRT"; + Graphics.Blit(m_SceneTargetTexture, colorRT); + + // Second pass: Blit the scene faded out in the scene target texture + float fade = Mathf.Clamp01((float)(EditorApplication.timeSinceStartup - m_StartSearchFilterTime)); + if (!s_FadeMaterial) + s_FadeMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewGrayscaleEffectFade.mat") as Material; + s_FadeMaterial.SetFloat("_Fade", fade); + Graphics.Blit(colorRT, m_SceneTargetTexture, s_FadeMaterial); + + // Third pass: Draw aura for objects which meet the search filter, but are occluded. Save color buffer for later. + m_Camera.renderingPath = RenderingPath.Forward; + if (!s_AuraShader) + s_AuraShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewAura.shader") as Shader; + m_Camera.SetReplacementShader(s_AuraShader, ""); + Handles.SetCameraFilterMode(m_Camera, Handles.CameraFilterMode.ShowFiltered); + Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode); + + var fadedDesc = m_SceneTargetTexture.descriptor; + colorDesc.depthBufferBits = 0; + var fadedRT = RenderTexture.GetTemporary(fadedDesc); + fadedRT.name = "FadedColorRT"; + Graphics.Blit(m_SceneTargetTexture, fadedRT); + + // Fourth pass: Draw objects which do meet filter in a mask + RenderTexture.active = m_SceneTargetTexture; + GL.Clear(false, true, Color.clear); + + if (!s_BuildFilterShader) + s_BuildFilterShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewBuildFilter.shader") as Shader; + m_Camera.SetReplacementShader(s_BuildFilterShader, ""); + Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode); + + // Final pass: Blit the faded scene where the mask isn't set + if (!s_ApplyFilterMaterial) + s_ApplyFilterMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewApplyFilter.mat") as Material; + s_ApplyFilterMaterial.SetTexture("_MaskTex", m_SceneTargetTexture); + Graphics.Blit(fadedRT, colorRT, s_ApplyFilterMaterial); + Graphics.Blit(colorRT, m_SceneTargetTexture); + + RenderTexture.ReleaseTemporary(colorRT); + RenderTexture.ReleaseTemporary(fadedRT); + + // Reset camera + m_Camera.SetReplacementShader(m_ReplacementShader, m_ReplacementString); + m_Camera.renderingPath = oldRenderingPath; + + if (fade < 1) + Repaint(); + } + void SetupPBRValidation() { DrawCameraMode renderMode = m_CameraMode.drawMode; @@ -2222,9 +2263,7 @@ void SetupCamera() if (Event.current.type == EventType.Repaint) { - bool enableImageEffects = false; - if (!UseSceneFiltering()) - enableImageEffects = m_CameraMode.drawMode == DrawCameraMode.Textured && sceneViewState.showImageEffects; + bool enableImageEffects = m_CameraMode.drawMode == DrawCameraMode.Textured && sceneViewState.showImageEffects; UpdateImageEffects(enableImageEffects); } diff --git a/Editor/Mono/SceneView/SceneViewPicking.cs b/Editor/Mono/SceneView/SceneViewPicking.cs deleted file mode 100644 index 9c83d61c48..0000000000 --- a/Editor/Mono/SceneView/SceneViewPicking.cs +++ /dev/null @@ -1,169 +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.Collections.Generic; -using System.Linq; -using UnityEngine; - -namespace UnityEditor -{ - // No BaseSelection available: - // 1. Just cycle through the selection from topmost to bottom - - // SelectionBase available for topmost object: - // 1. First click selects the base - // 2. Second click selects the topmost - // 3. All subsequent clicks cycle through the stack of overlapping objects from top to bottom, regardless of their SelectionBase status - // 4. When we hit the bottom, we goto 1 - - // Example: Scene from back to front (visually): Panel(base), Label, Image, Button(base), Image2, Label2 - // Selection order: Button, Label2, Image2, Image, Label, Panel, goto start - - internal class SceneViewPicking - { - private static bool s_RetainHashes = false; - private static int s_PreviousTopmostHash = 0; - private static int s_PreviousPrefixHash = 0; - - static SceneViewPicking() - { - Selection.selectionChanged += ResetHashes; - } - - private static void ResetHashes() - { - if (!s_RetainHashes) - { - s_PreviousTopmostHash = 0; - s_PreviousPrefixHash = 0; - } - - s_RetainHashes = false; - } - - public static GameObject PickGameObject(Vector2 mousePosition) - { - s_RetainHashes = true; - - var enumerator = GetAllOverlapping(mousePosition).GetEnumerator(); - if (!enumerator.MoveNext()) - return null; - - var topmost = enumerator.Current; - var selectionBase = HandleUtility.FindSelectionBase(topmost); - var first = (selectionBase == null ? topmost : selectionBase); - int topmostHash = topmost.GetHashCode(); - int prefixHash = topmostHash; - - if (Selection.activeGameObject == null) - { - // Nothing selected - // Return selection base if it exists, otherwise topmost game object - s_PreviousTopmostHash = topmostHash; - s_PreviousPrefixHash = prefixHash; - return first; - } - - if (topmostHash != s_PreviousTopmostHash) - { - // Topmost game object changed - // Return selection base if exists and is not already selected, otherwise topmost game object - s_PreviousTopmostHash = topmostHash; - s_PreviousPrefixHash = prefixHash; - return (Selection.activeGameObject == selectionBase ? topmost : first); - } - - s_PreviousTopmostHash = topmostHash; - - // Pick potential selection base before topmost game object - if (Selection.activeGameObject == selectionBase) - { - if (prefixHash == s_PreviousPrefixHash) - return topmost; - else - { - s_PreviousPrefixHash = prefixHash; - return selectionBase; - } - } - - // Check if active game object will appear in selection stack - var picked = HandleUtility.PickGameObject(mousePosition, false, null, new GameObject[] { Selection.activeGameObject }); - if (picked == Selection.activeGameObject) - { - // Advance enumerator to active game object - while (enumerator.Current != Selection.activeGameObject) - { - if (!enumerator.MoveNext()) - { - s_PreviousPrefixHash = topmostHash; - return first; // Should not occur - } - - UpdateHash(ref prefixHash, enumerator.Current); - } - } - - if (prefixHash != s_PreviousPrefixHash) - { - // Prefix hash changed, start over - s_PreviousPrefixHash = topmostHash; - return first; - } - - // Move on to next game object - if (!enumerator.MoveNext()) - { - s_PreviousPrefixHash = topmostHash; - return first; // End reached, start over - } - - UpdateHash(ref prefixHash, enumerator.Current); - - if (enumerator.Current == selectionBase) - { - // Skip selection base - if (!enumerator.MoveNext()) - { - s_PreviousPrefixHash = topmostHash; - return first; // End reached, start over - } - - UpdateHash(ref prefixHash, enumerator.Current); - } - - s_PreviousPrefixHash = prefixHash; - return enumerator.Current; - } - - // Use picking system to get us ordered list of all visually overlapping gameobjects in screen position from top to bottom - private static IEnumerable GetAllOverlapping(Vector2 position) - { - var allOverlapping = new List(); - - while (true) - { - var go = HandleUtility.PickGameObject(position, false, allOverlapping.ToArray()); - if (go == null) - break; - - // Prevent infinite loop if game object cannot be ignored when picking (This needs to fixed so print an error) - if (allOverlapping.Count > 0 && go == allOverlapping.Last()) - { - Debug.LogError("GetAllOverlapping failed, could not ignore game object '" + go.name + "' when picking"); - break; - } - - yield return go; - - allOverlapping.Add(go); - } - } - - private static void UpdateHash(ref int hash, object obj) - { - hash = unchecked(hash * 33 + obj.GetHashCode()); - } - } -} diff --git a/Editor/Mono/SceneView/SceneViewStageHandling.cs b/Editor/Mono/SceneView/SceneViewStageHandling.cs index 9f45d1315c..4173497993 100644 --- a/Editor/Mono/SceneView/SceneViewStageHandling.cs +++ b/Editor/Mono/SceneView/SceneViewStageHandling.cs @@ -36,11 +36,13 @@ static bool autoSave static class Styles { - public static GUIContent autoSaveGUIContent = EditorGUIUtility.TrTextContent("Auto Save"); + public static GUIContent autoSaveGUIContent = EditorGUIUtility.TrTextContent("Auto Save", "When Auto Save is enabled, every change you make is automatically saved to the Prefab Asset. Disable Auto Save if you experience long import times."); public static GUIContent saveButtonContent = EditorGUIUtility.TrTextContent("Save"); public static GUIContent checkoutButtonContent = EditorGUIUtility.TrTextContent("Check Out"); + public static GUIContent autoSavingBadgeContent = EditorGUIUtility.TrTextContent("Auto Saving..."); public static GUIStyle saveToggle; public static GUIStyle button; + public static GUIStyle savingBadge = "Badge"; static Styles() { @@ -232,16 +234,14 @@ void AutoSaveButtons() { StatusQueryOptions opts = EditorUserSettings.allowAsyncStatusUpdate ? StatusQueryOptions.UseCachedAsync : StatusQueryOptions.UseCachedIfPossible; bool openForEdit = AssetDatabase.IsOpenForEdit(item.prefabAssetPath, opts); - if (!openForEdit) + + PrefabStage stage = item.prefabStage; + if (stage.showingSavingLabel) { - if (GUILayout.Button(Styles.checkoutButtonContent, Styles.button)) - { - Task task = Provider.Checkout(AssetDatabase.LoadAssetAtPath(item.prefabAssetPath), CheckoutMode.Both); - task.Wait(); - } + GUILayout.Label(Styles.autoSavingBadgeContent, Styles.savingBadge); + GUILayout.Space(4); } - PrefabStage stage = item.prefabStage; if (!stage.autoSave) { using (new EditorGUI.DisabledScope(!openForEdit || !PrefabStageUtility.GetCurrentPrefabStage().HasSceneBeenModified())) @@ -259,6 +259,15 @@ void AutoSaveButtons() if (EditorGUI.EndChangeCheck()) stage.autoSave = autoSaveForScene; } + + if (!openForEdit) + { + if (GUILayout.Button(Styles.checkoutButtonContent, Styles.button)) + { + Task task = Provider.Checkout(AssetDatabase.LoadAssetAtPath(item.prefabAssetPath), CheckoutMode.Both); + task.Wait(); + } + } } } diff --git a/Editor/Mono/ScriptAttributeGUI/CustomPropertyDrawerAttribute.cs b/Editor/Mono/ScriptAttributeGUI/CustomPropertyDrawerAttribute.cs deleted file mode 100644 index c021401405..0000000000 --- a/Editor/Mono/ScriptAttributeGUI/CustomPropertyDrawerAttribute.cs +++ /dev/null @@ -1,29 +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 -{ - // Tells a custom [[PropertyDrawer]] which run-time [[Serializable]] class or [[PropertyAttribute]] it's a drawer for. - [System.AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)] - public sealed class CustomPropertyDrawer : Attribute - { - internal Type m_Type; - internal bool m_UseForChildren; - - // Tells a PropertyDrawer class which run-time class or attribute it's a drawer for. - public CustomPropertyDrawer(Type type) - { - m_Type = type; - } - - // Tells a PropertyDrawer class which run-time class or attribute it's a drawer for. - public CustomPropertyDrawer(Type type, bool useForChildren) - { - m_Type = type; - m_UseForChildren = useForChildren; - } - } -} diff --git a/Editor/Mono/ScriptAttributeGUI/DecoratorDrawer.cs b/Editor/Mono/ScriptAttributeGUI/DecoratorDrawer.cs deleted file mode 100644 index 58767403d4..0000000000 --- a/Editor/Mono/ScriptAttributeGUI/DecoratorDrawer.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 UnityEngine; - -namespace UnityEditor -{ - // Base class to derive custom decorator drawers from. - public abstract class DecoratorDrawer : GUIDrawer - { - internal PropertyAttribute m_Attribute; - - // The [[PropertyAttribute]] for the property. - public PropertyAttribute attribute { get { return m_Attribute; } } - - // Override this method to make your own GUI for the property. - public virtual void OnGUI(Rect position) - { - } - - // Override this method to specify how tall the GUI for this field is in pixels. - public virtual float GetHeight() - { - return EditorGUI.kSingleLineHeight; - } - - public virtual bool CanCacheInspectorGUI() - { - return true; - } - } -} diff --git a/Editor/Mono/ScriptAttributeGUI/GUIDrawer.cs b/Editor/Mono/ScriptAttributeGUI/GUIDrawer.cs deleted file mode 100644 index cd87d0003d..0000000000 --- a/Editor/Mono/ScriptAttributeGUI/GUIDrawer.cs +++ /dev/null @@ -1,9 +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 -{ - // Base class for both PropertyDrawer and DecoratorDrawer. - public abstract class GUIDrawer {} -} diff --git a/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs b/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs deleted file mode 100644 index d15df0fdbc..0000000000 --- a/Editor/Mono/ScriptAttributeGUI/Implementations/DecoratorDrawers.cs +++ /dev/null @@ -1,35 +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; - -namespace UnityEditor -{ - // Built-in DecoratorDrawers. See matching attributes in PropertyAttribute.cs - - [CustomPropertyDrawer(typeof(SpaceAttribute))] - internal sealed class SpaceDrawer : DecoratorDrawer - { - public override float GetHeight() - { - return (attribute as SpaceAttribute).height; - } - } - - [CustomPropertyDrawer(typeof(HeaderAttribute))] - internal sealed class HeaderDrawer : DecoratorDrawer - { - public override void OnGUI(Rect position) - { - position.y += 8; - position = EditorGUI.IndentedRect(position); - GUI.Label(position, (attribute as HeaderAttribute).header, EditorStyles.boldLabel); - } - - public override float GetHeight() - { - return 24; - } - } -} diff --git a/Editor/Mono/ScriptableSingletonDictionary.cs b/Editor/Mono/ScriptableSingletonDictionary.cs deleted file mode 100644 index 7e0a0e2cff..0000000000 --- a/Editor/Mono/ScriptableSingletonDictionary.cs +++ /dev/null @@ -1,147 +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 System; -using System.IO; -using UnityEditorInternal; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - // Use the LibraryFolderPathAttribute when you want to have your scriptable singleton dictionary - // to persist between unity sessions. - // Example: [LibraryFolderPathAttribute("EditorWindows")] - [AttributeUsage(AttributeTargets.Class)] - class LibraryFolderPathAttribute : Attribute - { - public string folderPath { get; set; } - public LibraryFolderPathAttribute(string relativePath) - { - if (string.IsNullOrEmpty(relativePath)) - { - Debug.LogError("Invalid relative path! (its null or empty)"); - return; - } - - // We do not want a slash as first char. - if (relativePath[0] == '/') - throw new ArgumentException("Folder relative path cannot start with a slash."); - - folderPath = "Library/" + relativePath; - } - } - - internal abstract class ScriptableSingletonDictionary : ScriptableObject - where TDerived : ScriptableObject - where TValue : ScriptableObject - { - private static TDerived s_Instance; - static readonly string k_Extension = ".pref"; - - protected string m_PreferencesFileName; - - public static TDerived instance - { - get - { - if (s_Instance == null) - { - s_Instance = ScriptableObject.CreateInstance(); - s_Instance.hideFlags = HideFlags.HideAndDontSave; - } - return s_Instance; - } - } - - public TValue this[string preferencesFileName] - { - get - { - return Load(preferencesFileName); - } - } - - private TValue CreateNewValue() - { - TValue value = ScriptableObject.CreateInstance(); - value.hideFlags |= HideFlags.HideAndDontSave; - return value; - } - - private string GetProjectRelativePath(string file) - { - return GetFolderPath() + "/" + file + k_Extension; - } - - // Save() should be called whenever the user of this data store - // believes the data might have changed and needs to be updated - // in the pref file. Otherwise, Save() will only be called when - // switching between pref files by accessing with different keys. - public void Save(string preferencesFileName, TValue value) - { - const bool saveAsText = true; - - Debug.Assert(preferencesFileName != null && value != null, "Should always have valid key/values."); - if (string.IsNullOrEmpty(preferencesFileName) || value == null) - return; - - // if there is no key the object does not exist on disk, - // so there is no guid associated with it - string file = preferencesFileName; - if (string.IsNullOrEmpty(file)) - return; - - // make sure the path exists or file write will fail - string fullPath = Application.dataPath + "/../" + GetFolderPath(); - if (!System.IO.Directory.Exists(fullPath)) - System.IO.Directory.CreateDirectory(fullPath); - - InternalEditorUtility.SaveToSerializedFileAndForget(new[] { value }, GetProjectRelativePath(file), saveAsText); - } - - public void Clear(string preferencesFileName) - { - string fullPath = Application.dataPath + "/../" + GetProjectRelativePath(preferencesFileName); - if (System.IO.File.Exists(fullPath)) - System.IO.File.Delete(fullPath); - } - - private TValue Load(string preferencesFileName) - { - TValue value = null; - string file = preferencesFileName; - if (!string.IsNullOrEmpty(file)) - { - var objects = InternalEditorUtility.LoadSerializedFileAndForget(GetProjectRelativePath(file)); - if (objects != null && objects.Length > 0) - { - value = objects[0] as TValue; - if (value != null) - value.hideFlags |= HideFlags.HideAndDontSave; - } - } - - m_PreferencesFileName = preferencesFileName; - return value ?? CreateNewValue(); - } - - private string GetFolderPath() - { - Type type = this.GetType(); - object[] attributes = type.GetCustomAttributes(true); - foreach (object attr in attributes) - { - if (attr is LibraryFolderPathAttribute) - { - LibraryFolderPathAttribute f = attr as LibraryFolderPathAttribute; - return f.folderPath; - } - } - - // The folder path attribute is required. - throw new ArgumentException("The LibraryFolderPathAttribute[] attribute is required for this class."); - } - } -} diff --git a/Editor/Mono/Scripting/Compilers/BooCompiler.cs b/Editor/Mono/Scripting/Compilers/BooCompiler.cs index 91bc774c92..8cbb470b10 100644 --- a/Editor/Mono/Scripting/Compilers/BooCompiler.cs +++ b/Editor/Mono/Scripting/Compilers/BooCompiler.cs @@ -23,19 +23,19 @@ override protected Program StartCompiler() { "-debug", "-target:library", - "-out:" + _island._output, + "-out:" + m_Island._output, "-x-type-inference-rule-attribute:" + typeof(UnityEngineInternal.TypeInferenceRuleAttribute) }; - foreach (string dll in _island._references) + foreach (string dll in m_Island._references) arguments.Add("-r:" + PrepareFileName(dll)); - foreach (string define in _island._defines.Distinct()) + foreach (string define in m_Island._defines.Distinct()) arguments.Add("-define:" + define); - foreach (string source in _island._files) + foreach (string source in m_Island._files) arguments.Add(PrepareFileName(source)); string compilerPath = Path.Combine(GetBooCompilerDirectory(), "booc.exe"); - return StartCompiler(_island._target, compilerPath, arguments, GetBooProfileDirectory()); + return StartCompiler(m_Island._target, compilerPath, arguments, GetBooProfileDirectory()); } protected override CompilerOutputParserBase CreateOutputParser() @@ -43,6 +43,11 @@ protected override CompilerOutputParserBase CreateOutputParser() return new BooCompilerOutputParser(); } + protected override string[] GetSystemReferenceDirectories() + { + return new[] { GetBooCompilerDirectory() }; + } + string GetBooCompilerDirectory() { if (EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy) @@ -54,7 +59,7 @@ string GetBooCompilerDirectory() string GetBooProfileDirectory() { if (EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy) - return BuildPipeline.CompatibilityProfileToClassLibFolder(_island._api_compatibility_level); + return BuildPipeline.CompatibilityProfileToClassLibFolder(m_Island._api_compatibility_level); return k_UnityScriptProfileDirectory; } diff --git a/Editor/Mono/Scripting/Compilers/BooCompilerOutputParser.cs b/Editor/Mono/Scripting/Compilers/BooCompilerOutputParser.cs deleted file mode 100644 index fef008d186..0000000000 --- a/Editor/Mono/Scripting/Compilers/BooCompilerOutputParser.cs +++ /dev/null @@ -1,34 +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.Text.RegularExpressions; - -namespace UnityEditor.Scripting.Compilers -{ - class BooCompilerOutputParser : CompilerOutputParserBase - { - private static Regex sCompilerOutput = new Regex(@"\s*(?.*)\((?\d+),(?\d+)\):\s*[BU]C(?W|E)(?[^:]*):\s*(?.*)", RegexOptions.ExplicitCapture); - private static Regex sMissingMember = new Regex(@"[^']*'(?[^']+)'[^']+'(?[^']+)'", RegexOptions.ExplicitCapture | RegexOptions.Compiled); - private static Regex sUnknownTypeOrNamespace = new Regex(@"[^']*'(?[^']+)'.*", RegexOptions.ExplicitCapture | RegexOptions.Compiled); - - protected override string GetErrorIdentifier() - { - return "E"; - } - - protected override Regex GetOutputRegex() - { - return sCompilerOutput; - } - - protected override NormalizedCompilerStatus NormalizedStatusFor(Match match) - { - var status = TryNormalizeCompilerStatus(match, "0019", sMissingMember, NormalizeMemberNotFoundError); - if (status.code != NormalizedCompilerStatusCode.NotNormalized) - return status; - - return TryNormalizeCompilerStatus(match, "0018", sUnknownTypeOrNamespace, NormalizeSimpleUnknownTypeOfNamespaceError); - } - } -} diff --git a/Editor/Mono/Scripting/Compilers/BooLanguage.cs b/Editor/Mono/Scripting/Compilers/BooLanguage.cs deleted file mode 100644 index 36f8f30817..0000000000 --- a/Editor/Mono/Scripting/Compilers/BooLanguage.cs +++ /dev/null @@ -1,39 +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 Boo.Lang.Parser; - -using System.Linq; - -namespace UnityEditor.Scripting.Compilers -{ - internal class BooLanguage : SupportedLanguage - { - public override string GetExtensionICanCompile() - { - return "boo"; - } - - public override string GetLanguageName() - { - return "Boo"; - } - - public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater) - { - return new BooCompiler(island, runUpdater); - } - - public override string GetNamespace(string fileName, string definedSymbols) - { - try - { - return BooParser.ParseFile(fileName).Modules.First().Namespace.Name; - } - catch {} - - return base.GetNamespace(fileName, definedSymbols); - } - } -} diff --git a/Editor/Mono/Scripting/Compilers/CSharpLanguage.cs b/Editor/Mono/Scripting/Compilers/CSharpLanguage.cs index 8d83e543ee..a3481ab119 100644 --- a/Editor/Mono/Scripting/Compilers/CSharpLanguage.cs +++ b/Editor/Mono/Scripting/Compilers/CSharpLanguage.cs @@ -56,45 +56,25 @@ public override bool CompilerRequiresAdditionalReferences() return true; } - public string GetNamespaceNewRuntime(string filePath, string definedSymbols) + static string[] GetSystemReferenceDirectories(ApiCompatibilityLevel apiCompatibilityLevel) { - var definedSymbolSplit = definedSymbols.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - string[] defines = null; - var responseFilePath = Path.Combine("Assets", MonoCSharpCompiler.ReponseFilename); - try - { - var responseFileData = ScriptCompilerBase.ParseResponseFileFromFile(responseFilePath); - defines = new string[responseFileData.Defines.Length + definedSymbolSplit.Length]; - Array.Copy(definedSymbolSplit, defines, definedSymbolSplit.Length); - Array.Copy(responseFileData.Defines, 0, defines, definedSymbolSplit.Length, responseFileData.Defines.Length); - } - catch (Exception e) - { - Debug.LogException(e); - } - - var uniqueSymbols = new HashSet(defines ?? definedSymbolSplit); - return CSharpNamespaceParser.GetNamespace(ReadAndConverteNewLines(filePath).ReadToEnd(), Path.GetFileNameWithoutExtension(filePath), uniqueSymbols.ToArray()); + return MonoLibraryHelpers.GetSystemReferenceDirectories(apiCompatibilityLevel); } - public string GetNamespaceOldRuntime(string filePath, string definedSymbols) + public string GetNamespaceNewRuntime(string filePath, string definedSymbols, string[] defines) { var definedSymbolSplit = definedSymbols.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); - string[] defines = null; - var responseFilePath = Path.Combine("Assets", MonoCSharpCompiler.ReponseFilename); - try - { - var responseFileData = ScriptCompilerBase.ParseResponseFileFromFile(responseFilePath); - defines = new string[responseFileData.Defines.Length + definedSymbolSplit.Length]; - Array.Copy(definedSymbolSplit, defines, definedSymbolSplit.Length); - Array.Copy(responseFileData.Defines, 0, defines, definedSymbolSplit.Length, responseFileData.Defines.Length); - } - catch (Exception e) - { - Debug.LogException(e); - } + var uniqueSymbols = defines.Union(definedSymbolSplit).Distinct().ToArray(); + return CSharpNamespaceParser.GetNamespace( + ReadAndConverteNewLines(filePath).ReadToEnd(), + Path.GetFileNameWithoutExtension(filePath), + uniqueSymbols); + } - var uniqueSymbols = new HashSet(defines ?? definedSymbolSplit); + public string GetNamespaceOldRuntime(string filePath, string definedSymbols, string[] defines) + { + var definedSymbolSplit = definedSymbols.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + var uniqueSymbols = defines.Union(definedSymbolSplit).Distinct().ToArray(); using (var parser = ParserFactory.CreateParser(ICSharpCode.NRefactory.SupportedLanguage.CSharp, ReadAndConverteNewLines(filePath))) { foreach (var symbol in uniqueSymbols) @@ -121,13 +101,22 @@ public string GetNamespaceOldRuntime(string filePath, string definedSymbols) public override string GetNamespace(string filePath, string definedSymbols) { + var responseFilePath = Path.Combine("Assets", MonoCSharpCompiler.ResponseFilename); if (EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Latest) { - return GetNamespaceNewRuntime(filePath, definedSymbols); + var responseFileData = ScriptCompilerBase.ParseResponseFileFromFile( + responseFilePath, + Application.dataPath, + GetSystemReferenceDirectories(ApiCompatibilityLevel.NET_4_6)); + return GetNamespaceNewRuntime(filePath, definedSymbols, responseFileData.Defines); } else { - return GetNamespaceOldRuntime(filePath, definedSymbols); + var responseFileData = ScriptCompilerBase.ParseResponseFileFromFile( + responseFilePath, + Application.dataPath, + GetSystemReferenceDirectories(ApiCompatibilityLevel.NET_2_0)); + return GetNamespaceOldRuntime(filePath, definedSymbols, responseFileData.Defines); } } diff --git a/Editor/Mono/Scripting/Compilers/MicrosoftCSharpCompiler.cs b/Editor/Mono/Scripting/Compilers/MicrosoftCSharpCompiler.cs index 19a5762ed3..5a19930cbc 100644 --- a/Editor/Mono/Scripting/Compilers/MicrosoftCSharpCompiler.cs +++ b/Editor/Mono/Scripting/Compilers/MicrosoftCSharpCompiler.cs @@ -8,6 +8,7 @@ using System.IO; using System.Linq; using UnityEditor.Modules; +using UnityEditor.Scripting.ScriptCompilation; using UnityEditor.Utils; using UnityEngine; @@ -21,18 +22,18 @@ public MicrosoftCSharpCompiler(MonoIsland island, bool runUpdater) : base(island { } - private BuildTarget BuildTarget { get { return _island._target; } } + BuildTarget BuildTarget => m_Island._target; - private string[] GetClassLibraries() + public static string[] GetClassLibraries(BuildTarget buildTarget) { - var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(BuildTarget); + var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(buildTarget); if (PlayerSettings.GetScriptingBackend(buildTargetGroup) != ScriptingImplementation.WinRTDotNET) { return new string[] {}; } - if (BuildTarget != BuildTarget.WSAPlayer) - throw new InvalidOperationException(string.Format("MicrosoftCSharpCompiler cannot build for .NET Scripting backend for BuildTarget.{0}.", BuildTarget)); + if (buildTarget != BuildTarget.WSAPlayer) + throw new InvalidOperationException($"MicrosoftCSharpCompiler cannot build for .NET Scripting backend for BuildTarget. {buildTarget}."); var resolver = new NuGetPackageResolver { ProjectLockFile = @"UWP\project.lock.json" }; return resolver.Resolve(); @@ -54,7 +55,7 @@ private void FillCompilerOptions(List arguments, out string argsPrefix) { var compilationExtension = platformSupportModule.CreateCompilationExtension(); - arguments.AddRange(GetClassLibraries().Select(r => "/reference:\"" + r + "\"")); + arguments.AddRange(GetClassLibraries(BuildTarget).Select(r => "/reference:\"" + r + "\"")); arguments.AddRange(compilationExtension.GetAdditionalAssemblyReferences().Select(r => "/reference:\"" + r + "\"")); arguments.AddRange(compilationExtension.GetWindowsMetadataReferences().Select(r => "/reference:\"" + r + "\"")); arguments.AddRange(compilationExtension.GetAdditionalDefines().Select(d => "/define:" + d)); @@ -69,14 +70,14 @@ private static void ThrowCompilerNotFoundException(string path) private Program StartCompilerImpl(List arguments, string argsPrefix) { - foreach (string dll in _island._references) + foreach (string dll in m_Island._references) arguments.Add("/reference:" + PrepareFileName(dll)); - foreach (string define in _island._defines.Distinct()) + foreach (string define in m_Island._defines.Distinct()) arguments.Add("/define:" + define); - var filePathMappings = new List(_island._files.Length); - foreach (var source in _island._files) + var filePathMappings = new List(m_Island._files.Length); + foreach (var source in m_Island._files) { var f = PrepareFileName(source); if (Application.platform == RuntimePlatform.WindowsEditor) @@ -117,7 +118,7 @@ private Program StartCompilerImpl(List arguments, string argsPrefix) if (!AddCustomResponseFileIfPresent(arguments, ReponseFilename) && PlayerSettings.GetScriptingBackend(buildTargetGroup) != ScriptingImplementation.WinRTDotNET) { if (AddCustomResponseFileIfPresent(arguments, "mcs.rsp")) - UnityEngine.Debug.LogWarning(string.Format("Using obsolete custom response file 'mcs.rsp'. Please use '{0}' instead.", ReponseFilename)); + UnityEngine.Debug.LogWarning($"Using obsolete custom response file 'mcs.rsp'. Please use '{ReponseFilename}' instead."); } var responseFile = CommandLineFormatter.GenerateResponseFile(arguments); @@ -168,7 +169,7 @@ static bool UseNetCoreCompiler() protected override Program StartCompiler() { - var outputPath = PrepareFileName(_island._output); + var outputPath = PrepareFileName(m_Island._output); // Always build with "/debug:pdbonly", "/optimize+", because even if the assembly is optimized // it seems you can still succesfully debug C# scripts in Visual Studio @@ -179,11 +180,12 @@ protected override Program StartCompiler() "/out:" + outputPath }; - if (_island._allowUnsafeCode) + if (m_Island._allowUnsafeCode) arguments.Add("/unsafe"); var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(BuildTarget); - if (!_island._development_player) + var disableOptimizations = m_Island._development_player || (m_Island._editor && EditorPrefs.GetBool("AllowAttachedDebuggingOfEditor", true)); + if (!disableOptimizations) { if (PlayerSettings.GetScriptingBackend(buildTargetGroup) == ScriptingImplementation.WinRTDotNET) arguments.Add("/debug:pdbonly"); @@ -205,6 +207,17 @@ protected override Program StartCompiler() return StartCompilerImpl(arguments, argsPrefix); } + protected override string[] GetSystemReferenceDirectories() + { + var buildTargetGroup = BuildPipeline.GetBuildTargetGroup(BuildTarget); + if (BuildTarget == BuildTarget.WSAPlayer && PlayerSettings.GetScriptingBackend(buildTargetGroup) == ScriptingImplementation.WinRTDotNET) + { + return GetClassLibraries(BuildTarget).Select(library => Directory.GetParent(library).FullName).Distinct().ToArray(); + } + + return MonoLibraryHelpers.GetSystemReferenceDirectories(m_Island._api_compatibility_level); + } + protected override string[] GetStreamContainingCompilerMessages() { return GetStandardOutput(); diff --git a/Editor/Mono/Scripting/Compilers/MonoCSharpCompiler.cs b/Editor/Mono/Scripting/Compilers/MonoCSharpCompiler.cs index 6572173376..f442a9f7b4 100644 --- a/Editor/Mono/Scripting/Compilers/MonoCSharpCompiler.cs +++ b/Editor/Mono/Scripting/Compilers/MonoCSharpCompiler.cs @@ -14,13 +14,13 @@ namespace UnityEditor.Scripting.Compilers { class MonoCSharpCompiler : MonoScriptCompilerBase { - public static readonly string ReponseFilename = "mcs.rsp"; + public static readonly string ResponseFilename = "mcs.rsp"; public MonoCSharpCompiler(MonoIsland island, bool runUpdater) : base(island, runUpdater) { } - override protected Program StartCompiler() + protected override Program StartCompiler() { var arguments = new List { @@ -28,23 +28,23 @@ override protected Program StartCompiler() "-target:library", "-nowarn:0169", "-langversion:" + ((EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Latest) ? "6" : "4"), - "-out:" + PrepareFileName(_island._output), + "-out:" + PrepareFileName(m_Island._output), "-nostdlib", }; - if (_island._allowUnsafeCode) + if (m_Island._allowUnsafeCode) arguments.Add("-unsafe"); - if (!_island._development_player && !_island._editor) + if (!m_Island._development_player && !m_Island._editor) arguments.Add("-optimize"); - foreach (string dll in _island._references) + foreach (string dll in m_Island._references) arguments.Add("-r:" + PrepareFileName(dll)); - foreach (string define in _island._defines.Distinct()) + foreach (string define in m_Island._defines.Distinct()) arguments.Add("-define:" + define); - var pathMappings = new List(_island._files.Length); - foreach (string source in _island._files) + var pathMappings = new List(m_Island._files.Length); + foreach (string source in m_Island._files) { var preparedFileName = PrepareFileName(source); if (preparedFileName != source) @@ -53,35 +53,39 @@ override protected Program StartCompiler() arguments.Add(preparedFileName); } - if (!AddCustomResponseFileIfPresent(arguments, ReponseFilename)) + if (!AddCustomResponseFileIfPresent(arguments, ResponseFilename)) { - if (_island._api_compatibility_level == ApiCompatibilityLevel.NET_2_0_Subset && AddCustomResponseFileIfPresent(arguments, "smcs.rsp")) - Debug.LogWarning(string.Format("Using obsolete custom response file 'smcs.rsp'. Please use '{0}' instead.", ReponseFilename)); - else if (_island._api_compatibility_level == ApiCompatibilityLevel.NET_2_0 && AddCustomResponseFileIfPresent(arguments, "gmcs.rsp")) - Debug.LogWarning(string.Format("Using obsolete custom response file 'gmcs.rsp'. Please use '{0}' instead.", ReponseFilename)); + if (m_Island._api_compatibility_level == ApiCompatibilityLevel.NET_2_0_Subset + && AddCustomResponseFileIfPresent(arguments, "smcs.rsp")) + { + Debug.LogWarning("Using obsolete custom response file \'smcs.rsp\'. " + + $"Please use '{ResponseFilename}' instead."); + } + else if (m_Island._api_compatibility_level == ApiCompatibilityLevel.NET_2_0 + && AddCustomResponseFileIfPresent(arguments, "gmcs.rsp")) + { + Debug.LogWarning("Using obsolete custom response file \'gmcs.rsp\'. " + + $"Please use '{ResponseFilename}' instead."); + } } return StartCompiler( - _island._target, - GetCompilerPath(arguments), + m_Island._target, + GetCompilerPath(), arguments, - BuildPipeline.CompatibilityProfileToClassLibFolder(_island._api_compatibility_level), + BuildPipeline.CompatibilityProfileToClassLibFolder(m_Island._api_compatibility_level), false, MonoInstallationFinder.GetMonoInstallation(MonoInstallationFinder.MonoBleedingEdgeInstallation), pathMappings ); } - private string GetCompilerPath(List arguments) + static string GetCompilerPath() { string dir = MonoInstallationFinder.GetProfileDirectory("4.5", MonoInstallationFinder.MonoBleedingEdgeInstallation); var compilerPath = Path.Combine(dir, "mcs.exe"); if (File.Exists(compilerPath)) { - var systemAssemblyDirectory = MonoLibraryHelpers.GetSystemReferenceDirectory(_island._api_compatibility_level); - - if (!string.IsNullOrEmpty(systemAssemblyDirectory) && Directory.Exists(systemAssemblyDirectory)) - arguments.Add("-lib:" + PrepareFileName(systemAssemblyDirectory)); return compilerPath; } @@ -93,6 +97,11 @@ protected override CompilerOutputParserBase CreateOutputParser() return new MonoCSharpCompilerOutputParser(); } + protected override string[] GetSystemReferenceDirectories() + { + return MonoLibraryHelpers.GetSystemReferenceDirectories(m_Island._api_compatibility_level); + } + public static string[] Compile(string[] sources, string[] references, string[] defines, string outputFile, bool allowUnsafeCode) { var island = new MonoIsland(BuildTarget.StandaloneWindows, ApiCompatibilityLevel.NET_2_0_Subset, allowUnsafeCode, sources, references, defines, outputFile); diff --git a/Editor/Mono/Scripting/Compilers/MonoScriptCompilerBase.cs b/Editor/Mono/Scripting/Compilers/MonoScriptCompilerBase.cs index 52122f5232..6d919acd25 100644 --- a/Editor/Mono/Scripting/Compilers/MonoScriptCompilerBase.cs +++ b/Editor/Mono/Scripting/Compilers/MonoScriptCompilerBase.cs @@ -16,14 +16,14 @@ protected MonoScriptCompilerBase(MonoIsland island, bool runUpdater) : base(isla protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List arguments) { - return StartCompiler(target, compiler, arguments, BuildPipeline.CompatibilityProfileToClassLibFolder(_island._api_compatibility_level)); + return StartCompiler(target, compiler, arguments, BuildPipeline.CompatibilityProfileToClassLibFolder(m_Island._api_compatibility_level)); } protected ManagedProgram StartCompiler(BuildTarget target, string compiler, List arguments, string profileDirectory) { AddCustomResponseFileIfPresent(arguments, Path.GetFileNameWithoutExtension(compiler) + ".rsp"); - var monoInstallation = (PlayerSettingsEditor.IsLatestApiCompatibility(_island._api_compatibility_level)) + var monoInstallation = PlayerSettingsEditor.IsLatestApiCompatibility(m_Island._api_compatibility_level) ? MonoInstallationFinder.GetMonoBleedingEdgeInstallation() : MonoInstallationFinder.GetMonoInstallation(); return StartCompiler(target, compiler, arguments, profileDirectory, true, monoInstallation); diff --git a/Editor/Mono/Scripting/Compilers/NuGetPackageResolver.cs b/Editor/Mono/Scripting/Compilers/NuGetPackageResolver.cs deleted file mode 100644 index 3ad6f81a6c..0000000000 --- a/Editor/Mono/Scripting/Compilers/NuGetPackageResolver.cs +++ /dev/null @@ -1,117 +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; - -// Note: this file is externally included included in some tools - SerializationWeaver, AssemblyUpdater, InternalCallReplacer etc. - -namespace UnityEditor.Scripting.Compilers -{ - internal sealed class NuGetPackageResolver - { - public string PackagesDirectory - { - get; - set; - } - - public string ProjectLockFile - { - get; - set; - } - - public string TargetMoniker - { - get; - set; - } - - public string[] ResolvedReferences - { - get; - private set; - } - - public NuGetPackageResolver() - { - TargetMoniker = "UAP,Version=v10.0"; - } - - private string ConvertToWindowsPath(string path) - { - return path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); - } - - public string[] Resolve() - { - var text = File.ReadAllText(ProjectLockFile); - var lockFile = (Dictionary)Json.Deserialize(text); - var targets = (Dictionary)lockFile["targets"]; - var target = FindUWPTarget(targets); - - var references = new List(); - var packagesPath = ConvertToWindowsPath(GetPackagesPath()); - - foreach (var packagePair in target) - { - var package = (Dictionary)packagePair.Value; - - object compileObject; - if (!package.TryGetValue("compile", out compileObject)) - continue; - var compile = (Dictionary)compileObject; - - var parts = packagePair.Key.Split('/'); - var packageId = parts[0]; - var packageVersion = parts[1]; - var packagePath = Path.Combine(Path.Combine(packagesPath, packageId), packageVersion); - if (!Directory.Exists(packagePath)) - throw new Exception(string.Format("Package directory not found: \"{0}\".", packagePath)); - - foreach (var name in compile.Keys) - { - const string emptyFolder = "_._"; - if (string.Equals(Path.GetFileName(name), emptyFolder, StringComparison.InvariantCultureIgnoreCase)) - continue; - var reference = Path.Combine(packagePath, ConvertToWindowsPath(name)); - if (!File.Exists(reference)) - throw new Exception(string.Format("Reference not found: \"{0}\".", reference)); - references.Add(reference); - } - - if (package.ContainsKey("frameworkAssemblies")) - throw new NotImplementedException("Support for \"frameworkAssemblies\" property has not been implemented yet."); - } - - ResolvedReferences = references.ToArray(); - return ResolvedReferences; - } - - private Dictionary FindUWPTarget(Dictionary targets) - { - foreach (var target in targets) - { - if (target.Key.StartsWith(TargetMoniker) && !target.Key.Contains("/")) - return (Dictionary)target.Value; - } - - throw new InvalidOperationException("Could not find suitable target for " + TargetMoniker + " in project.lock.json file."); - } - - private string GetPackagesPath() - { - var value = PackagesDirectory; - if (!string.IsNullOrEmpty(value)) - return value; - value = Environment.GetEnvironmentVariable("NUGET_PACKAGES"); - if (!string.IsNullOrEmpty(value)) - return value; - var userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); - return Path.Combine(Path.Combine(userProfile, ".nuget"), "packages"); - } - } -} diff --git a/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs b/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs index fd3072da16..d140999018 100644 --- a/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs +++ b/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using UnityEditor.Scripting.ScriptCompilation; using UnityEngine; using UnityEditor.Utils; @@ -22,9 +23,10 @@ public class Reference } public string[] Defines; - public Reference[] References; + public Reference[] FullPathReferences; public bool Unsafe; public string[] Errors; + public string[] OtherArguments; } public class CompilerOption @@ -38,9 +40,10 @@ public class CompilerOption private Program process; private string _responseFile = null; private bool _runAPIUpdater; + string m_ProjectDirectory; // ToDo: would be nice to move MonoIsland to MonoScriptCompilerBase - protected MonoIsland _island; + protected MonoIsland m_Island; protected abstract Program StartCompiler(); @@ -48,8 +51,9 @@ public class CompilerOption protected ScriptCompilerBase(MonoIsland island, bool runAPIUpdater) { - _island = island; + m_Island = island; _runAPIUpdater = runAPIUpdater; + m_ProjectDirectory = Directory.GetParent(Application.dataPath).FullName.ConvertSeparatorsToUnity(); } protected string[] GetErrorOutput() @@ -98,15 +102,17 @@ public void WaitForCompilationToFinish() protected string GetMonoProfileLibDirectory() { - var profile = BuildPipeline.CompatibilityProfileToClassLibFolder(_island._api_compatibility_level); + var profile = BuildPipeline.CompatibilityProfileToClassLibFolder(m_Island._api_compatibility_level); - var monoInstall = (PlayerSettingsEditor.IsLatestApiCompatibility(_island._api_compatibility_level)) + var monoInstall = PlayerSettingsEditor.IsLatestApiCompatibility(m_Island._api_compatibility_level) ? MonoInstallationFinder.MonoBleedingEdgeInstallation : MonoInstallationFinder.MonoInstallation; return MonoInstallationFinder.GetProfileDirectory(profile, monoInstall); } + protected abstract string[] GetSystemReferenceDirectories(); + protected bool AddCustomResponseFileIfPresent(List arguments, string responseFileName) { var relativeCustomResponseFilePath = Path.Combine("Assets", responseFileName); @@ -114,19 +120,36 @@ protected bool AddCustomResponseFileIfPresent(List arguments, string res if (!File.Exists(relativeCustomResponseFilePath)) return false; - arguments.Add("@" + relativeCustomResponseFilePath); + var responseFileData = ParseResponseFileFromFile( + Path.Combine(m_ProjectDirectory, relativeCustomResponseFilePath), + Application.dataPath, + GetSystemReferenceDirectories()); + foreach (var error in responseFileData.Errors) + { + Debug.LogError($"{relativeCustomResponseFilePath} Parse Error : {error}"); + } + + arguments.AddRange(responseFileData.Defines.Distinct().Select(define => "/define:" + define)); + arguments.AddRange(responseFileData.FullPathReferences.Select(reference => + "/reference:" + PrepareFileName(reference.Assembly))); + + if (responseFileData.Unsafe) arguments.Add("/unsafe"); + arguments.AddRange(responseFileData.OtherArguments); return true; } - public static ResponseFileData ParseResponseFileFromFile(string responseFilePath) + public static ResponseFileData ParseResponseFileFromFile( + string responseFilePath, + string projectDirectory, + string[] systemReferenceDirectories) { if (!File.Exists(responseFilePath)) { var empty = new ResponseFileData { Defines = new string[0], - References = new ResponseFileData.Reference[0], + FullPathReferences = new ResponseFileData.Reference[0], Unsafe = false, Errors = new string[0] }; @@ -136,7 +159,11 @@ public static ResponseFileData ParseResponseFileFromFile(string responseFilePath var responseFileText = File.ReadAllText(responseFilePath); - return ParseResponseFileText(responseFileText); + return ParseResponseFileText( + responseFileText, + responseFilePath, + projectDirectory, + systemReferenceDirectories); } // From: @@ -204,7 +231,11 @@ static string[] ResponseFileTextToStrings(string responseFileText) return args.ToArray(); } - public static ResponseFileData ParseResponseFileText(string responseFileText) + static ResponseFileData ParseResponseFileText( + string responseFileText, + string responseFileName, + string projectDirectory, + string[] systemReferenceDirectories) { var compilerOptions = new List(); @@ -232,6 +263,7 @@ public static ResponseFileData ParseResponseFileText(string responseFileText) compilerOptions.Add(new CompilerOption { Arg = arg, Value = value }); } + var responseArguments = new List(); var defines = new List(); var references = new List(); bool unsafeDefined = false; @@ -276,24 +308,61 @@ public static ResponseFileData ParseResponseFileText(string responseFileText) break; } - foreach (string reference in refs) + var reference = refs[0]; + if (reference.Length == 0) { - if (reference.Length == 0) - continue; + continue; + } - int index = reference.IndexOf('='); - if (index > -1) - { - string alias = reference.Substring(0, index); - string assembly = reference.Substring(index + 1); + ResponseFileData.Reference responseReference; + + int index = reference.IndexOf('='); + if (index > -1) + { + string alias = reference.Substring(0, index); + string assembly = reference.Substring(index + 1); + + responseReference = new ResponseFileData.Reference { Alias = alias, Assembly = assembly }; + } + else + { + responseReference = new ResponseFileData.Reference { Alias = string.Empty, Assembly = reference }; + } - references.Add(new ResponseFileData.Reference { Alias = alias, Assembly = assembly }); + string fullPathReference = ""; + var referencePath = responseReference.Assembly; + if (Path.IsPathRooted(referencePath)) + { + fullPathReference = referencePath; + } + else + { + foreach (var directory in systemReferenceDirectories) + { + var systemReferencePath = Paths.Combine(directory, referencePath); + if (File.Exists(systemReferencePath)) + { + fullPathReference = systemReferencePath; + break; + } } - else + + var userPath = Paths.Combine(projectDirectory, referencePath); + if (File.Exists(userPath)) { - references.Add(new ResponseFileData.Reference { Alias = string.Empty, Assembly = reference }); + fullPathReference = userPath; } } + + if (fullPathReference == "") + { + errors.Add($"{responseFileName}: not parsed correctly: {responseReference.Assembly} could not be found as a system library.\n" + + "If this was meant as a user reference please provide the relative path from project root (parent of the Assets folder) in the response file."); + continue; + } + + responseReference.Assembly = fullPathReference.Replace('\\', '/'); + references.Add(responseReference); } break; @@ -309,15 +378,20 @@ public static ResponseFileData ParseResponseFileText(string responseFileText) unsafeDefined = false; } break; + default: + var valueWithColon = value.Length == 0 ? "" : ":" + value; + responseArguments.Add(arg + valueWithColon); + break; } } var responseFileData = new ResponseFileData { Defines = defines.ToArray(), - References = references.ToArray(), + FullPathReferences = references.ToArray(), Unsafe = unsafeDefined, - Errors = errors.ToArray() + Errors = errors.ToArray(), + OtherArguments = responseArguments.ToArray(), }; return responseFileData; @@ -336,7 +410,11 @@ public virtual CompilerMessage[] GetCompilerMessages() DumpStreamOutputToLog(); - return CreateOutputParser().Parse(GetStreamContainingCompilerMessages(), CompilationHadFailure(), Path.GetFileName(_island._output)).ToArray(); + return CreateOutputParser().Parse( + GetStreamContainingCompilerMessages(), + CompilationHadFailure(), + Path.GetFileName(m_Island._output) + ).ToArray(); } protected bool CompilationHadFailure() @@ -367,7 +445,11 @@ private void DumpStreamOutputToLog() string[] stdOutput = GetStandardOutput(); - Console.WriteLine("-----CompilerOutput:-stdout--exitcode: " + process.ExitCode + "--compilationhadfailure: " + hadCompilationFailure + "--outfile: " + _island._output); + Console.WriteLine( + "-----CompilerOutput:-stdout--exitcode: " + process.ExitCode + + "--compilationhadfailure: " + hadCompilationFailure + + "--outfile: " + m_Island._output + ); foreach (string line in stdOutput) Console.WriteLine(line); @@ -386,7 +468,11 @@ protected void RunAPIUpdaterIfRequired(string responseFile, IList pathMa var pathMappingsFilePath = Path.GetTempFileName(); File.WriteAllLines(pathMappingsFilePath, pathMappings.ToArray()); - APIUpdaterHelper.UpdateScripts(responseFile, _island.GetExtensionOfSourceFiles(), PrepareFileName(pathMappingsFilePath)); + APIUpdaterHelper.UpdateScripts( + responseFile, + m_Island.GetExtensionOfSourceFiles(), + PrepareFileName(pathMappingsFilePath) + ); } } diff --git a/Editor/Mono/Scripting/Compilers/SupportedLanguage.cs b/Editor/Mono/Scripting/Compilers/SupportedLanguage.cs deleted file mode 100644 index c1ac360e69..0000000000 --- a/Editor/Mono/Scripting/Compilers/SupportedLanguage.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 - -namespace UnityEditor.Scripting.Compilers -{ - internal abstract class SupportedLanguage - { - public abstract string GetExtensionICanCompile(); - public abstract string GetLanguageName(); - public abstract ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater); - public virtual string GetNamespace(string fileName, string definedSymbols) - { - return string.Empty; - } - - public virtual bool CompilerRequiresAdditionalReferences() - { - return false; - } - } -} diff --git a/Editor/Mono/Scripting/Compilers/UWPReferences.cs b/Editor/Mono/Scripting/Compilers/UWPReferences.cs index f057f616bf..d2c2861e13 100644 --- a/Editor/Mono/Scripting/Compilers/UWPReferences.cs +++ b/Editor/Mono/Scripting/Compilers/UWPReferences.cs @@ -31,20 +31,22 @@ internal class UWPSDK { public readonly Version Version; public readonly Version MinVSVersion; + public readonly IEnumerable PreviousSDKs; - public UWPSDK(Version version, Version minVSVersion) + public UWPSDK(Version version, Version minVSVersion, IEnumerable previousSDKs) { Version = version; MinVSVersion = minVSVersion; + PreviousSDKs = previousSDKs; } } - internal class PreviousSDKVersion + internal class PreviousUWPSDK { - public readonly string Version; + public readonly Version Version; public readonly bool DefaultFallback; - public PreviousSDKVersion(string version, bool defaultFallback) + public PreviousUWPSDK(Version version, bool defaultFallback) { Version = version; DefaultFallback = defaultFallback; @@ -71,13 +73,19 @@ public UWPExtension(string manifest, string windowsKitsFolder, string sdkVersion } } - public static string[] GetReferences(Version sdkVersion) + private static readonly Version kMinimumSupportedUWPVersion = new Version(10, 0, 10240, 0); + private static readonly PreviousUWPSDK kMinimumSupportedPreviousUWPSDK = new PreviousUWPSDK(kMinimumSupportedUWPVersion, true); + private static readonly UWPSDK kMinimumSupportedUWPSDK = new UWPSDK(kMinimumSupportedUWPVersion, new Version(14, 0), new[] { kMinimumSupportedPreviousUWPSDK }); + + public static UWPSDK MinimumSupportedUWPSDK { get { return kMinimumSupportedUWPSDK; } } + + public static string[] GetReferences(UWPSDK sdk) { var folder = GetWindowsKit10(); if (string.IsNullOrEmpty(folder)) return new string[0]; - var version = SdkVersionToString(sdkVersion); + var version = SdkVersionToString(sdk.Version); var references = new HashSet(StringComparer.InvariantCultureIgnoreCase); var windowsWinMd = CombinePaths(folder, "UnionMetadata", version, "Facade", "Windows.winmd"); @@ -102,13 +110,13 @@ public static string[] GetReferences(Version sdkVersion) return references.ToArray(); } - public static IEnumerable GetExtensionSDKs(Version sdkVersion) + public static IEnumerable GetExtensionSDKs(UWPSDK sdk) { var windowsKit10Directory = GetWindowsKit10(); if (string.IsNullOrEmpty(windowsKit10Directory)) return new UWPExtensionSDK[0]; - return GetExtensionSDKs(windowsKit10Directory, SdkVersionToString(sdkVersion)); + return GetExtensionSDKs(windowsKit10Directory, SdkVersionToString(sdk.Version)); } static string SdkVersionToString(Version version) @@ -125,17 +133,17 @@ static string SdkVersionToString(Version version) return sdkVersion; } - public static IEnumerable>>> GetInstalledSDKs() + public static IEnumerable GetInstalledSDKs() { var windowsKit10Directory = GetWindowsKit10(); if (string.IsNullOrEmpty(windowsKit10Directory)) - return Enumerable.Empty>>>(); + return Enumerable.Empty(); var platformsUAP = CombinePaths(windowsKit10Directory, "Platforms", "UAP"); if (!Directory.Exists(platformsUAP)) - return Enumerable.Empty>>>(); + return Enumerable.Empty(); - var allSDKs = new Dictionary>>(); + var allSDKs = new List(); var filesUnderPlatformsUAP = Directory.GetFiles(platformsUAP, "*", SearchOption.AllDirectories); var allPlatformXmlFiles = filesUnderPlatformsUAP.Where(f => string.Equals("Platform.xml", Path.GetFileName(f), StringComparison.OrdinalIgnoreCase)); @@ -158,50 +166,64 @@ public static IEnumerable e.Value).FirstOrDefault(); // Get supported previous versionss var previousVersionPath = Path.Combine(Path.GetDirectoryName(platformXmlFile), "PreviousPlatforms.xml"); - var previousVersions = new SortedList(); + var previousVersions = new List(); if (File.Exists(previousVersionPath)) { + XNamespace xn = "http://microsoft.com/schemas/Windows/SDK/PreviousPlatforms"; + XDocument previousPlatformsDocument = null; + try { - XNamespace xn = "http://microsoft.com/schemas/Windows/SDK/PreviousPlatforms"; - var previousPlatformsDocument = XDocument.Load(previousVersionPath); + previousPlatformsDocument = XDocument.Load(previousVersionPath); + } + catch + { + } - foreach (XElement previousPlatformElement in previousPlatformsDocument.Element(xn + "PreviousPlatforms").Elements(xn + "ApplicationPlatform")) + if (previousPlatformsDocument != null) + { + var previousPlatformsElement = previousPlatformsDocument.Element(xn + "PreviousPlatforms"); + if (previousPlatformsElement != null) { - var previousVersion = previousPlatformElement.Attribute("version").Value; - var isDefault = false; - - try + foreach (XElement previousPlatformElement in previousPlatformsElement.Elements(xn + "ApplicationPlatform")) { - isDefault = bool.Parse(previousPlatformElement.Attribute("IsDefaultFallback").Value); + var versionAttribute = previousPlatformElement.Attribute("version"); + if (versionAttribute != null) + { + var previousVersionString = versionAttribute.Value; + bool isDefault = false; + + var isDefaultFallbackAttribute = previousPlatformElement.Attribute("IsDefaultFallback"); + if (isDefaultFallbackAttribute != null) + bool.TryParse(isDefaultFallbackAttribute.Value, out isDefault); + + var previousVersion = TryParseVersion(previousVersionString); + if (previousVersion != null && previousVersion >= kMinimumSupportedUWPVersion) + previousVersions.Add(new PreviousUWPSDK(previousVersion, isDefault)); + } } - catch - { - // Ignore exception. The IsDefaultFallback attribute isn't present. This is OK. - } - - previousVersions.Add(previousVersion, new PreviousSDKVersion(previousVersion, isDefault)); } } - catch - { - // Ignore exception. We'll just use the default below. - } } if (previousVersions.Count == 0) { - // For previous versions, only support the current version if no PreviousVersions.xml was found. - previousVersions.Add(version.ToString(), new PreviousSDKVersion(version.ToString(), true)); + // For previous versions, only support the current version and our minimum supported version if no PreviousVersions.xml was found. + previousVersions.Add(new PreviousUWPSDK(version, true)); + + if (version > kMinimumSupportedUWPVersion) + previousVersions.Add(new PreviousUWPSDK(kMinimumSupportedUWPVersion, false)); } - previousVersions.Reverse(); - allSDKs.Add(new UWPSDK(version, TryParseVersion(minVSVersionString)), previousVersions); + allSDKs.Add(new UWPSDK(version, TryParseVersion(minVSVersionString), previousVersions)); } } } diff --git a/Editor/Mono/Scripting/Compilers/UnityScriptCompiler.cs b/Editor/Mono/Scripting/Compilers/UnityScriptCompiler.cs index 48b4ab118e..7b4c4c5809 100644 --- a/Editor/Mono/Scripting/Compilers/UnityScriptCompiler.cs +++ b/Editor/Mono/Scripting/Compilers/UnityScriptCompiler.cs @@ -25,7 +25,7 @@ protected override CompilerOutputParserBase CreateOutputParser() return new UnityScriptCompilerOutputParser(); } - override protected Program StartCompiler() + protected override Program StartCompiler() { var arguments = new List { @@ -37,30 +37,30 @@ override protected Program StartCompiler() "-nowarn:BCW0016", "-nowarn:BCW0003", "-method:Main", - "-out:" + _island._output, + "-out:" + m_Island._output, "-x-type-inference-rule-attribute:" + typeof(UnityEngineInternal.TypeInferenceRuleAttribute) }; if (StrictBuildTarget()) arguments.Add("-pragmas:strict,downcast"); - foreach (var define in _island._defines.Distinct()) + foreach (var define in m_Island._defines.Distinct()) arguments.Add("-define:" + define); - foreach (var dll in _island._references) + foreach (var dll in m_Island._references) arguments.Add("-r:" + PrepareFileName(dll)); - var compilingEditorScripts = Array.Exists(_island._references, UnityEditorPattern.IsMatch); + var compilingEditorScripts = Array.Exists(m_Island._references, UnityEditorPattern.IsMatch); if (compilingEditorScripts) arguments.Add("-i:UnityEditor"); - else if (!BuildPipeline.IsUnityScriptEvalSupported(_island._target)) - arguments.Add(string.Format("-disable-eval:eval is not supported on the current build target ({0}).", _island._target)); + else if (!BuildPipeline.IsUnityScriptEvalSupported(m_Island._target)) + arguments.Add($"-disable-eval:eval is not supported on the current build target ({m_Island._target})."); - foreach (string source in _island._files) + foreach (string source in m_Island._files) arguments.Add(PrepareFileName(source)); var compilerPath = Path.Combine(GetUnityScriptCompilerDirectory(), "us.exe"); - return StartCompiler(_island._target, compilerPath, arguments, GetUnityScriptProfileDirectory()); + return StartCompiler(m_Island._target, compilerPath, arguments, GetUnityScriptProfileDirectory()); } string GetUnityScriptCompilerDirectory() @@ -74,14 +74,19 @@ string GetUnityScriptCompilerDirectory() string GetUnityScriptProfileDirectory() { if (EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Legacy) - return BuildPipeline.CompatibilityProfileToClassLibFolder(_island._api_compatibility_level); + return BuildPipeline.CompatibilityProfileToClassLibFolder(m_Island._api_compatibility_level); return k_UnityScriptProfileDirectory; } private bool StrictBuildTarget() { - return Array.IndexOf(_island._defines, "ENABLE_DUCK_TYPING") == -1; + return Array.IndexOf(m_Island._defines, "ENABLE_DUCK_TYPING") == -1; + } + + protected override string[] GetSystemReferenceDirectories() + { + return new[] { GetUnityScriptCompilerDirectory() }; } protected override string[] GetStreamContainingCompilerMessages() diff --git a/Editor/Mono/Scripting/Compilers/UnityScriptCompilerOutputParser.cs b/Editor/Mono/Scripting/Compilers/UnityScriptCompilerOutputParser.cs deleted file mode 100644 index 9ea0c0ad66..0000000000 --- a/Editor/Mono/Scripting/Compilers/UnityScriptCompilerOutputParser.cs +++ /dev/null @@ -1,34 +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.Text.RegularExpressions; - -namespace UnityEditor.Scripting.Compilers -{ - class UnityScriptCompilerOutputParser : CompilerOutputParserBase - { - private static Regex sCompilerOutput = new Regex(@"\s*(?.*)\((?\d+),(?\d+)\):\s*[BU]C(?W|E)(?[^:]*):\s*(?.*)", RegexOptions.ExplicitCapture); - - private static Regex sUnknownTypeOrNamespace = new Regex(@"[^']*'(?[^']+)'.*", RegexOptions.ExplicitCapture | RegexOptions.Compiled); - - protected override string GetErrorIdentifier() - { - return "E"; - } - - protected override Regex GetOutputRegex() - { - return sCompilerOutput; - } - - protected override NormalizedCompilerStatus NormalizedStatusFor(Match match) - { - var status = TryNormalizeCompilerStatus(match, "0018", sUnknownTypeOrNamespace, NormalizeSimpleUnknownTypeOfNamespaceError); - if (status.code != NormalizedCompilerStatusCode.NotNormalized) - return status; - - return TryNormalizeCompilerStatus(match, "0005", sUnknownTypeOrNamespace, NormalizeSimpleUnknownTypeOfNamespaceError); - } - } -} diff --git a/Editor/Mono/Scripting/Compilers/UnityScriptLanguage.cs b/Editor/Mono/Scripting/Compilers/UnityScriptLanguage.cs deleted file mode 100644 index 7bcf8c2c41..0000000000 --- a/Editor/Mono/Scripting/Compilers/UnityScriptLanguage.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 - -namespace UnityEditor.Scripting.Compilers -{ - internal class UnityScriptLanguage : SupportedLanguage - { - public override string GetExtensionICanCompile() - { - return "js"; - } - - public override string GetLanguageName() - { - return "UnityScript"; - } - - public override ScriptCompilerBase CreateCompiler(MonoIsland island, bool buildingForEditor, BuildTarget targetPlatform, bool runUpdater) - { - return new UnityScriptCompiler(island, runUpdater); - } - } -} diff --git a/Editor/Mono/Scripting/PragmaFixing30.cs b/Editor/Mono/Scripting/PragmaFixing30.cs deleted file mode 100644 index f4accaaab8..0000000000 --- a/Editor/Mono/Scripting/PragmaFixing30.cs +++ /dev/null @@ -1,148 +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 UnityEditor; -using UnityEditorInternal; -using System; -using System.IO; -using System.Text; -using System.Text.RegularExpressions; -using System.Collections; -using System.Collections.Generic; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEditor.Scripting -{ - internal class PragmaFixing30 - { - [RequiredByNativeCode] - static void FixJavaScriptPragmas() - { - string[] filesToFix = CollectBadFiles(); - if (filesToFix.Length == 0) - return; - - if (!InternalEditorUtility.inBatchMode) - PragmaFixingWindow.ShowWindow(filesToFix); - else - FixFiles(filesToFix); - } - - public static void FixFiles(string[] filesToFix) - { - foreach (string f in filesToFix) - { - try - { - FixPragmasInFile(f); - } - catch (Exception ex) - { - Debug.LogError("Failed to fix pragmas in file '" + f + "'.\n" + ex.Message); - } - } - } - - static bool FileNeedsPragmaFixing(string fileName) - { - return CheckOrFixPragmas(fileName, true); - } - - static void FixPragmasInFile(string fileName) - { - CheckOrFixPragmas(fileName, false); - } - - static bool CheckOrFixPragmas(string fileName, bool onlyCheck) - { - string oldText = File.ReadAllText(fileName); - StringBuilder text = new StringBuilder(oldText); - - LooseComments(text); - - Match strictMatch = PragmaMatch(text, "strict"); - - if (!strictMatch.Success) - return false; - - bool hasDowncast = PragmaMatch(text, "downcast").Success; - bool hasImplicit = PragmaMatch(text, "implicit").Success; - - if (hasDowncast && hasImplicit) - return false; - - if (!onlyCheck) - DoFixPragmasInFile(fileName, oldText, strictMatch.Index + strictMatch.Length, hasDowncast, hasImplicit); - - return true; - } - - static void DoFixPragmasInFile(string fileName, string oldText, int fixPos, bool hasDowncast, bool hasImplicit) - { - string textToAdd = string.Empty; - string lineEndings = HasWinLineEndings(oldText) ? "\r\n" : "\n"; - - if (!hasImplicit) - textToAdd += lineEndings + "#pragma implicit"; - if (!hasDowncast) - textToAdd += lineEndings + "#pragma downcast"; - - File.WriteAllText(fileName, oldText.Insert(fixPos, textToAdd)); - } - - static bool HasWinLineEndings(string text) - { - return text.IndexOf("\r\n") != -1; - } - - static IEnumerable SearchRecursive(string dir, string mask) - { - foreach (string d in Directory.GetDirectories(dir)) - foreach (string f in SearchRecursive(d, mask)) - yield return f; - foreach (string f in Directory.GetFiles(dir, mask)) - yield return f; - } - - static void LooseComments(StringBuilder sb) - { - // TODO: better comment ignoring? this one sort of does the job, it handles // - // and if it's in multiline comments, our added lines will end up commented as well - Regex r = new Regex("//"); - foreach (Match m in r.Matches(sb.ToString())) - { - int pos = m.Index; - while (pos < sb.Length && sb[pos] != '\n' && sb[pos] != '\r') - sb[pos++] = ' '; - } - } - - static Match PragmaMatch(StringBuilder sb, string pragma) - { - // unity java script, like regex, treats new line as space character as well - return new Regex(@"#\s*pragma\s*" + pragma).Match(sb.ToString()); - } - - static string[] CollectBadFiles() - { - List filesToFix = new List(); - - foreach (string f in SearchRecursive(Path.Combine(Directory.GetCurrentDirectory(), "Assets"), "*.js")) - { - try - { - if (FileNeedsPragmaFixing(f)) - filesToFix.Add(f); - } - catch (Exception ex) - { - Debug.LogError("Failed to fix pragmas in file '" + f + "'.\n" + ex.Message); - } - } - - return filesToFix.ToArray(); - } - } -} diff --git a/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs b/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs index 55e0c6d088..a8a63432fa 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/CSharpNamespaceParser.cs @@ -11,6 +11,14 @@ namespace UnityEditor.Scripting.ScriptCompilation { + internal class IllegalNamespaceParsing : Exception + { + public IllegalNamespaceParsing(string className, Exception cause) + : base($"Searching for classname: '{className}' caused error in CSharpNameParser", cause) + { + } + } + internal static class CSharpNamespaceParser { static readonly Regex k_ReDefineExpr = new Regex(@"r'\s+|([=!]=)\s*(true|false)|([_a-zA-Z][_a-zA-Z0-9]*)|([()!]|&&|\|\|)", RegexOptions.Compiled); @@ -20,6 +28,7 @@ internal static class CSharpNamespaceParser static readonly Regex k_VerbatimStrings = new Regex(@"@(""[^""]*"")+", RegexOptions.Compiled); static readonly Regex k_NewlineRegex = new Regex("\r\n?", RegexOptions.Compiled); static readonly Regex k_SingleQuote = new Regex(@"((? defines) var split = source.Split(new[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (var s in split) { - if (s.Contains("#define")) + var match = k_ConditionalCompilation.Match(s); + var directive = match.Groups[1].Value; + var arg = match.Groups[2].Value; + if (directive == "define") { - if (stack.Count == 0 || stack.Peek().Item1) defines.Add(s.Split(new[] { "#define" }, StringSplitOptions.None)[1].Trim()); + if (stack.Count == 0 || stack.Peek().Item1) defines.Add(arg.Trim()); } - else if (s.Contains("#undefine")) + else if (directive == "undefine") { - if (stack.Count == 0 || stack.Peek().Item1) defines.Add(s.Split(new[] { "#define" }, StringSplitOptions.None)[1].Trim()); + if (stack.Count == 0 || stack.Peek().Item1) defines.Add(arg.Trim()); } - else if (s.Contains("#if")) + else if (directive == "if") { - var evalResult = EvaluateDefine(s.Split(new[] { "#if" }, StringSplitOptions.None)[1].Trim(), defines); + var evalResult = EvaluateDefine(arg.Trim(), defines); var isEmitting = stack.Count == 0 || stack.Peek().Item1; stack.Push(new Tuple(isEmitting && evalResult, isEmitting && !evalResult)); } - else if (s.Contains("#elif")) + else if (directive == "elif") { + var evalResult = EvaluateDefine(arg, defines); var elseEmitting = stack.Peek().Item2; - var evalResult = EvaluateDefine(s.Split(new[] { "#elif" }, StringSplitOptions.None)[1], defines); - stack.Pop(); - stack.Push(new Tuple(elseEmitting && evalResult, elseEmitting && !evalResult)); + stack.Pop(); stack.Push(new Tuple(elseEmitting && evalResult, elseEmitting && !evalResult)); } - else if (s.Contains("#else")) + else if (directive == "else") { var elseEmitting = stack.Peek().Item2; - stack.Pop(); - stack.Push(new Tuple(elseEmitting, false)); + stack.Pop(); stack.Push(new Tuple(elseEmitting, false)); } - else if (s.Contains("#endif")) + else if (directive == "endif") { stack.Pop(); } diff --git a/Editor/Mono/Scripting/ScriptCompilation/CompilerMessage.cs b/Editor/Mono/Scripting/ScriptCompilation/CompilerMessage.cs deleted file mode 100644 index a7eddb93d6..0000000000 --- a/Editor/Mono/Scripting/ScriptCompilation/CompilerMessage.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 - -namespace UnityEditor.Compilation -{ - public enum CompilerMessageType - { - Error = 0, - Warning = 1 - } - - public struct CompilerMessage - { - public string message; - public string file; - public int line; - public int column; - public CompilerMessageType type; - } -} diff --git a/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs b/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs index f784520a09..1eccdccda8 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/EditorBuildRules.cs @@ -769,6 +769,17 @@ static bool IsCompatibleWithPlatformAndDefines(TargetAssembly assembly, ScriptAs return assembly.IsCompatibleFunc == null || assembly.IsCompatibleFunc(settings, assembly.Defines); } + public static bool IsCompatibleWithPlatformAndDefines(TargetAssembly assembly, BuildTarget buildTarget, EditorScriptCompilationOptions options) + { + var settings = new ScriptAssemblySettings + { + BuildTarget = buildTarget, + CompilationOptions = options + }; + + return IsCompatibleWithPlatformAndDefines(assembly, settings); + } + internal static TargetAssembly[] CreatePredefinedTargetAssemblies() { var runtimeFirstPassAssemblies = new List(); diff --git a/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs b/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs index b607729175..5f5e896a54 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs @@ -148,7 +148,9 @@ public override void PostprocessMessage(ref CompilerMessage message) var index = message.message.IndexOf(EditorApplication.scriptingRuntimeVersion == ScriptingRuntimeVersion.Latest ? "Consider adding a reference to that assembly." : "Consider adding a reference to assembly"); if (index != -1) message.message = message.message.Substring(0, index); - var moduleName = GetNiceDisplayNameForModule(match.Groups[1].Value); + var moduleName = match.Groups[1].Value; + moduleName = ModuleMetadata.GetExcludingModule(moduleName); + moduleName = GetNiceDisplayNameForModule(moduleName); message.message += string.Format("Enable the built in package '{0}' in the Package Manager window to fix this error.", moduleName); } @@ -238,6 +240,23 @@ public void DirtyScript(string path) dirtyScripts.Add(path); } + public void DirtyMovedScript(string oldPath, string newPath) + { + DirtyScript(newPath); + + var targetAssembly = EditorBuildRules.GetTargetAssembly(oldPath, projectDirectory, customTargetAssemblies); + + // The target assembly might not exist any more. + if (targetAssembly == null) + { + areAllScriptsDirty = true; + } + else + { + dirtyTargetAssemblies.Add(targetAssembly); + } + } + public void DirtyRemovedScript(string path) { allScripts.Remove(path); @@ -352,7 +371,7 @@ public PrecompiledAssembly[] GetAllPrecompiledAssemblies() return this.precompiledAssemblies; } - public TargetAssemblyInfo[] GetAllCompiledAndResolvedCustomTargetAssemblies(out CustomScriptAssemblyAndReference[] assembliesWithMissingReference) + public TargetAssemblyInfo[] GetAllCompiledAndResolvedCustomTargetAssemblies(EditorScriptCompilationOptions options, BuildTarget buildTarget, out CustomScriptAssemblyAndReference[] assembliesWithMissingReference) { if (customTargetAssemblies == null) { @@ -391,6 +410,11 @@ public TargetAssemblyInfo[] GetAllCompiledAndResolvedCustomTargetAssemblies(out // of compiled assemblies. foreach (var reference in assembly.References) { + // Don't check references that are not compatible with the current build target, + // as those assemblies have not been compiled. + if (!EditorBuildRules.IsCompatibleWithPlatformAndDefines(reference, buildTarget, options)) + continue; + if (!customTargetAssemblyCompiledPaths.ContainsKey(reference)) { customTargetAssemblyCompiledPaths.Remove(assembly); @@ -487,7 +511,8 @@ void CheckCyclicAssemblyReferences() } } - Exception[] UpdateCustomTargetAssemblies() + public static Exception[] UpdateCustomScriptAssemblies(CustomScriptAssembly[] customScriptAssemblies, + PackageAssembly[] packageAssemblies) { var exceptions = new List(); @@ -495,14 +520,14 @@ Exception[] UpdateCustomTargetAssemblies() { try { - if (m_PackageAssemblies != null && !assembly.PackageAssembly.HasValue) + if (packageAssemblies != null && !assembly.PackageAssembly.HasValue) { var pathPrefix = assembly.PathPrefix.ToLowerInvariant(); - foreach (var packageAssembly in m_PackageAssemblies) + foreach (var packageAssembly in packageAssemblies) { - var lower = AssetPath.ReplaceSeparators(packageAssembly.DirectoryPath).ToLowerInvariant(); - if (pathPrefix.StartsWith(lower)) + var lower = AssetPath.ReplaceSeparators(packageAssembly.DirectoryPath + AssetPath.Separator).ToLowerInvariant(); + if (pathPrefix.StartsWith(lower, StringComparison.Ordinal)) { assembly.PackageAssembly = packageAssembly; break; @@ -521,11 +546,22 @@ Exception[] UpdateCustomTargetAssemblies() } catch (Exception e) { - SetCompilationSetupErrorFlags(CompilationSetupErrorFlags.loadError); exceptions.Add(e); } } + return exceptions.ToArray(); + } + + Exception[] UpdateCustomTargetAssemblies() + { + var exceptions = UpdateCustomScriptAssemblies(customScriptAssemblies, m_PackageAssemblies); + + if (exceptions.Length > 0) + { + SetCompilationSetupErrorFlags(CompilationSetupErrorFlags.loadError); + } + customTargetAssemblies = EditorBuildRules.CreateTargetAssemblies(customScriptAssemblies, precompiledAssemblies); ClearCompilationSetupErrorFlags(CompilationSetupErrorFlags.cyclicReferences); @@ -533,7 +569,7 @@ Exception[] UpdateCustomTargetAssemblies() // customTargetAssemblies being updated. UpdateDirtyTargetAssemblies(); - return exceptions.ToArray(); + return exceptions; } void UpdateDirtyTargetAssemblies() diff --git a/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs b/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs index c30ab10805..e51ed2fc6c 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/EditorCompilationInterface.cs @@ -155,6 +155,12 @@ public static void DirtyRemovedScript(string path) Instance.DirtyRemovedScript(path); } + [RequiredByNativeCode] + public static void DirtyMovedScript(string oldPath, string newPath) + { + Instance.DirtyMovedScript(oldPath, newPath); + } + [RequiredByNativeCode] public static void DirtyPrecompiledAssembly(string path) { @@ -210,11 +216,11 @@ public static void SetAllPackageAssemblies(EditorCompilation.PackageAssembly[] p } [RequiredByNativeCode] - public static EditorCompilation.TargetAssemblyInfo[] GetAllCompiledAndResolvedCustomTargetAssemblies() + public static EditorCompilation.TargetAssemblyInfo[] GetAllCompiledAndResolvedCustomTargetAssemblies(EditorScriptCompilationOptions options, BuildTarget buildTarget) { EditorCompilation.CustomScriptAssemblyAndReference[] assembliesWithMissingReference = null; - var result = EmitExceptionAsError(() => Instance.GetAllCompiledAndResolvedCustomTargetAssemblies(out assembliesWithMissingReference), new EditorCompilation.TargetAssemblyInfo[0]); + var result = EmitExceptionAsError(() => Instance.GetAllCompiledAndResolvedCustomTargetAssemblies(options, buildTarget, out assembliesWithMissingReference), new EditorCompilation.TargetAssemblyInfo[0]); if (assembliesWithMissingReference.Length > 0) { diff --git a/Editor/Mono/Scripting/ScriptCompilation/EditorScriptCompilationOptions.cs b/Editor/Mono/Scripting/ScriptCompilation/EditorScriptCompilationOptions.cs index 54d00b3510..c2cc1d0136 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/EditorScriptCompilationOptions.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/EditorScriptCompilationOptions.cs @@ -17,6 +17,7 @@ enum EditorScriptCompilationOptions BuildingForIl2Cpp = 1 << 3, BuildingWithAsserts = 1 << 4, BuildingIncludingTestAssemblies = 1 << 5, - BuildingPredefinedAssembliesAllowUnsafeCode = (1 << 6) + BuildingPredefinedAssembliesAllowUnsafeCode = (1 << 6), + BuildingForHeadlessPlayer = 1 << 7 }; } diff --git a/Editor/Mono/Scripting/ScriptCompilation/MonoLibraryHelpers.cs b/Editor/Mono/Scripting/ScriptCompilation/MonoLibraryHelpers.cs index f5578f113f..ecf78af84d 100644 --- a/Editor/Mono/Scripting/ScriptCompilation/MonoLibraryHelpers.cs +++ b/Editor/Mono/Scripting/ScriptCompilation/MonoLibraryHelpers.cs @@ -33,6 +33,16 @@ public static string[] GetSystemLibraryReferences(ApiCompatibilityLevel apiCompa return GetCachedSystemLibraryReferences(apiCompatibilityLevel); } + static string[] FindReferencesInDirectories(this string[] references, string[] directories) + { + return ( + from reference in references + from directory in directories + where File.Exists(Path.Combine(directory, reference)) + select Path.Combine(directory, reference) + ).ToArray(); + } + static string[] GetCachedSystemLibraryReferences(ApiCompatibilityLevel apiCompatibilityLevel) { // We cache the references because they are computed by getting files in directories on disk, @@ -43,7 +53,7 @@ static string[] GetCachedSystemLibraryReferences(ApiCompatibilityLevel apiCompat } var references = new List(); - var monoAssemblyDirectory = GetSystemReferenceDirectory(apiCompatibilityLevel); + var monoAssemblyDirectories = GetSystemReferenceDirectories(apiCompatibilityLevel); if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard_2_0) { @@ -51,19 +61,20 @@ static string[] GetCachedSystemLibraryReferences(ApiCompatibilityLevel apiCompat } else if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6) { - references.AddRange(GetSystemReferences().Select(dll => Path.Combine(monoAssemblyDirectory, dll))); - references.AddRange(GetNet46SystemReferences().Select(dll => Path.Combine(monoAssemblyDirectory, dll))); + references.AddRange(GetSystemReferences().FindReferencesInDirectories(monoAssemblyDirectories)); + references.AddRange(GetNet46SystemReferences().FindReferencesInDirectories(monoAssemblyDirectories)); // Look in the mono assembly directory for a facade folder and get a list of all the DLL's to be // used later by the language compilers. + var monoAssemblyDirectory = MonoInstallationFinder.GetProfileDirectory("4.7.1-api", MonoInstallationFinder.MonoBleedingEdgeInstallation); references.AddRange(Directory.GetFiles(Path.Combine(monoAssemblyDirectory, "Facades"), "*.dll")); references.AddRange(GetBooAndUsReferences().Select(dll => Path.Combine(MonoInstallationFinder.GetProfileDirectory("unityscript", MonoInstallationFinder.MonoBleedingEdgeInstallation), dll))); } else { - references.AddRange(GetSystemReferences().Select(dll => Path.Combine(monoAssemblyDirectory, dll))); - references.AddRange(GetBooAndUsReferences().Select(dll => Path.Combine(monoAssemblyDirectory, dll))); + references.AddRange(GetSystemReferences().FindReferencesInDirectories(monoAssemblyDirectories)); + references.AddRange(GetBooAndUsReferences().FindReferencesInDirectories(monoAssemblyDirectories)); } cachedReferences = new CachedReferences @@ -76,18 +87,40 @@ static string[] GetCachedSystemLibraryReferences(ApiCompatibilityLevel apiCompat return cachedReferences.References; } - public static string GetSystemReferenceDirectory(ApiCompatibilityLevel apiCompatibilityLevel) + static string GetSystemReference(ApiCompatibilityLevel apiCompatibilityLevel) { - if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard_2_0) - return ""; - else if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6) + if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6) return MonoInstallationFinder.GetProfileDirectory("4.7.1-api", MonoInstallationFinder.MonoBleedingEdgeInstallation); - else if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_2_0) + if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_2_0) return MonoInstallationFinder.GetProfileDirectory("2.0-api", MonoInstallationFinder.MonoBleedingEdgeInstallation); return MonoInstallationFinder.GetProfileDirectory(BuildPipeline.CompatibilityProfileToClassLibFolder(apiCompatibilityLevel), MonoInstallationFinder.MonoBleedingEdgeInstallation); } + public static string[] GetSystemReferenceDirectories(ApiCompatibilityLevel apiCompatibilityLevel) + { + if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard_2_0) + { + var systemReferenceDirectories = new List(); + systemReferenceDirectories.Add(NetStandardFinder.GetReferenceDirectory()); + systemReferenceDirectories.Add(NetStandardFinder.GetNetStandardCompatShimsDirectory()); + systemReferenceDirectories.Add(NetStandardFinder.GetNetStandardExtensionsDirectory()); + systemReferenceDirectories.Add(NetStandardFinder.GetDotNetFrameworkCompatShimsDirectory()); + return systemReferenceDirectories.ToArray(); + } + + if (apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6) + { + var systemReferenceDirectories = new List(); + var frameworkDirectory = GetSystemReference(apiCompatibilityLevel); + systemReferenceDirectories.Add(frameworkDirectory); + systemReferenceDirectories.Add(Path.Combine(frameworkDirectory, "Facades")); + return systemReferenceDirectories.ToArray(); + } + + return new[] { GetSystemReference(apiCompatibilityLevel) }; + } + static string[] GetNetStandardClassLibraries() { var classLibraries = new List(); @@ -125,7 +158,10 @@ static string[] GetNet46SystemReferences() return new[] { "System.Numerics.dll", - "System.Numerics.Vectors.dll" + "System.Numerics.Vectors.dll", + "System.Net.Http.dll", + "Microsoft.CSharp.dll", + "System.Data.dll", }; } diff --git a/Editor/Mono/Scripting/ScriptCompilation/OptionalUnityReferences.cs b/Editor/Mono/Scripting/ScriptCompilation/OptionalUnityReferences.cs deleted file mode 100644 index 951ecde961..0000000000 --- a/Editor/Mono/Scripting/ScriptCompilation/OptionalUnityReferences.cs +++ /dev/null @@ -1,16 +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.Scripting.ScriptCompilation -{ - // Keep in sync with OptionalUnityReferences in C++ - [Flags] - internal enum OptionalUnityReferences - { - None = 0, - TestAssemblies = 1 << 1, - } -} diff --git a/Editor/Mono/Scripting/ScriptCompilation/WSAHelpers.cs b/Editor/Mono/Scripting/ScriptCompilation/WSAHelpers.cs deleted file mode 100644 index e2d0b0fce5..0000000000 --- a/Editor/Mono/Scripting/ScriptCompilation/WSAHelpers.cs +++ /dev/null @@ -1,51 +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 UnityEditor.Modules; -using UnityEditor.Scripting.Compilers; - -namespace UnityEditor.Scripting.ScriptCompilation -{ - static class WSAHelpers - { - public static bool IsCSharpAssembly(ScriptAssembly scriptAssembly) - { - if (scriptAssembly.Filename.ToLower().Contains("firstpass")) - return false; - - return scriptAssembly.Language == ScriptCompilers.CSharpSupportedLanguage; - } - - public static bool IsCSharpFirstPassAssembly(ScriptAssembly scriptAssembly) - { - if (!scriptAssembly.Filename.ToLower().Contains("firstpass")) - return false; - - return scriptAssembly.Language == ScriptCompilers.CSharpSupportedLanguage; - } - - public static bool UseDotNetCore(ScriptAssembly scriptAssembly) - { - var metroCompilationOverrides = PlayerSettings.WSA.compilationOverrides; - bool dotNetCoreEnabled = scriptAssembly.BuildTarget == BuildTarget.WSAPlayer && metroCompilationOverrides != PlayerSettings.WSACompilationOverrides.None; - bool useDotNetCore = dotNetCoreEnabled && (IsCSharpAssembly(scriptAssembly) || (metroCompilationOverrides != PlayerSettings.WSACompilationOverrides.UseNetCorePartially && IsCSharpFirstPassAssembly(scriptAssembly))); - - return useDotNetCore; - } - - public static bool BuildingForDotNet(BuildTarget buildTarget, bool buildingForEditor, string assemblyName) - { - if (buildTarget != BuildTarget.WSAPlayer) - return false; - - if (CSharpLanguage.GetCSharpCompiler(buildTarget, buildingForEditor, assemblyName) != CSharpCompiler.Microsoft) - return false; - - if (PlayerSettings.GetScriptingBackend(BuildPipeline.GetBuildTargetGroup(buildTarget)) != ScriptingImplementation.WinRTDotNET) - return false; - - return true; - } - } -} diff --git a/Editor/Mono/Scripting/Serialization/Weaver.cs b/Editor/Mono/Scripting/Serialization/Weaver.cs deleted file mode 100644 index 80176b6584..0000000000 --- a/Editor/Mono/Scripting/Serialization/Weaver.cs +++ /dev/null @@ -1,84 +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.IO; -using System.Linq; -using System.Collections.Generic; -using Mono.Cecil; -using UnityEditor.Modules; -using UnityEngine; -using UnityEditor.Utils; -using UnityEditor.Scripting.ScriptCompilation; - -namespace UnityEditor.Scripting.Serialization -{ - internal static class Weaver - { - private static ManagedProgram SerializationWeaverProgramWith(string arguments, string playerPackage) - { - return ManagedProgramFor(playerPackage + "/SerializationWeaver/SerializationWeaver.exe", arguments); - } - - private static ManagedProgram ManagedProgramFor(string exe, string arguments) - { - return new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), null, exe, arguments, false, null); - } - - private static ICompilationExtension GetCompilationExtension() - { - var target = ModuleManager.GetTargetStringFromBuildTarget(EditorUserBuildSettings.activeBuildTarget); - return ModuleManager.GetCompilationExtension(target); - } - - private static void QueryAssemblyPathsAndResolver(ICompilationExtension compilationExtension, string file, bool editor, out string[] assemblyPaths, out IAssemblyResolver assemblyResolver) - { - assemblyResolver = compilationExtension.GetAssemblyResolver(editor, file, null); - assemblyPaths = compilationExtension.GetCompilerExtraAssemblyPaths(editor, file).ToArray(); - } - - public static bool WeaveUnetFromEditor(ScriptAssembly assembly, string assemblyDirectory, string outputDirectory, string unityEngine, string unityUNet, bool buildingForEditor) - { - if ((assembly.Flags & AssemblyFlags.EditorOnly) == AssemblyFlags.EditorOnly) - return true; - - var assemblyPath = Path.Combine(assemblyDirectory, assembly.Filename); - - ICompilationExtension compilationExtension = GetCompilationExtension(); - IAssemblyResolver assemblyResolver; - string[] assemblyPaths; - QueryAssemblyPathsAndResolver(compilationExtension, assemblyPath, buildingForEditor, out assemblyPaths, out assemblyResolver); - return WeaveInto(assembly, assemblyPath, outputDirectory, unityEngine, unityUNet, assemblyPaths, assemblyResolver); - } - - private static bool WeaveInto(ScriptAssembly assembly, string assemblyPath, string outputDirectory, string unityEngine, string unityUNet, string[] extraAssemblyPaths, IAssemblyResolver assemblyResolver) - { - var dependencies = assembly.GetAllReferences(); - var dependencyPaths = new string[dependencies.Count() + (extraAssemblyPaths != null ? extraAssemblyPaths.Length : 0)]; - - int i = 0; - - foreach (var dependency in dependencies) - dependencyPaths[i++] = Path.GetDirectoryName(dependency); - - if (extraAssemblyPaths != null) - extraAssemblyPaths.CopyTo(dependencyPaths, i); - - try - { - if (!Unity.UNetWeaver.Program.Process(unityEngine, unityUNet, outputDirectory, new[] { assemblyPath }, dependencyPaths, assemblyResolver, UnityEngine.Debug.LogWarning, UnityEngine.Debug.LogError)) - { - UnityEngine.Debug.LogError("Failure generating network code."); - return false; - } - } - catch (Exception ex) - { - UnityEngine.Debug.LogError("Exception generating network code: " + ex.ToString() + " " + ex.StackTrace); - } - return true; - } - - } -} diff --git a/Editor/Mono/Selection.bindings.cs b/Editor/Mono/Selection.bindings.cs deleted file mode 100644 index ef5daa3a2a..0000000000 --- a/Editor/Mono/Selection.bindings.cs +++ /dev/null @@ -1,129 +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.Bindings; - -namespace UnityEditor -{ - // SelectionMode can be used to tweak the selection returned by Selection.GetTransforms. - public enum SelectionMode - { - // Return the whole selection. - Unfiltered = 0, - // Only return the topmost selected transform. A selected child of another selected transform will be filtered out. - TopLevel = 1, - // Return the selection and all child transforms of the selection. - Deep = 2, - // Excludes any prefabs from the selection. - ExcludePrefab = 4, - // Excludes any objects which shall not be modified. - Editable = 8, - // Only return objects that are assets in the Asset directory. - Assets = 16, - // If the selection contains folders, also include all assets and subfolders within that folder in the file hierarchy. - DeepAssets = 32, - // Return a selection that only contains top level selection of all visible assets - //TopLevelAssets = 64, - // renamed to Editable - OnlyUserModifiable = 8 - } - - [NativeHeader("Editor/Src/Selection.bindings.h")] - [NativeHeader("Editor/Src/Gizmos/GizmoUtil.h")] - [NativeHeader("Editor/Src/Selection.h")] - [NativeHeader("Editor/Src/SceneInspector.h")] - public sealed partial class Selection - { - // Returns the top level selection, excluding prefabs. - public extern static Transform[] transforms - { - [NativeMethod("GetTransformSelection", true)] - get; - } - - // Returns the actual game object selection. Includes prefabs, non-modifyable objects. - public extern static Transform activeTransform - { - [NativeMethod("GetActiveTransform", true)] - get; - [NativeMethod("SetActiveObject", true)] - set; - } - - // Returns the actual game object selection. Includes prefabs, non-modifyable objects. - public extern static GameObject[] gameObjects - { - [NativeMethod("GetGameObjectSelection", true)] - get; - } - - // Returns the active game object. (The one shown in the inspector) - public extern static GameObject activeGameObject - { - [NativeMethod("GetActiveGO", true)] - get; - [NativeMethod("SetActiveObject", true)] - set; - } - - // Returns the actual object selection. Includes prefabs, non-modifyable objects. - extern public static Object activeObject - { - [NativeMethod("GetActiveObject", true)] - get; - [NativeMethod("SetActiveObject", true)] - set; - } - - // Returns the active context object - extern public static Object activeContext - { - [NativeMethod("GetActiveContext", true)] - get; - } - - // Returns the instanceID of the actual object selection. Includes prefabs, non-modifyable objects. - [StaticAccessor("Selection", StaticAccessorType.DoubleColon)] - [NativeName("ActiveID")] - extern public static int activeInstanceID { get; set; } - - // The actual unfiltered selection from the Scene. - [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] - extern public static Object[] objects { get; set; } - - // The actual unfiltered selection from the Scene returned as instance ids instead of ::ref::objects. - [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] - extern public static int[] instanceIDs { get; set; } - - [StaticAccessor("GetSceneTracker()", StaticAccessorType.Dot)] - [NativeMethod("IsSelected")] - extern public static bool Contains(int instanceID); - - [NativeMethod("SetActiveObjectWithContextInternal", true)] - extern public static void SetActiveObjectWithContext(Object obj, Object context); - - // Allows for fine grained control of the selection type using the [[SelectionMode]] bitmask. - [NativeMethod("GetTransformSelection", true)] - extern public static Transform[] GetTransforms(SelectionMode mode); - - //* undocumented - utility function - [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] - extern internal static Object[] GetObjectsMode(SelectionMode mode); - - [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] - extern internal static string[] assetGUIDsDeepSelection - { - [NativeMethod("GetSelectedAssetGUIDStringsDeep")] - get; - } - - [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] - extern public static string[] assetGUIDs - { - [NativeMethod("GetSelectedAssetGUIDStrings")] - get; - } - } -} diff --git a/Editor/Mono/Selection.cs b/Editor/Mono/Selection.cs deleted file mode 100644 index f72e882bee..0000000000 --- a/Editor/Mono/Selection.cs +++ /dev/null @@ -1,73 +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 System.Linq; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor -{ - public sealed partial class Selection - { - public static System.Action selectionChanged; - - private static void Internal_CallSelectionChanged() - { - if (selectionChanged != null) - selectionChanged(); - } - - public static bool Contains(Object obj) { return Contains(obj.GetInstanceID()); } - - internal static void Add(int instanceID) - { - var ids = new List(Selection.instanceIDs); - if (ids.IndexOf(instanceID) < 0) - { - ids.Add(instanceID); - Selection.instanceIDs = ids.ToArray(); - } - } - - internal static void Add(Object obj) - { - if (obj != null) - Add(obj.GetInstanceID()); - } - - internal static void Remove(int instanceID) - { - var ids = new List(Selection.instanceIDs); - ids.Remove(instanceID); - Selection.instanceIDs = ids.ToArray(); - } - - internal static void Remove(Object obj) - { - if (obj != null) - Remove(obj.GetInstanceID()); - } - - private static IEnumerable GetFilteredInternal(System.Type type, SelectionMode mode) - { - if (typeof(Component).IsAssignableFrom(type) || type.IsInterface) - return GetTransforms(mode).Select(t => t.GetComponent(type)).Where(c => c != null); - else if (typeof(GameObject).IsAssignableFrom(type)) - return GetTransforms(mode).Select(t => t.gameObject); - else - return GetObjectsMode(mode).Where(o => o != null && type.IsAssignableFrom(o.GetType())); - } - - public static T[] GetFiltered(SelectionMode mode) // no generic constraint because we also want to allow interfaces - { - return GetFilteredInternal(typeof(T), mode).Cast().ToArray(); - } - - public static Object[] GetFiltered(System.Type type, SelectionMode mode) - { - return GetFilteredInternal(type, mode).Cast().ToArray(); - } - } -} diff --git a/Editor/Mono/SerializedProperty/SerializedPropertyFilters.cs b/Editor/Mono/SerializedProperty/SerializedPropertyFilters.cs deleted file mode 100644 index 6e82b7ae85..0000000000 --- a/Editor/Mono/SerializedProperty/SerializedPropertyFilters.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 UnityEngine; - -namespace UnityEditor -{ - internal class SerializedPropertyFilters - { - internal interface IFilter - { - bool Active(); // returns true if filter is active, false otherwise - bool Filter(SerializedProperty prop); // returns true if filtering passes - void OnGUI(Rect r); // draws the filter control - string SerializeState(); // returns null if there's nothing to serialize - void DeserializeState(string state); // state must not be null - } - - internal abstract class SerializableFilter : IFilter - { - public abstract bool Active(); // returns true if filter is active, false otherwise - public abstract bool Filter(SerializedProperty prop); // returns true if filtering passes - public abstract void OnGUI(Rect r); // draws the filter control - public string SerializeState() { return JsonUtility.ToJson(this); } - public void DeserializeState(string state) { JsonUtility.FromJsonOverwrite(state, this); } - }; - - - internal class String : SerializableFilter - { - static class Styles - { - public static readonly GUIStyle searchField = "SearchTextField"; - public static readonly GUIStyle searchFieldCancelButton = "SearchCancelButton"; - public static readonly GUIStyle searchFieldCancelButtonEmpty = "SearchCancelButtonEmpty"; - } - - [SerializeField] protected string m_Text = ""; - public override bool Active() { return !string.IsNullOrEmpty(m_Text); } - public override bool Filter(SerializedProperty prop) { return prop.stringValue.IndexOf(m_Text, 0, System.StringComparison.OrdinalIgnoreCase) >= 0; } - public override void OnGUI(Rect r) - { - r.width -= 15; - m_Text = EditorGUI.TextField(r, GUIContent.none, m_Text, Styles.searchField); - - // draw the cancel button - r.x += r.width; - r.width = 15; - bool notEmpty = m_Text != ""; - if (GUI.Button(r, GUIContent.none, notEmpty ? Styles.searchFieldCancelButton : Styles.searchFieldCancelButtonEmpty) && notEmpty) - { - m_Text = ""; - GUIUtility.keyboardControl = 0; - } - } - } - - internal sealed class Name : String - { - public bool Filter(string str) { return str.IndexOf(m_Text, 0, System.StringComparison.OrdinalIgnoreCase) >= 0; } - } - - internal sealed class None : IFilter - { - public bool Active() { return false; } - public bool Filter(SerializedProperty prop) { return true; } - public void OnGUI(Rect r) {} - public string SerializeState() { return null; } - public void DeserializeState(string state) {} - } - internal static readonly None s_FilterNone = new None(); - } -} diff --git a/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs b/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs index c00bc409b7..c1c276d9e1 100644 --- a/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs +++ b/Editor/Mono/Settings/Providers/AssetSettingsProvider.cs @@ -8,6 +8,7 @@ using UnityEngine.Experimental.UIElements; using UnityEngine.Internal; using UnityEditor.StyleSheets; +using UnityEditorInternal; namespace UnityEditor { @@ -68,9 +69,20 @@ public override void OnDeactivate() public override void OnGUI(string searchContext) { if (m_SettingsEditor != null) + { using (new SettingsWindow.GUIScope()) m_SettingsEditor.OnInspectorGUI(); + // Emulate the Inspector by handling DnD at the native level. + var remainingRect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandHeight(true)); + if ((Event.current.type == EventType.DragUpdated || Event.current.type == EventType.DragPerform) && remainingRect.Contains(Event.current.mousePosition)) + { + DragAndDrop.visualMode = InternalEditorUtility.InspectorWindowDrag(new[] { m_SettingsEditor.target }, Event.current.type == EventType.DragPerform); + if (Event.current.type == EventType.DragPerform) + DragAndDrop.AcceptDrag(); + } + } + base.OnGUI(searchContext); } @@ -90,5 +102,11 @@ public override void OnTitleBarGUI() } } } + + public override void OnFooterBarGUI() + { + if (m_SettingsEditor != null) + InspectorWindow.DrawVCSShortInfo(settingsWindow, m_SettingsEditor); + } } } diff --git a/Editor/Mono/Settings/SettingsProvider.cs b/Editor/Mono/Settings/SettingsProvider.cs index 622bdcdb43..c41f58ca89 100644 --- a/Editor/Mono/Settings/SettingsProvider.cs +++ b/Editor/Mono/Settings/SettingsProvider.cs @@ -69,6 +69,7 @@ public string label public Action guiHandler { get; set; } public Action titleBarGuiHandler { get; set; } + public Action footerBarGuiHandler { get; set; } public Action activateHandler { get; set; } public Action deactivateHandler { get; set; } public Func hasSearchInterestHandler { get; set; } @@ -119,6 +120,11 @@ public virtual void OnTitleBarGUI() titleBarGuiHandler?.Invoke(); } + public virtual void OnFooterBarGUI() + { + footerBarGuiHandler?.Invoke(); + } + public void PopulateSearchKeywordsFromGUIContentProperties() { GetSearchKeywordsFromGUIContentProperties(keywords); diff --git a/Editor/Mono/Settings/SettingsService.cs b/Editor/Mono/Settings/SettingsService.cs index 61c625bdeb..8ca28cfcb2 100644 --- a/Editor/Mono/Settings/SettingsService.cs +++ b/Editor/Mono/Settings/SettingsService.cs @@ -6,14 +6,23 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using System.Text; using UnityEngine; using UnityEngine.Internal; namespace UnityEditor { [ExcludeFromDocs] + [InitializeOnLoad] public class SettingsService { + const string k_ProjectSettings = "Edit/Project Settings"; + static SettingsService() + { + EditorApplication.update -= CheckProjectSettings; + EditorApplication.update += CheckProjectSettings; + } + public static event Action settingsProviderChanged; public static SettingsProvider[] FetchSettingsProviders() @@ -31,6 +40,22 @@ public static void NotifySettingsProviderChanged() settingsProviderChanged?.Invoke(); } + private static void CheckProjectSettings() + { + EditorApplication.update -= CheckProjectSettings; + + var deprecatedMenuItems = Menu.ExtractSubmenus(k_ProjectSettings); + if (deprecatedMenuItems.Length > 0) + { + var sb = new StringBuilder(); + sb.Append("There are menu items registered under Edit/Project Settings: "); + sb.Append(string.Join(", ", deprecatedMenuItems.Select(item => item.Replace(k_ProjectSettings + "/", "")).ToArray())); + sb.Append("\n"); + sb.AppendLine("Consider using [SettingsProvider] attribute to register in the Unified Settings Window."); + Debug.LogWarning(sb); + } + } + private static IEnumerable FetchPreferenceItems() { var methods = AttributeHelper.GetMethodsWithAttribute(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); @@ -39,8 +64,8 @@ private static IEnumerable FetchPreferenceItems() var callback = Delegate.CreateDelegate(typeof(Action), method.info) as Action; if (callback != null) { - Debug.LogWarning("PreferenceItem is deprecated. Use [SettingsProvider] instead"); var attributeName = (method.attribute as PreferenceItem).name; + Debug.LogWarning($"Trying to register preference item: \"{attributeName}\". [PreferenceItem] attribute is deprecated. Use [SettingsProvider] attribute instead."); return new SettingsProvider("Preferences/" + attributeName) { guiHandler = searchContext => callback(), scopes = SettingsScopes.User }; } diff --git a/Editor/Mono/Settings/SettingsWindow.cs b/Editor/Mono/Settings/SettingsWindow.cs index e69757227e..cf6b61a8ba 100644 --- a/Editor/Mono/Settings/SettingsWindow.cs +++ b/Editor/Mono/Settings/SettingsWindow.cs @@ -275,19 +275,22 @@ private void DrawToolbar() private void DrawSettingsPanel() { + if (m_TreeView.currentProvider == null) + return; + + DrawTitleBar(); + using (var scrollViewScope = new EditorGUILayout.ScrollViewScope(m_PosRight, GUILayout.ExpandWidth(true))) { m_PosRight = scrollViewScope.scrollPosition; DrawControls(); } + + DrawFooterBar(); } private void DrawControls() { - if (m_TreeView.currentProvider == null) - return; - - DrawTitleBar(); using (new EditorGUI.LabelHighlightScope(m_SearchText, Styles.settingsPanel.GetColor("-unity-search-highlight-selection-color"), Styles.settingsPanel.GetColor("-unity-search-highlight-color"))) m_TreeView.currentProvider.OnGUI(m_SearchText); } @@ -303,6 +306,11 @@ private void DrawTitleBar() GUILayout.EndHorizontal(); } + private void DrawFooterBar() + { + m_TreeView.currentProvider.OnFooterBarGUI(); + } + private void DrawTreeView() { var splitterRect = m_Splitter.GetSplitterRect(m_Splitter.Children().First()); diff --git a/Editor/Mono/SettingsWindow/FogEditor.cs b/Editor/Mono/SettingsWindow/FogEditor.cs deleted file mode 100644 index 34e8ac7a75..0000000000 --- a/Editor/Mono/SettingsWindow/FogEditor.cs +++ /dev/null @@ -1,73 +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; - -namespace UnityEditor -{ - [CustomEditor(typeof(RenderSettings))] - internal class FogEditor : Editor - { - internal class Styles - { - public static readonly GUIContent FogWarning = EditorGUIUtility.TrTextContent("Fog has no effect on opaque objects when using Deferred Shading rendering. Use the Global Fog image effect instead, which supports opaque objects."); - public static readonly GUIContent FogDensity = EditorGUIUtility.TrTextContent("Density", "Controls the density of the fog effect in the Scene when using Exponential or Exponential Squared modes."); - public static readonly GUIContent FogLinearStart = EditorGUIUtility.TrTextContent("Start", "Controls the distance from the camera where the fog will start in the Scene."); - public static readonly GUIContent FogLinearEnd = EditorGUIUtility.TrTextContent("End", "Controls the distance from the camera where the fog will completely obscure objects in the Scene."); - public static readonly GUIContent FogEnable = EditorGUIUtility.TrTextContent("Fog", "Specifies whether fog is used in the Scene or not."); - public static readonly GUIContent FogColor = EditorGUIUtility.TrTextContent("Color", "Controls the color of that fog drawn in the Scene."); - public static readonly GUIContent FogMode = EditorGUIUtility.TrTextContent("Mode", "Controls the mathematical function determining the way fog accumulates with distance from the camera. Options are Linear, Exponential, and Exponential Squared."); - } - - protected SerializedProperty m_Fog; - protected SerializedProperty m_FogColor; - protected SerializedProperty m_FogMode; - protected SerializedProperty m_FogDensity; - protected SerializedProperty m_LinearFogStart; - protected SerializedProperty m_LinearFogEnd; - - public virtual void OnEnable() - { - m_Fog = serializedObject.FindProperty("m_Fog"); - m_FogColor = serializedObject.FindProperty("m_FogColor"); - m_FogMode = serializedObject.FindProperty("m_FogMode"); - m_FogDensity = serializedObject.FindProperty("m_FogDensity"); - m_LinearFogStart = serializedObject.FindProperty("m_LinearFogStart"); - m_LinearFogEnd = serializedObject.FindProperty("m_LinearFogEnd"); - } - - public virtual void OnDisable() {} - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_Fog, Styles.FogEnable); - if (m_Fog.boolValue) - { - EditorGUI.indentLevel++; - EditorGUILayout.PropertyField(m_FogColor, Styles.FogColor); - EditorGUILayout.PropertyField(m_FogMode, Styles.FogMode); - - if ((FogMode)m_FogMode.intValue != FogMode.Linear) - { - EditorGUILayout.PropertyField(m_FogDensity, Styles.FogDensity); - } - else - { - EditorGUILayout.PropertyField(m_LinearFogStart, Styles.FogLinearStart); - EditorGUILayout.PropertyField(m_LinearFogEnd, Styles.FogLinearEnd); - } - - if (SceneView.IsUsingDeferredRenderingPath()) - EditorGUILayout.HelpBox(Styles.FogWarning.text, MessageType.Info); - - EditorGUI.indentLevel--; - EditorGUILayout.Space(); - } - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/SettingsWindow/OtherRenderingEditor.cs b/Editor/Mono/SettingsWindow/OtherRenderingEditor.cs deleted file mode 100644 index b4f07afc1d..0000000000 --- a/Editor/Mono/SettingsWindow/OtherRenderingEditor.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; - -namespace UnityEditor -{ - [CustomEditor(typeof(RenderSettings))] - internal class OtherRenderingEditor : Editor - { - internal static class Styles - { - public static readonly GUIContent HaloStrength = EditorGUIUtility.TrTextContent("Halo Strength", "Controls the visibility of the halo effect around lights in the Scene."); - public static readonly GUIContent HaloTexture = EditorGUIUtility.TrTextContent("Halo Texture", "Specifies the Texture used when drawing the halo effect around lights in the Scene"); - public static readonly GUIContent FlareStrength = EditorGUIUtility.TrTextContent("Flare Strength", "Controls the visibility of lens flares from lights in the Scene."); - public static readonly GUIContent FlareFadeSpeed = EditorGUIUtility.TrTextContent("Flare Fade Speed", "Controls the time over which lens flares fade from view after initially appearing."); - public static readonly GUIContent SpotCookie = EditorGUIUtility.TrTextContent("Spot Cookie", "Specifies the Texture mask used to cast shadows, create silhouettes, or patterned illumination when using spot lights."); - } - - protected SerializedProperty m_HaloStrength; - protected SerializedProperty m_FlareStrength; - protected SerializedProperty m_FlareFadeSpeed; - protected SerializedProperty m_HaloTexture; - protected SerializedProperty m_SpotCookie; - - public virtual void OnEnable() - { - m_HaloStrength = serializedObject.FindProperty("m_HaloStrength"); - m_FlareStrength = serializedObject.FindProperty("m_FlareStrength"); - m_FlareFadeSpeed = serializedObject.FindProperty("m_FlareFadeSpeed"); - m_HaloTexture = serializedObject.FindProperty("m_HaloTexture"); - m_SpotCookie = serializedObject.FindProperty("m_SpotCookie"); - } - - public virtual void OnDisable() {} - - public override void OnInspectorGUI() - { - serializedObject.Update(); - - EditorGUILayout.PropertyField(m_HaloTexture, Styles.HaloTexture); - EditorGUILayout.Slider(m_HaloStrength, 0.0f, 1.0f, Styles.HaloStrength); - - EditorGUILayout.PropertyField(m_FlareFadeSpeed, Styles.FlareFadeSpeed); - EditorGUILayout.Slider(m_FlareStrength, 0.0f, 1.0f, Styles.FlareStrength); - - EditorGUILayout.PropertyField(m_SpotCookie, Styles.SpotCookie); - - serializedObject.ApplyModifiedProperties(); - } - } -} diff --git a/Editor/Mono/ShapeEditor/ShapeEditorRectSelection.cs b/Editor/Mono/ShapeEditor/ShapeEditorRectSelection.cs deleted file mode 100644 index 7861a37133..0000000000 --- a/Editor/Mono/ShapeEditor/ShapeEditorRectSelection.cs +++ /dev/null @@ -1,232 +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 UnityEngine; -using SelectionType = UnityEditor.ShapeEditor.SelectionType; - -namespace UnityEditor -{ - internal class ShapeEditorRectSelectionTool - { - Vector2 m_SelectStartPoint; - Vector2 m_SelectMousePoint; - bool m_RectSelecting; - int m_RectSelectionID; - const float k_MinSelectionSize = 6f; - - public event Action RectSelect = (i, p) => {}; - public event Action ClearSelection = () => {}; - - public ShapeEditorRectSelectionTool(IGUIUtility gu) - { - guiUtility = gu; - m_RectSelectionID = guiUtility.GetPermanentControlID(); - } - - public void OnGUI() - { - Event evt = Event.current; - - Handles.BeginGUI(); - - Vector2 mousePos = evt.mousePosition; - int id = m_RectSelectionID; - - switch (evt.GetTypeForControl(id)) - { - case EventType.Layout: - if (!Tools.viewToolActive) - HandleUtility.AddDefaultControl(id); - break; - - case EventType.MouseDown: - if (HandleUtility.nearestControl == id && evt.button == 0) - { - guiUtility.hotControl = id; - m_SelectStartPoint = mousePos; - } - break; - case EventType.MouseDrag: - if (guiUtility.hotControl == id) - { - if (!m_RectSelecting && (mousePos - m_SelectStartPoint).magnitude > k_MinSelectionSize) - { - m_RectSelecting = true; - } - if (m_RectSelecting) - { - m_SelectMousePoint = mousePos; - - SelectionType type = SelectionType.Normal; - if (Event.current.control) - type = SelectionType.Subtractive; - else if (Event.current.shift) - type = SelectionType.Additive; - RectSelect(EditorGUIExt.FromToRect(m_SelectStartPoint, m_SelectMousePoint), type); - } - evt.Use(); - } - break; - - case EventType.Repaint: - if (guiUtility.hotControl == id && m_RectSelecting) - { - EditorStyles.selectionRect.Draw(EditorGUIExt.FromToRect(m_SelectStartPoint, m_SelectMousePoint), GUIContent.none, - false, false, false, false); - } - break; - - case EventType.MouseUp: - if (guiUtility.hotControl == id && evt.button == 0) - { - guiUtility.hotControl = 0; - guiUtility.keyboardControl = 0; - if (m_RectSelecting) - { - m_SelectMousePoint = new Vector2(mousePos.x, mousePos.y); - - SelectionType type = SelectionType.Normal; - if (Event.current.control) - type = SelectionType.Subtractive; - else if (Event.current.shift) - type = SelectionType.Additive; - - RectSelect(EditorGUIExt.FromToRect(m_SelectStartPoint, m_SelectMousePoint), type); - - m_RectSelecting = false; - } - else - { - ClearSelection(); - } - evt.Use(); - } - break; - } - - Handles.EndGUI(); - } - - public bool isSelecting - { - get { return guiUtility.hotControl == m_RectSelectionID; } - } - - IGUIUtility guiUtility - { - get; set; - } - } - - // TODO: For now we copy-paste from RectSelection. Refactor to avoid duplicate codes. - internal class ShapeEditorSelection : IEnumerable - { - HashSet m_SelectedPoints = new HashSet(); - ShapeEditor m_ShapeEditor; - - public ShapeEditorSelection(ShapeEditor owner) - { - m_ShapeEditor = owner; - } - - public bool Contains(int i) - { - return m_SelectedPoints.Contains(i); - } - - public int Count - { - get { return m_SelectedPoints.Count; } - } - - public void DeleteSelection() - { - var sorted = m_SelectedPoints.OrderByDescending(x => x); - foreach (int selectedIndex in sorted) - { - m_ShapeEditor.RemovePointAt(selectedIndex); - } - if (m_ShapeEditor.activePoint >= m_ShapeEditor.GetPointsCount()) - m_ShapeEditor.activePoint = m_ShapeEditor.GetPointsCount() - 1; - m_SelectedPoints.Clear(); - } - - public void MoveSelection(Vector3 delta) - { - if (delta.sqrMagnitude < float.Epsilon) - return; - - foreach (int selectedIndex in m_SelectedPoints) - { - m_ShapeEditor.SetPointPosition(selectedIndex, m_ShapeEditor.GetPointPosition(selectedIndex) + delta); - } - } - - public void Clear() - { - m_SelectedPoints.Clear(); - if (m_ShapeEditor != null) - m_ShapeEditor.activePoint = -1; - } - - public void SelectPoint(int i, SelectionType type) - { - switch (type) - { - case SelectionType.Additive: - m_ShapeEditor.activePoint = i; - m_SelectedPoints.Add(i); - break; - case SelectionType.Subtractive: - m_ShapeEditor.activePoint = i > 0 ? i - 1 : 0; - m_SelectedPoints.Remove(i); - break; - case SelectionType.Normal: - m_SelectedPoints.Clear(); - m_ShapeEditor.activePoint = i; - m_SelectedPoints.Add(i); - break; - default: - m_ShapeEditor.activePoint = i; break; - } - m_ShapeEditor.Repaint(); - } - - public void RectSelect(Rect rect, SelectionType type) - { - if (type == SelectionType.Normal) - { - m_SelectedPoints.Clear(); - m_ShapeEditor.activePoint = -1; - type = SelectionType.Additive; - } - - for (int i = 0; i < m_ShapeEditor.GetPointsCount(); i++) - { - var p0 = m_ShapeEditor.GetPointPosition(i); - if (rect.Contains(p0)) - { - SelectPoint(i, type); - } - } - m_ShapeEditor.Repaint(); - } - - public HashSet indices { get { return m_SelectedPoints; } } - - public IEnumerator GetEnumerator() - { - return m_SelectedPoints.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} // namespace diff --git a/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs b/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs index e62e1ea2e5..d507ba77b3 100644 --- a/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs +++ b/Editor/Mono/SpriteEditor/SpriteEditorWindow.cs @@ -103,8 +103,8 @@ private void OnFocus() public void RefreshPropertiesCache() { - m_SpriteDataProvider = AssetImporter.GetAtPath(m_SelectedAssetPath) as ISpriteEditorDataProvider; - if (m_SpriteDataProvider == null) + m_SpriteDataProvider = AssetImporter.GetAtPath(m_SelectedAssetPath) as ISpriteEditorDataProvider; + if (!IsSpriteDataProviderValid()) { m_SelectedAssetPath = ""; return; @@ -156,7 +156,7 @@ private Rect warningMessageRect public SpriteImportMode spriteImportMode { - get { return m_SpriteDataProvider == null ? SpriteImportMode.None : m_SpriteDataProvider.spriteImportMode; } + get { return !IsSpriteDataProviderValid() ? SpriteImportMode.None : m_SpriteDataProvider.spriteImportMode; } } bool activeDataProviderSelected @@ -352,7 +352,7 @@ void OnEditorApplicationQuit() void HandleApplyRevertDialog(string dialogTitle, string dialogContent) { - if (textureIsDirty && m_SpriteDataProvider != null) + if (textureIsDirty && IsSpriteDataProviderValid()) { if (EditorUtility.DisplayDialog(dialogTitle, dialogContent, SpriteEditorWindowStyles.applyButtonLabel.text, SpriteEditorWindowStyles.revertButtonLabel.text)) @@ -364,10 +364,15 @@ void HandleApplyRevertDialog(string dialogTitle, string dialogContent) } } + bool IsSpriteDataProviderValid() + { + return m_SpriteDataProvider != null && !m_SpriteDataProvider.Equals(null); + } + void RefreshRects() { m_RectsCache = null; - if (m_SpriteDataProvider != null) + if (IsSpriteDataProviderValid()) { m_RectsCache = m_SpriteDataProvider.GetSpriteRects().ToList(); } @@ -379,7 +384,7 @@ private void Update() { if (m_ResetOnNextRepaint || selectedProviderChanged) { - if (selectedProviderChanged || m_SpriteDataProvider == null) + if (selectedProviderChanged || !IsSpriteDataProviderValid()) m_SelectedAssetPath = GetSelectionAssetPath(); RebuildCache(); } @@ -393,7 +398,6 @@ private void RebuildCache() RefreshPropertiesCache(); RefreshRects(); UpdateAvailableModules(); - SetupModule(m_CurrentModuleIndex); } private void DoTextureAndModulesGUI() @@ -735,7 +739,7 @@ void UpdateAvailableModules() } m_RegisteredModuleNames = new GUIContent[m_RegisteredModules.Count]; - int lastUsedModuleIndex = -1; + int lastUsedModuleIndex = 0; for (int i = 0; i < m_RegisteredModules.Count; i++) { m_RegisteredModuleNames[i] = new GUIContent(m_RegisteredModules[i].moduleName); @@ -745,10 +749,7 @@ void UpdateAvailableModules() } } - if (lastUsedModuleIndex >= 0) - SetupModule(lastUsedModuleIndex); - else - SetupModule(0); + SetupModule(lastUsedModuleIndex); } void InitModules() diff --git a/Editor/Mono/SpriteEditor/SpriteRect.cs b/Editor/Mono/SpriteEditor/SpriteRect.cs deleted file mode 100644 index c494ea2a0c..0000000000 --- a/Editor/Mono/SpriteEditor/SpriteRect.cs +++ /dev/null @@ -1,174 +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 System.Collections.Generic; -using System.Collections; -using UnityEditor.Experimental.U2D; -using UnityEditorInternal; - -namespace UnityEditor -{ - [Serializable] - public class SpriteRect - { - [SerializeField] - string m_Name; - - [SerializeField] - string m_OriginalName; - - [SerializeField] - Vector2 m_Pivot; - - [SerializeField] - SpriteAlignment m_Alignment; - - [SerializeField] - Vector4 m_Border; - - [SerializeField] - Rect m_Rect; - - [SerializeField] - string m_SpriteID; - - GUID m_GUID; - - public string name - { - get { return m_Name; } - set { m_Name = value; } - } - - public Vector2 pivot - { - get { return m_Pivot; } - set { m_Pivot = value; } - } - - public SpriteAlignment alignment - { - get { return m_Alignment; } - set { m_Alignment = value; } - } - - public Vector4 border - { - get { return m_Border; } - set { m_Border = value; } - } - - public Rect rect - { - get { return m_Rect; } - set { m_Rect = value; } - } - - internal string originalName - { - get - { - if (m_OriginalName == null) - { - m_OriginalName = name; - } - return m_OriginalName; - } - - set { m_OriginalName = value; } - } - - public GUID spriteID - { - get - { - ValidateGUID(); - return m_GUID; - } - set - { - m_GUID = value; - m_SpriteID = m_GUID.ToString(); - ValidateGUID(); - } - } - - private void ValidateGUID() - { - if (m_GUID.Empty()) - { - // We can't use ISerializationCallbackReceiver because we will hit into Script serialization errors - m_GUID = new GUID(m_SpriteID); - if (m_GUID.Empty()) - { - m_GUID = GUID.Generate(); - m_SpriteID = m_GUID.ToString(); - } - } - } - - public static GUID GetSpriteIDFromSerializedProperty(SerializedProperty sp) - { - return new GUID(sp.FindPropertyRelative("m_SpriteID").stringValue); - } - } - - internal class SpriteRectCache : ScriptableObject - { - [SerializeField] - public List m_Rects; - - public int Count - { - get { return m_Rects != null ? m_Rects.Count : 0; } - } - - public SpriteRect RectAt(int i) - { - return i >= Count || i < 0 ? null : m_Rects[i]; - } - - public void AddRect(SpriteRect r) - { - if (m_Rects != null) - m_Rects.Add(r); - } - - public void RemoveRect(SpriteRect r) - { - if (m_Rects != null) - m_Rects.RemoveAll(x => x.spriteID == r.spriteID); - } - - public void ClearAll() - { - if (m_Rects != null) - m_Rects.Clear(); - } - - public int GetIndex(SpriteRect spriteRect) - { - if (m_Rects != null && spriteRect != null) - return m_Rects.FindIndex(p => p.spriteID == spriteRect.spriteID); - - return -1; - } - - public bool Contains(SpriteRect spriteRect) - { - if (m_Rects != null && spriteRect != null) - return m_Rects.Find(x => x.spriteID == spriteRect.spriteID) != null; - - return false; - } - - void OnEnable() - { - if (m_Rects == null) - m_Rects = new List(); - } - } -} diff --git a/Editor/Mono/SpritePacker.bindings.cs b/Editor/Mono/SpritePacker.bindings.cs deleted file mode 100644 index 2840cb9a03..0000000000 --- a/Editor/Mono/SpritePacker.bindings.cs +++ /dev/null @@ -1,93 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using UnityEditor; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor.Sprites -{ - [StructLayout(LayoutKind.Sequential)] - public struct AtlasSettings - { - public TextureFormat format; - public ColorSpace colorSpace; - public int compressionQuality; - public FilterMode filterMode; - public int maxWidth; - public int maxHeight; - public uint paddingPower; - public int anisoLevel; - public bool generateMipMaps; - public bool enableRotation; - public bool allowsAlphaSplitting; - } - - [NativeHeader("Editor/Src/SpritePacker/SpritePacker.h")] - public sealed class PackerJob - { - internal PackerJob() - { - } - - [FreeFunction("SpritePacker::ActiveJob_AddAtlas")] - private static extern void Internal_AddAtlas(string atlasName, AtlasSettings settings); - [FreeFunction("SpritePacker::ActiveJob_AssignToAtlas")] - private static extern void Internal_AssignToAtlas(string atlasName, Sprite sprite, SpritePackingMode packingMode, SpritePackingRotation packingRotation); - - public void AddAtlas(string atlasName, AtlasSettings settings) - { - Internal_AddAtlas(atlasName, settings); - } - - public void AssignToAtlas(string atlasName, Sprite sprite, SpritePackingMode packingMode, SpritePackingRotation packingRotation) - { - Internal_AssignToAtlas(atlasName, sprite, packingMode, packingRotation); - } - } - - [NativeHeader("Editor/Src/SpritePacker/SpritePacker.h")] - public sealed partial class Packer - { - public extern static string[] atlasNames - { - [FreeFunction("SpritePacker::GetAvailableAtlases")] - get; - } - - [FreeFunction("SpritePacker::GetAtlasNameForSprite")] - private static extern string Internal_GetAtlasNameForSprite(Sprite sprite); - [FreeFunction("SpritePacker::GetAtlasTextureSprite")] - private static extern Texture2D Internal_GetAtlasTextureSprite(Sprite sprite); - - [FreeFunction("SpritePacker::GetTexturesForAtlas")] - public static extern Texture2D[] GetTexturesForAtlas(string atlasName); - [FreeFunction("SpritePacker::GetAlphaTexturesForAtlas")] - public static extern Texture2D[] GetAlphaTexturesForAtlas(string atlasName); - [FreeFunction("SpritePacker::RebuildAtlasCacheIfNeededFromScript")] - public static extern void RebuildAtlasCacheIfNeeded(BuildTarget target, bool displayProgressBar, Execution execution); - - public static void RebuildAtlasCacheIfNeeded(BuildTarget target, bool displayProgressBar) - { - RebuildAtlasCacheIfNeeded(target, displayProgressBar, Execution.Normal); - } - - public static void RebuildAtlasCacheIfNeeded(BuildTarget target) - { - RebuildAtlasCacheIfNeeded(target, false, Execution.Normal); - } - - public static void GetAtlasDataForSprite(Sprite sprite, out string atlasName, out Texture2D atlasTexture) - { - atlasName = Internal_GetAtlasNameForSprite(sprite); - atlasTexture = Internal_GetAtlasTextureSprite(sprite); - } - } -} diff --git a/Editor/Mono/Sprites/DefaultSpritePackerPolicy.cs b/Editor/Mono/Sprites/DefaultSpritePackerPolicy.cs deleted file mode 100644 index 49e0708dad..0000000000 --- a/Editor/Mono/Sprites/DefaultSpritePackerPolicy.cs +++ /dev/null @@ -1,152 +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 UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor.Sprites -{ - // DefaultPackerPolicy will pack rectangles no matter what Sprite mesh type is unless their packing tag contains "[TIGHT]". - internal class DefaultPackerPolicy : IPackerPolicy - { - protected class Entry - { - public Sprite sprite; - public AtlasSettings settings; - public string atlasName; - public SpritePackingMode packingMode; - public int anisoLevel; - } - - private const uint kDefaultPaddingPower = 3; // Good for base and two mip levels. - - public virtual int GetVersion() { return 1; } - public virtual bool AllowSequentialPacking { get { return false; } } - - protected virtual string TagPrefix { get { return "[TIGHT]"; } } - protected virtual bool AllowTightWhenTagged { get { return true; } } - protected virtual bool AllowRotationFlipping { get { return false; } } - - public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) - { - List entries = new List(); - - string targetName = ""; - if (target != BuildTarget.NoTarget) - { - targetName = BuildPipeline.GetBuildTargetName(target); - } - - foreach (int instanceID in textureImporterInstanceIDs) - { - TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; - - TextureFormat desiredFormat; - ColorSpace colorSpace; - int compressionQuality; - ti.ReadTextureImportInstructions(target, out desiredFormat, out colorSpace, out compressionQuality); - - TextureImporterSettings tis = new TextureImporterSettings(); - ti.ReadTextureSettings(tis); - - bool hasAlphaSplittingForCompression = (targetName != "" && HasPlatformEnabledAlphaSplittingForCompression(targetName, ti)); - - Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray(); - foreach (Sprite sprite in sprites) - { - Entry entry = new Entry(); - entry.sprite = sprite; - entry.settings.format = desiredFormat; - entry.settings.colorSpace = colorSpace; - // Use Compression Quality for Grouping later only for Compressed Formats. Otherwise leave it Empty. - entry.settings.compressionQuality = UnityEditor.TextureUtil.IsCompressedTextureFormat(desiredFormat) ? compressionQuality : 0; - entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear; - entry.settings.maxWidth = 2048; - entry.settings.maxHeight = 2048; - entry.settings.generateMipMaps = ti.mipmapEnabled; - entry.settings.enableRotation = AllowRotationFlipping; - entry.settings.allowsAlphaSplitting = TextureImporter.IsTextureFormatETC1Compression(desiredFormat) && hasAlphaSplittingForCompression; - if (ti.mipmapEnabled) - entry.settings.paddingPower = kDefaultPaddingPower; - else - entry.settings.paddingPower = (uint)EditorSettings.spritePackerPaddingPower; - entry.atlasName = ParseAtlasName(ti.spritePackingTag); - entry.packingMode = GetPackingMode(ti.spritePackingTag, tis.spriteMeshType); - entry.anisoLevel = ti.anisoLevel; - - entries.Add(entry); - } - - Resources.UnloadAsset(ti); - } - - // First split sprites into groups based on atlas name - var atlasGroups = - from e in entries - group e by e.atlasName; - foreach (var atlasGroup in atlasGroups) - { - int page = 0; - // Then split those groups into smaller groups based on texture settings - var settingsGroups = - from t in atlasGroup - group t by t.settings; - foreach (var settingsGroup in settingsGroups) - { - string atlasName = atlasGroup.Key; - if (settingsGroups.Count() > 1) - atlasName += string.Format(" (Group {0})", page); - - AtlasSettings settings = settingsGroup.Key; - settings.anisoLevel = 1; - // Use the highest aniso level from all entries in this atlas - if (settings.generateMipMaps) - foreach (Entry entry in settingsGroup) - if (entry.anisoLevel > settings.anisoLevel) - settings.anisoLevel = entry.anisoLevel; - - job.AddAtlas(atlasName, settings); - foreach (Entry entry in settingsGroup) - { - job.AssignToAtlas(atlasName, entry.sprite, entry.packingMode, SpritePackingRotation.None); - } - - ++page; - } - } - } - - protected bool HasPlatformEnabledAlphaSplittingForCompression(string targetName, TextureImporter ti) - { - TextureImporterPlatformSettings platformSettings = ti.GetPlatformTextureSettings(targetName); - return (platformSettings.overridden && platformSettings.allowsAlphaSplitting); - } - - protected bool IsTagPrefixed(string packingTag) - { - packingTag = packingTag.Trim(); - if (packingTag.Length < TagPrefix.Length) - return false; - return (packingTag.Substring(0, TagPrefix.Length) == TagPrefix); - } - - private string ParseAtlasName(string packingTag) - { - string name = packingTag.Trim(); - if (IsTagPrefixed(name)) - name = name.Substring(TagPrefix.Length).Trim(); - return (name.Length == 0) ? "(unnamed)" : name; - } - - private SpritePackingMode GetPackingMode(string packingTag, SpriteMeshType meshType) - { - if (meshType == SpriteMeshType.Tight) - if (IsTagPrefixed(packingTag) == AllowTightWhenTagged) - return SpritePackingMode.Tight; - return SpritePackingMode.Rectangle; - } - } -} diff --git a/Editor/Mono/Sprites/SpritePacker.cs b/Editor/Mono/Sprites/SpritePacker.cs deleted file mode 100644 index 12130789bb..0000000000 --- a/Editor/Mono/Sprites/SpritePacker.cs +++ /dev/null @@ -1,162 +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 UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor.Sprites -{ - public sealed partial class Packer - { - public enum Execution - { - Normal = 0, - ForceRegroup - } - - public static string kDefaultPolicy = typeof(DefaultPackerPolicy).Name; - - private static string[] m_policies = null; - public static string[] Policies - { - get - { - RegenerateList(); - return m_policies; - } - } - - private static string m_selectedPolicy = null; - private static void SetSelectedPolicy(string value) - { - m_selectedPolicy = value; - PlayerSettings.spritePackerPolicy = m_selectedPolicy; - } - - public static string SelectedPolicy - { - get - { - RegenerateList(); - return m_selectedPolicy; - } - set - { - RegenerateList(); - if (value == null) - throw new ArgumentNullException(); - if (!m_policies.Contains(value)) - throw new ArgumentException("Specified policy {0} is not in the policy list.", value); - SetSelectedPolicy(value); - } - } - - private static Dictionary m_policyTypeCache = null; - private static void RegenerateList() - { - if (m_policies != null) - return; - - List types = new List(); - - System.Reflection.Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); - foreach (var assembly in assemblies) - { - try - { - Type[] asst = assembly.GetTypes(); - foreach (var t in asst) - { - if (typeof(IPackerPolicy).IsAssignableFrom(t) && (t != typeof(IPackerPolicy))) - types.Add(t); - } - } - catch (Exception ex) - { - Debug.Log(string.Format("SpritePacker failed to get types from {0}. Error: {1}", assembly.FullName, ex.Message)); - } - } - - m_policies = types.Select(t => t.Name).ToArray(); - - m_policyTypeCache = new Dictionary(); - foreach (var t in types) - { - if (m_policyTypeCache.ContainsKey(t.Name)) - { - Type otherT = m_policyTypeCache[t.Name]; - Debug.LogError(string.Format("Duplicate Sprite Packer policies found: {0} and {1}. Please rename one.", t.FullName, otherT.FullName)); - continue; - } - else - m_policyTypeCache[t.Name] = t; - } - - m_selectedPolicy = String.IsNullOrEmpty(PlayerSettings.spritePackerPolicy) ? kDefaultPolicy : PlayerSettings.spritePackerPolicy; - - // Did policies change? - if (!m_policies.Contains(m_selectedPolicy)) - SetSelectedPolicy(kDefaultPolicy); - } - - internal static string GetSelectedPolicyId() - { - RegenerateList(); - - Type t = m_policyTypeCache[m_selectedPolicy]; - IPackerPolicy policy = Activator.CreateInstance(t) as IPackerPolicy; - string versionString = string.Format("{0}::{1}", t.AssemblyQualifiedName, policy.GetVersion()); - - return versionString; - } - - internal static bool AllowSequentialPacking() - { - RegenerateList(); - - Type t = m_policyTypeCache[m_selectedPolicy]; - IPackerPolicy policy = Activator.CreateInstance(t) as IPackerPolicy; - return policy.AllowSequentialPacking; - } - - internal static void ExecuteSelectedPolicy(BuildTarget target, int[] textureImporterInstanceIDs) - { - RegenerateList(); - - Type t = m_policyTypeCache[m_selectedPolicy]; - IPackerPolicy policy = Activator.CreateInstance(t) as IPackerPolicy; - policy.OnGroupAtlases(target, new PackerJob(), textureImporterInstanceIDs); - } - - internal static void SaveUnappliedTextureImporterSettings() - { - foreach (InspectorWindow i in InspectorWindow.GetAllInspectorWindows()) - { - ActiveEditorTracker activeEditor = i.tracker; - foreach (Editor e in activeEditor.activeEditors) - { - TextureImporterInspector inspector = e as TextureImporterInspector; - if (inspector == null) - continue; - if (!inspector.HasModified()) - continue; - TextureImporter importer = inspector.target as TextureImporter; - if (EditorUtility.DisplayDialog("Unapplied import settings", "Unapplied import settings for \'" + importer.assetPath + "\'", "Apply", "Revert")) - { - inspector.ApplyAndImport(); // No way to apply/revert only some assets. Bug: 564192. - } - } - } - } - } - - public interface IPackerPolicy - { - bool AllowSequentialPacking { get; } - void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs); - int GetVersion(); - } -} diff --git a/Editor/Mono/Sprites/TightRotateEnabledSpritePackerPolicy.cs b/Editor/Mono/Sprites/TightRotateEnabledSpritePackerPolicy.cs deleted file mode 100644 index f0323ebd25..0000000000 --- a/Editor/Mono/Sprites/TightRotateEnabledSpritePackerPolicy.cs +++ /dev/null @@ -1,19 +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 UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor.Sprites -{ - // TightRotateEnabledSpritePackerPolicy will tightly pack non-rectangle Sprites unless their packing tag contains "[RECT]" with rotation and flipping for optimal packing. - internal class TightRotateEnabledSpritePackerPolicy : DefaultPackerPolicy - { - protected override string TagPrefix { get { return "[RECT]"; } } - protected override bool AllowTightWhenTagged { get { return false; } } - protected override bool AllowRotationFlipping { get { return true; } } - } -} diff --git a/Editor/Mono/Sprites/TightSpritePackerPolicy.cs b/Editor/Mono/Sprites/TightSpritePackerPolicy.cs deleted file mode 100644 index ef78eec698..0000000000 --- a/Editor/Mono/Sprites/TightSpritePackerPolicy.cs +++ /dev/null @@ -1,19 +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 UnityEngine; -using System.Collections.Generic; - -namespace UnityEditor.Sprites -{ - // TightPackerPolicy will tightly pack non-rectangle Sprites unless their packing tag contains "[RECT]". - internal class TightPackerPolicy : DefaultPackerPolicy - { - protected override string TagPrefix { get { return "[RECT]"; } } - protected override bool AllowTightWhenTagged { get { return false; } } - protected override bool AllowRotationFlipping { get { return false; } } - } -} diff --git a/Editor/Mono/StateMachine.bindings.cs b/Editor/Mono/StateMachine.bindings.cs deleted file mode 100644 index 7dd60ce12c..0000000000 --- a/Editor/Mono/StateMachine.bindings.cs +++ /dev/null @@ -1,323 +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 UnityEngineInternal; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor.Animations -{ - public enum AnimatorConditionMode - { - If = 1, - IfNot = 2, - Greater = 3, - Less = 4, - //ExitTime = 5, - Equals = 6, - NotEqual = 7, - } - - public enum TransitionInterruptionSource - { - None, - Source, - Destination, - SourceThenDestination, - DestinationThenSource - } - - [NativeHeader("Editor/Src/Animation/Transition.h")] - public struct AnimatorCondition - { - public AnimatorConditionMode mode { get {return m_ConditionMode; } set {m_ConditionMode = value; } } - public string parameter { get {return m_ConditionEvent; } set {m_ConditionEvent = value; } } - public float threshold { get {return m_EventTreshold; } set {m_EventTreshold = value; } } - - AnimatorConditionMode m_ConditionMode; //eConditionMode - string m_ConditionEvent; - float m_EventTreshold;// m_ParameterThreshold - } - - [NativeHeader("Editor/Src/Animation/Transition.h")] - [NativeHeader("Runtime/Animation/MecanimUtility.h")] - public partial class AnimatorTransitionBase : Object - { - protected AnimatorTransitionBase() {} - - public string GetDisplayName(Object source) - { - return (source is AnimatorState) ? GetDisplayNameStateSource(source as AnimatorState) : GetDisplayNameStateMachineSource(source as AnimatorStateMachine); - } - - [NativeMethod("GetDisplayName")] - extern internal string GetDisplayNameStateSource(AnimatorState source); - - [NativeMethod("GetDisplayName")] - extern internal string GetDisplayNameStateMachineSource(AnimatorStateMachine source); - - [FreeFunction] - extern static internal string BuildTransitionName(string source, string destination); - - extern public bool solo { get; set; } - extern public bool mute { get; set; } - extern public bool isExit { get; set; } - - extern public AnimatorStateMachine destinationStateMachine - { - [NativeMethod("GetDstStateMachine")] - get; - [NativeMethod("SetDstStateMachine")] - set; - } - extern public AnimatorState destinationState - { - [NativeMethod("GetDstState")] - get; - [NativeMethod("SetDstState")] - set; - } - - extern public AnimatorCondition[] conditions - { - get; - set; - } - } - - [NativeHeader("Editor/Src/Animation/Transition.h")] - [NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")] - public class AnimatorTransition : AnimatorTransitionBase - { - public AnimatorTransition() - { - Internal_CreateAnimatorTransition(this); - } - - [FreeFunction("StateMachineBindings::Internal_CreateAnimatorTransition")] - extern private static void Internal_CreateAnimatorTransition([Writable] AnimatorTransition mono); - } - - [NativeHeader("Editor/Src/Animation/Transition.h")] - [NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")] - public class AnimatorStateTransition : AnimatorTransitionBase - { - public AnimatorStateTransition() - { - Internal_CreateAnimatorStateTransition(this); - } - - [FreeFunction("StateMachineBindings::Internal_CreateAnimatorStateTransition")] - extern private static void Internal_CreateAnimatorStateTransition([Writable] AnimatorStateTransition self); - - extern public float duration - { - [NativeMethod("GetTransitionDuration")] - get; - [NativeMethod("SetTransitionDuration")] - set; - } - extern public float offset - { - [NativeMethod("GetTransitionOffset")] - get; - [NativeMethod("SetTransitionOffset")] - set; - } - extern public TransitionInterruptionSource interruptionSource - { - [NativeMethod("GetTransitionInterruptionSource")] - get; - [NativeMethod("SetTransitionInterruptionSource")] - set; - } - extern public bool orderedInterruption { get; set; } - extern public float exitTime { get; set; } - extern public bool hasExitTime { get; set; } - extern public bool hasFixedDuration { get; set; } - extern public bool canTransitionToSelf { get; set; } - } - - [NativeHeader("Editor/Src/Animation/StateMachine.h")] - [NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")] - [NativeHeader("Editor/Src/Animation/StateMachineBehaviourScripting.h")] - public partial class AnimatorState : Object - { - public AnimatorState() - { - Internal_CreateAnimatorState(this); - } - - [FreeFunction("StateMachineBindings::Internal_CreateAnimatorState")] - extern private static void Internal_CreateAnimatorState([Writable] AnimatorState self); - - extern public int nameHash - { - get; - } - extern public Motion motion { get; set; } - extern public float speed { get; set; } - extern public float cycleOffset { get; set; } - extern public bool mirror { get; set; } - extern public bool iKOnFeet { get; set; } - extern public bool writeDefaultValues { get; set; } - extern public string tag { get; set; } - extern public string speedParameter { get; set; } - extern public string cycleOffsetParameter { get; set; } - extern public string mirrorParameter { get; set; } - extern public string timeParameter { get; set; } - extern public bool speedParameterActive - { - [NativeMethod("IsSpeedParameterActive")] - get; - set; - } - extern public bool cycleOffsetParameterActive - { - [NativeMethod("IsCycleOffsetParameterActive")] - get; - set; - } - extern public bool mirrorParameterActive - { - [NativeMethod("IsMirrorParameterActive")] - get; - set; - } - - extern public bool timeParameterActive - { - [NativeMethod("IsTimeParameterActive")] - get; - set; - } - - extern internal void AddBehaviour(int instanceID); - extern internal void RemoveBehaviour(int index); - - extern public AnimatorStateTransition[] transitions { get; set; } - - [FreeFunction(Name = "ScriptingAddStateMachineBehaviourWithType", HasExplicitThis = true)] - extern private ScriptableObject ScriptingAddStateMachineBehaviourWithType(Type stateMachineBehaviourType); - - [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] - public StateMachineBehaviour AddStateMachineBehaviour(Type stateMachineBehaviourType) - { - return (StateMachineBehaviour)ScriptingAddStateMachineBehaviourWithType(stateMachineBehaviourType); - } - - public T AddStateMachineBehaviour() where T : StateMachineBehaviour - { - return AddStateMachineBehaviour(typeof(T)) as T; - } - } - - [NativeHeader("Editor/Src/Animation/StateMachine.h")] - [NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")] - [RequiredByNativeCode] - public struct ChildAnimatorState - { - AnimatorState m_State; - Vector3 m_Position; - - public AnimatorState state { get { return m_State; } set { m_State = value; } } - public Vector3 position { get {return m_Position; } set { m_Position = value; } } - } - - - [NativeHeader("Editor/Src/Animation/StateMachine.h")] - [NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")] - [RequiredByNativeCode] - public struct ChildAnimatorStateMachine - { - AnimatorStateMachine m_StateMachine; - Vector3 m_Position; - - public AnimatorStateMachine stateMachine { get { return m_StateMachine; } set { m_StateMachine = value; } } - public Vector3 position { get {return m_Position; } set { m_Position = value; } } - } - - [NativeHeader("Editor/Src/Animation/StateMachine.h")] - [NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")] - [NativeHeader("Editor/Src/Animation/StateMachineBehaviourScripting.h")] - public partial class AnimatorStateMachine : Object - { - public AnimatorStateMachine() - { - Internal_CreateAnimatorStateMachine(this); - } - - [FreeFunction("StateMachineBindings::Internal_CreateAnimatorStateMachine")] - extern private static void Internal_CreateAnimatorStateMachine([Writable] AnimatorStateMachine self); - - extern public ChildAnimatorState[] states { get; set; } - - extern public ChildAnimatorStateMachine[] stateMachines { get; set; } - - extern public AnimatorState defaultState - { - [NativeMethod("DefaultState")] - get; - set; - } - - extern public Vector3 anyStatePosition { get; set; } - extern public Vector3 entryPosition { get; set; } - extern public Vector3 exitPosition { get; set; } - extern public Vector3 parentStateMachinePosition { get; set; } - extern public AnimatorStateTransition[] anyStateTransitions { get; set; } - extern public AnimatorTransition[] entryTransitions { get; set; } - - extern public AnimatorTransition[] GetStateMachineTransitions(AnimatorStateMachine sourceStateMachine); - - extern public void SetStateMachineTransitions(AnimatorStateMachine sourceStateMachine, AnimatorTransition[] transitions); - - extern internal void AddBehaviour(int instanceID); - extern internal void RemoveBehaviour(int index); - - [FreeFunction(Name = "ScriptingAddStateMachineBehaviourWithType", HasExplicitThis = true)] - extern private ScriptableObject ScriptingAddStateMachineBehaviourWithType(Type stateMachineBehaviourType); - - [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] - public StateMachineBehaviour AddStateMachineBehaviour(Type stateMachineBehaviourType) - { - return (StateMachineBehaviour)ScriptingAddStateMachineBehaviourWithType(stateMachineBehaviourType); - } - - public T AddStateMachineBehaviour() where T : StateMachineBehaviour - { - return AddStateMachineBehaviour(typeof(T)) as T; - } - - extern public string MakeUniqueStateName(string name); - extern public string MakeUniqueStateMachineName(string name); - - - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Internals - - extern internal void Clear(); - [NativeMethod("RemoveState")] - extern internal void RemoveStateInternal(AnimatorState state); - [NativeMethod("RemoveStateMachine")] - extern internal void RemoveStateMachineInternal(AnimatorStateMachine stateMachine); - - extern internal void MoveState(AnimatorState state, AnimatorStateMachine target); - extern internal void MoveStateMachine(AnimatorStateMachine stateMachine, AnimatorStateMachine target); - - extern internal bool HasState(AnimatorState state, bool recursive); - extern internal bool HasStateMachine(AnimatorStateMachine state, bool recursive); - - extern internal int transitionCount - { - get; - } - } -} diff --git a/Editor/Mono/StateMachineBehaviourContext.bindings.cs b/Editor/Mono/StateMachineBehaviourContext.bindings.cs deleted file mode 100644 index eeac9a33dd..0000000000 --- a/Editor/Mono/StateMachineBehaviourContext.bindings.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; -using UnityEngine.Bindings; -using UnityEngine.Scripting; -using UnityEditor; -using System.Runtime.InteropServices; - -namespace UnityEditor.Animations -{ - [NativeHeader("Editor/Src/Animation/StateMachineBehaviourContext.h")] - [System.Serializable] - [StructLayout(LayoutKind.Sequential)] - [NativeAsStruct] - public partial class StateMachineBehaviourContext - { - [NativeName("m_AnimatorController")] - public AnimatorController animatorController; - [NativeName("m_AnimatorObject")] - public UnityEngine.Object animatorObject; - [NativeName("m_LayerIndex")] - public int layerIndex; - } -} diff --git a/Editor/Mono/StaticEditorFlags.cs b/Editor/Mono/StaticEditorFlags.cs deleted file mode 100644 index 2601f33a14..0000000000 --- a/Editor/Mono/StaticEditorFlags.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; - -namespace UnityEditor -{ - // Static Editor Flags - [Flags] - public enum StaticEditorFlags - { - // Considered static for lightmapping. - LightmapStatic = 1, - // Considered static for occlusion. - OccluderStatic = 2, - // Considered static for occlusion. - OccludeeStatic = 16, - // Consider for static batching. - BatchingStatic = 4, - // Considered static for navigation. - NavigationStatic = 8, - // Auto-generate OffMeshLink. - OffMeshLinkGeneration = 32, - ReflectionProbeStatic = 64 - } -} diff --git a/Editor/Mono/TooltipView/TooltipView.cs b/Editor/Mono/TooltipView/TooltipView.cs index 4a9b6242c8..bc3f53b210 100644 --- a/Editor/Mono/TooltipView/TooltipView.cs +++ b/Editor/Mono/TooltipView/TooltipView.cs @@ -66,7 +66,7 @@ void Setup(string tooltip, Rect rect) position = new Rect(0, 0, m_optimalSize.x, m_optimalSize.y); - window.ShowPopup(); + window.ShowTooltip(); window.SetAlpha(1.0f); s_guiView.mouseRayInvisible = true; diff --git a/Editor/Mono/TypeSystem/UnityType.bindings.cs b/Editor/Mono/TypeSystem/UnityType.bindings.cs deleted file mode 100644 index dcb1d5c576..0000000000 --- a/Editor/Mono/TypeSystem/UnityType.bindings.cs +++ /dev/null @@ -1,30 +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.Bindings; -using UnityEngine.Scripting; - -namespace UnityEditor -{ - [NativeHeader("Editor/Mono/TypeSystem/UnityType.bindings.h")] - internal partial class UnityType - { - #pragma warning disable 649 - [UsedByNativeCode] - private struct UnityTypeTransport - { - public uint runtimeTypeIndex; - public uint descendantCount; - public uint baseClassIndex; - public string className; - public string classNamespace; - public string module; - public int persistentTypeID; - public uint flags; - } - private static extern UnityTypeTransport[] Internal_GetAllTypes(); - } -} diff --git a/Editor/Mono/TypeSystem/UnityType.cs b/Editor/Mono/TypeSystem/UnityType.cs deleted file mode 100644 index ffbc649197..0000000000 --- a/Editor/Mono/TypeSystem/UnityType.cs +++ /dev/null @@ -1,130 +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.Collections.ObjectModel; -using System.Linq; -using UnityEngine; - -namespace UnityEditor -{ - // NOTE : Corresponds to the native TypeFlags - [Flags] - enum UnityTypeFlags - { - Abstract = 1 << 0, - Sealed = 1 << 1, - EditorOnly = 1 << 2 - } - - sealed partial class UnityType - { - public string name { get; private set; } - public string nativeNamespace { get; private set; } - public string module { get; private set; } - public int persistentTypeID { get; private set; } - public UnityType baseClass { get; private set; } - - public UnityTypeFlags flags { get; private set; } - - public bool isAbstract { get { return (flags & UnityTypeFlags.Abstract) != 0; } } - public bool isSealed { get { return (flags & UnityTypeFlags.Sealed) != 0; } } - public bool isEditorOnly { get { return (flags & UnityTypeFlags.EditorOnly) != 0; } } - - uint runtimeTypeIndex; - uint descendantCount; - - public string qualifiedName - { - get { return hasNativeNamespace ? nativeNamespace + "::" + name : name; } - } - - // NOTE : nativeNamespace == "" for types with no namespace so added this helper for convenience - // in case the caller wasn't sure whether to compare nativeNamespace with null or empty - public bool hasNativeNamespace - { - get { return nativeNamespace.Length > 0; } - } - - public bool IsDerivedFrom(UnityType baseClass) - { - // NOTE : Type indices are ordered so all derived classes are immediately following the - // base class allowing us to test inheritance with only a range check - return (runtimeTypeIndex - baseClass.runtimeTypeIndex) < baseClass.descendantCount; - } - - public static UnityType FindTypeByPersistentTypeID(int persistentTypeId) - { - UnityType result = null; - ms_idToType.TryGetValue(persistentTypeId, out result); - return result; - } - - public static uint TypeCount { get { return (uint)ms_types.Length; } } - - public static UnityType GetTypeByRuntimeTypeIndex(uint index) - { - return ms_types[index]; - } - - public static UnityType FindTypeByName(string name) - { - UnityType result = null; - ms_nameToType.TryGetValue(name, out result); - return result; - } - - public static UnityType FindTypeByNameCaseInsensitive(string name) - { - return ms_types.FirstOrDefault(t => string.Equals(name, t.name, StringComparison.OrdinalIgnoreCase)); - } - - public static ReadOnlyCollection GetTypes() - { - return ms_typesReadOnly; - } - - static UnityType() - { - var types = UnityType.Internal_GetAllTypes(); - - ms_types = new UnityType[types.Length]; - ms_idToType = new Dictionary(); - ms_nameToType = new Dictionary(); - - for (int i = 0; i < types.Length; ++i) - { - // Types are sorted so base < derived and null baseclass is passed from native as 0xffffffff - UnityType baseClass = null; - if (types[i].baseClassIndex < types.Length) - baseClass = ms_types[types[i].baseClassIndex]; - - var newType = new UnityType - { - runtimeTypeIndex = types[i].runtimeTypeIndex, - descendantCount = types[i].descendantCount, - name = types[i].className, - nativeNamespace = types[i].classNamespace, - module = types[i].module, - persistentTypeID = types[i].persistentTypeID, - baseClass = baseClass, - flags = (UnityTypeFlags)types[i].flags - }; - - Debug.Assert(types[i].runtimeTypeIndex == i); - - ms_types[i] = newType; - ms_typesReadOnly = new ReadOnlyCollection(ms_types); - ms_idToType[newType.persistentTypeID] = newType; - ms_nameToType[newType.name] = newType; - } - } - - static UnityType[] ms_types; - static ReadOnlyCollection ms_typesReadOnly; - static Dictionary ms_idToType; - static Dictionary ms_nameToType; - } -} diff --git a/Editor/Mono/UIElements/Controls/CurveField.cs b/Editor/Mono/UIElements/Controls/CurveField.cs index a6c6f02794..e6a2f58051 100644 --- a/Editor/Mono/UIElements/Controls/CurveField.cs +++ b/Editor/Mono/UIElements/Controls/CurveField.cs @@ -149,6 +149,7 @@ public override void SetValueWithoutNotify(AnimationCurve newValue) m_Value.postWrapMode = WrapMode.Once; } m_TextureDirty = true; + CurveEditorWindow.curve = m_Value; IncrementVersion(VersionChangeType.Repaint); @@ -237,8 +238,8 @@ void FillCurveData() normals = new Vector3[k_HorizontalCurveResolution * 2]; } - float startTime = 0; - float endTime = curve.keys.Length > 0 ? curve.keys[curve.keys.Length - 1].time : 1.0f; + float startTime = curve.keys[0].time; + float endTime = curve.keys[curve.keys.Length - 1].time; float duration = endTime - startTime; float minValue = Mathf.Infinity; diff --git a/Editor/Mono/UIElements/SerializableJsonDictionary.cs b/Editor/Mono/UIElements/SerializableJsonDictionary.cs deleted file mode 100644 index 7f1107f8c5..0000000000 --- a/Editor/Mono/UIElements/SerializableJsonDictionary.cs +++ /dev/null @@ -1,114 +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 UnityEngine; -using UnityEngine.Experimental.UIElements; - -namespace UnityEditor.Experimental.UIElements -{ - internal class SerializableJsonDictionary : ScriptableObject, ISerializationCallbackReceiver, ISerializableJsonDictionary - { - [SerializeField] - private List m_Keys = new List(); - - [SerializeField] - private List m_Values = new List(); - - [NonSerialized] - private Dictionary m_Dict = new Dictionary(); - - public void Set(string key, T value) where T : class - { - m_Dict[key] = value; - } - - public T Get(string key) where T : class - { - if (!ContainsKey(key)) - return null; - - if (m_Dict[key] is string) - { - T obj = Activator.CreateInstance(); - EditorJsonUtility.FromJsonOverwrite((string)m_Dict[key], obj); - m_Dict[key] = obj; - } - - return m_Dict[key] as T; - } - - public T GetScriptable(string key) where T : ScriptableObject - { - if (!ContainsKey(key)) - return null; - - if (m_Dict[key] is string) - { - var newObject = ScriptableObject.CreateInstance(); - EditorJsonUtility.FromJsonOverwrite((string)m_Dict[key], newObject); - m_Dict[key] = newObject; - } - - return m_Dict[key] as T; - } - - public void Overwrite(object obj, string key) - { - if (!ContainsKey(key)) - return; - - if (m_Dict[key] is string) - { - EditorJsonUtility.FromJsonOverwrite((string)m_Dict[key], obj); - m_Dict[key] = obj; - } - else if (m_Dict[key] != obj) - { - // If the dict. value has already been expanded but it's not - // the same instance as the obj being passed in, we need to - // copy the serialized data from the object in the dict to the - // obj passed in and then fix the dict reference to point - // to the obj. - string json = EditorJsonUtility.ToJson(m_Dict[key]); - EditorJsonUtility.FromJsonOverwrite(json, obj); - m_Dict[key] = obj; - } - } - - public bool ContainsKey(string key) - { - return m_Dict.ContainsKey(key); - } - - public void OnBeforeSerialize() - { - m_Keys.Clear(); - m_Values.Clear(); - - foreach (var data in m_Dict) - { - if (data.Key != null && data.Value != null) - { - m_Keys.Add(data.Key); - m_Values.Add(EditorJsonUtility.ToJson(data.Value)); - } - } - } - - public void OnAfterDeserialize() - { - if (m_Keys.Count == m_Values.Count) - { - m_Dict = Enumerable.Range(0, m_Keys.Count).ToDictionary(i => m_Keys[i], i => m_Values[i] as object); - } - - m_Keys.Clear(); - m_Values.Clear(); - } - } -} diff --git a/Editor/Mono/UIElements/UXMLEditorFactories.cs b/Editor/Mono/UIElements/UXMLEditorFactories.cs index e08c7e366c..db9c6cd070 100644 --- a/Editor/Mono/UIElements/UXMLEditorFactories.cs +++ b/Editor/Mono/UIElements/UXMLEditorFactories.cs @@ -6,11 +6,12 @@ namespace UnityEditor.Experimental.UIElements { + [InitializeOnLoad] internal class UXMLEditorFactories { private static bool s_Registered; - internal static void RegisterAll() + static UXMLEditorFactories() { if (s_Registered) return; diff --git a/Editor/Mono/UIElements/VisualTreeAssetEditor.cs b/Editor/Mono/UIElements/VisualTreeAssetEditor.cs index 230c2b81b2..dd9f1f6885 100644 --- a/Editor/Mono/UIElements/VisualTreeAssetEditor.cs +++ b/Editor/Mono/UIElements/VisualTreeAssetEditor.cs @@ -59,7 +59,6 @@ public void Render(VisualTreeAsset vta, Rect r, GUIStyle background) if (m_Panel == null) { - UXMLEditorFactories.RegisterAll(); m_Panel = UIElementsUtility.FindOrCreatePanel(m_LastTree, ContextType.Editor, new DataWatchService()); if (m_Panel.visualTree.styleSheets == null) { diff --git a/Editor/Mono/UnityConnect/Services/AnalyticsAccess.cs b/Editor/Mono/UnityConnect/Services/AnalyticsAccess.cs deleted file mode 100644 index ed8e854b95..0000000000 --- a/Editor/Mono/UnityConnect/Services/AnalyticsAccess.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 UnityEditor.Connect; -using UnityEngine; -using UnityEditor.Analytics; -using UnityEditor; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - class AnalyticsAccess : CloudServiceAccess - { - private const string kServiceName = "Analytics"; - private const string kServiceDisplayName = "Analytics"; - private const string kServicePackageName = "com.unity.analytics"; - private const string kServiceUrl = "https://public-cdn.cloud.unity3d.com/editor/production/cloud/analytics"; - - public override string GetServiceName() - { - return kServiceName; - } - - public override string GetServiceDisplayName() - { - return kServiceDisplayName; - } - - public override string GetPackageName() - { - return kServicePackageName; - } - - override public bool IsServiceEnabled() - { - return AnalyticsSettings.enabled; - } - - [Serializable] - public struct AnalyticsServiceState { public bool analytics; } - override public void EnableService(bool enabled) - { - if (AnalyticsSettings.enabled != enabled) - { - AnalyticsSettings.SetEnabledServiceWindow(enabled); - EditorAnalytics.SendEventServiceInfo(new AnalyticsServiceState() { analytics = enabled }); - } - } - - public bool IsTestModeEnabled() - { - return AnalyticsSettings.testMode; - } - - public void SetTestModeEnabled(bool enabled) - { - AnalyticsSettings.testMode = enabled; - } - - static AnalyticsAccess() - { - var serviceData = new UnityConnectServiceData(kServiceName, kServiceUrl, new AnalyticsAccess(), "unity/project/cloud/analytics"); - UnityConnectServiceCollection.instance.AddService(serviceData); - } - } -} - diff --git a/Editor/Mono/UnityConnect/Services/BuildAccess.cs b/Editor/Mono/UnityConnect/Services/BuildAccess.cs deleted file mode 100644 index d2bd6dcf0c..0000000000 --- a/Editor/Mono/UnityConnect/Services/BuildAccess.cs +++ /dev/null @@ -1,43 +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 UnityEditor.Connect; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - internal class BuildAccess : CloudServiceAccess - { - private const string kServiceName = "Build"; - private const string kServiceDisplayName = "Unity Build"; - private const string kServiceUrl = "https://public-cdn.cloud.unity3d.com/editor/production/cloud/build"; - - public override string GetServiceName() - { - return kServiceName; - } - - public override string GetServiceDisplayName() - { - return kServiceDisplayName; - } - - public void ShowBuildForCommit(string commitId) - { - ShowServicePage(); - - string eventCmd = string.Format("window.unityEvents ? window.unityEvents.broadcast('build.showForCommit', '{0}'): '';", commitId); - var webview = GetWebView(); - webview.ExecuteJavascript(eventCmd); - } - - static BuildAccess() - { - var serviceData = new UnityConnectServiceData(kServiceName, kServiceUrl, new BuildAccess(), "unity/project/cloud/build"); - UnityConnectServiceCollection.instance.AddService(serviceData); - } - } -} - diff --git a/Editor/Mono/UnityConnect/Services/CloudServiceAccess.cs b/Editor/Mono/UnityConnect/Services/CloudServiceAccess.cs deleted file mode 100644 index d42162a646..0000000000 --- a/Editor/Mono/UnityConnect/Services/CloudServiceAccess.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 UnityEditor.Analytics; - - -namespace UnityEditor.Web -{ - internal abstract class CloudServiceAccess - { - public abstract string GetServiceName(); - - protected WebView GetWebView() - { - return UnityEditor.Connect.UnityConnectServiceCollection.instance.GetWebViewFromServiceName(GetServiceName()); - } - - protected string GetSafeServiceName() - { - return GetServiceName().Replace(' ', '_'); - } - - public virtual string GetServiceDisplayName() - { - return GetServiceName(); - } - - public virtual string GetPackageName() - { - return string.Empty; - } - - public virtual bool IsServiceEnabled() - { - return PlayerSettings.GetCloudServiceEnabled(GetServiceName()); - } - - public virtual void EnableService(bool enabled) - { - PlayerSettings.SetCloudServiceEnabled(GetServiceName(), enabled); - } - - public virtual void OnProjectUnbound() - { - // Do nothing - } - - public void ShowServicePage() - { - UnityEditor.Connect.UnityConnectServiceCollection.instance.ShowService(GetServiceName(), true, "show_service_page"); - } - - public void GoBackToHub() - { - UnityEditor.Connect.UnityConnectServiceCollection.instance.ShowService(UnityEditor.Web.HubAccess.kServiceName, true, "go_back_to_hub"); - } - } -} - diff --git a/Editor/Mono/UnityConnect/Services/CollabAccess.cs b/Editor/Mono/UnityConnect/Services/CollabAccess.cs deleted file mode 100644 index 627a8346af..0000000000 --- a/Editor/Mono/UnityConnect/Services/CollabAccess.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 UnityEditor; -using UnityEditorInternal; -using UnityEditor.Connect; -using UnityEditor.Collaboration; -using UnityEngine; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - internal class CollabAccess : CloudServiceAccess - { - private const string kServiceName = "Collab"; - private const string kServiceDisplayName = "Unity Collab"; - private const string kServiceUrl = "https://public-cdn.cloud.unity3d.com/editor/production/cloud/collab"; - - static private CollabAccess s_instance; - public static CollabAccess Instance - { - get - { - return s_instance; - } - } - - public override string GetServiceName() - { - return kServiceName; - } - - public override string GetServiceDisplayName() - { - return kServiceDisplayName; - } - - public override void EnableService(bool enabled) - { - base.EnableService(enabled); - Collab.instance.SendNotification(); - Collab.instance.SetCollabEnabledForCurrentProject(enabled); - - AssetDatabase.Refresh(); // If auto-refresh was off, make sure we refresh when setting it back on - } - - static CollabAccess() - { - s_instance = new CollabAccess(); - - var serviceData = new UnityConnectServiceData(kServiceName, kServiceUrl, s_instance, "unity/project/cloud/collab"); - UnityConnectServiceCollection.instance.AddService(serviceData); - } - - public bool IsCollabUIAccessible() - { - return true; - } - } -} - diff --git a/Editor/Mono/UnityConnect/Services/EditorProjectAccess.bindings.cs b/Editor/Mono/UnityConnect/Services/EditorProjectAccess.bindings.cs deleted file mode 100644 index bed26b37f2..0000000000 --- a/Editor/Mono/UnityConnect/Services/EditorProjectAccess.bindings.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 UnityEngine; -using UnityEngine.Bindings; - -namespace UnityEditor.Web -{ - [NativeHeader("Editor/Src/UnityConnect/Services/EditorProjectAccess.h")] - internal partial class EditorProjectAccess : Object - { - public EditorProjectAccess() - { - Internal_Create(this); - } - - extern private static void Internal_Create([Writable] EditorProjectAccess self); - extern public string GetProjectEditorVersion(); - extern public string GetRESTServiceURI(); - } -} diff --git a/Editor/Mono/UnityConnect/Services/ErrorHubAccess.cs b/Editor/Mono/UnityConnect/Services/ErrorHubAccess.cs deleted file mode 100644 index 868c95be60..0000000000 --- a/Editor/Mono/UnityConnect/Services/ErrorHubAccess.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 UnityEditor.Connect; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - internal class ErrorHubAccess : CloudServiceAccess - { - public const string kServiceName = "ErrorHub"; - private static string kServiceUrl = "file://" + EditorApplication.userJavascriptPackagesPath + "unityeditor-cloud-hub/dist/index.html?failure=unity_connect"; - - public static ErrorHubAccess instance { get; private set; } - public string errorMessage { get; set; } - - public override string GetServiceName() - { - return kServiceName; - } - - static ErrorHubAccess() - { - instance = new ErrorHubAccess(); - var serviceData = new UnityConnectServiceData(kServiceName, kServiceUrl, instance, "unity/project/cloud/errorhub"); - UnityConnectServiceCollection.instance.AddService(serviceData); - } - } -} - diff --git a/Editor/Mono/UnityConnect/Services/UnetAccess.cs b/Editor/Mono/UnityConnect/Services/UnetAccess.cs deleted file mode 100644 index 34dba3a5f9..0000000000 --- a/Editor/Mono/UnityConnect/Services/UnetAccess.cs +++ /dev/null @@ -1,50 +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.Connect; - -namespace UnityEditor.Web -{ - [InitializeOnLoad] - internal class UnetAccess : CloudServiceAccess - { - const string kServiceName = "UNet"; - const string kServiceDisplayName = "Multiplayer"; - const string kServiceUrl = "https://public-cdn.cloud.unity3d.com/editor/production/cloud/unet"; - - public override string GetServiceName() - { - return kServiceName; - } - - public override string GetServiceDisplayName() - { - return kServiceDisplayName; - } - - [Serializable] - public struct UnetServiceState { public bool unet; } - override public void EnableService(bool enabled) - { - if (IsServiceEnabled() != enabled) - { - base.EnableService(enabled); - EditorAnalytics.SendEventServiceInfo(new UnetServiceState() { unet = enabled }); - } - } - - static UnetAccess() - { - var serviceData = new UnityConnectServiceData(kServiceName, kServiceUrl, new UnetAccess(), "unity/project/cloud/networking"); - UnityConnectServiceCollection.instance.AddService(serviceData); - } - - public void SetMultiplayerId(int id) - { - } - } -} - diff --git a/Editor/Mono/UnityConnect/UnityConnectConsentView.cs b/Editor/Mono/UnityConnect/UnityConnectConsentView.cs deleted file mode 100644 index 8556770688..0000000000 --- a/Editor/Mono/UnityConnect/UnityConnectConsentView.cs +++ /dev/null @@ -1,93 +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 UnityEngine; -using UnityEditor.Web; -using System.Collections.Generic; - -namespace UnityEditor.Connect -{ - [Serializable] - internal class UnityConnectConsentView : WebViewEditorWindow - { - private String code = ""; - private String error = ""; - - public String Code - { - get - { - return code; - } - } - - public String Error - { - get - { - return error; - } - } - - internal override WebView webView - { - get; set; - } - - public static UnityConnectConsentView ShowUnityConnectConsentView(String URL) - { - UnityConnectConsentView consentView = ScriptableObject.CreateInstance(); - - var rect = new Rect(100, 100, 800, 605); - consentView.titleContent = EditorGUIUtility.TrTextContent("Unity Application Consent Window"); - consentView.minSize = new Vector2(rect.width, rect.height); - consentView.maxSize = new Vector2(rect.width, rect.height); - consentView.position = rect; - consentView.m_InitialOpenURL = URL; - consentView.ShowModal(); - - consentView.m_Parent.window.m_DontSaveToLayout = true; - - return consentView; - } - - override public void OnDestroy() - { - OnBecameInvisible(); - } - - override public void OnInitScripting() - { - base.SetScriptObject(); - } - - override public void OnLocationChanged(string url) - { - var location = new Uri(url); - foreach (string item in location.Query.Split('&')) - { - string[] qs = item.Replace("?", String.Empty).Split('='); - if (qs[0] == "code") - { - code = qs[1]; - break; - } - if (qs[0] == "error") - { - error = qs[1]; - break; - } - } - - if (!string.IsNullOrEmpty(code) || !string.IsNullOrEmpty(error)) - { - this.Close(); - return; - } - base.OnLocationChanged(url); - } - } -} diff --git a/Editor/Mono/UnityConnect/UnityConnectPrefs.cs b/Editor/Mono/UnityConnect/UnityConnectPrefs.cs deleted file mode 100644 index c120fce432..0000000000 --- a/Editor/Mono/UnityConnect/UnityConnectPrefs.cs +++ /dev/null @@ -1,175 +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; - -namespace UnityEditor.Connect -{ - internal class UnityConnectPrefs - { - public static string[] kEnvironmentFamilies = new string[] {"Production", "Staging", "Dev", "Custom"}; - public const int kProductionEnv = 0; - public const int kCustomEnv = 3; - - public const string kSvcEnvPref = "CloudPanelServer"; - public const string kSvcCustomUrlPref = "CloudPanelCustomUrl"; - public const string kSvcCustomPortPref = "CloudPanelCustomPort"; - - protected class CloudPanelPref - { - public CloudPanelPref(string serviceName) - { - m_ServiceName = serviceName; - m_CloudPanelServer = GetServiceEnv(m_ServiceName); - m_CloudPanelCustomUrl = EditorPrefs.GetString(ServicePrefKey(kSvcCustomUrlPref , m_ServiceName)); - m_CloudPanelCustomPort = EditorPrefs.GetInt(ServicePrefKey(kSvcCustomPortPref , m_ServiceName)); - } - - public void StoreCloudServicePref() - { - EditorPrefs.SetInt(ServicePrefKey(kSvcEnvPref, m_ServiceName), m_CloudPanelServer); - EditorPrefs.SetString(ServicePrefKey(kSvcCustomUrlPref , m_ServiceName), m_CloudPanelCustomUrl); - EditorPrefs.SetInt(ServicePrefKey(kSvcCustomPortPref , m_ServiceName), m_CloudPanelCustomPort); - } - - public string m_ServiceName; - public int m_CloudPanelServer; - public string m_CloudPanelCustomUrl; - public int m_CloudPanelCustomPort; - }; - - protected static CloudPanelPref GetPanelPref(string serviceName) - { - if (m_CloudPanelPref.ContainsKey(serviceName)) - return m_CloudPanelPref[serviceName]; - - CloudPanelPref pref = new CloudPanelPref(serviceName); - m_CloudPanelPref.Add(serviceName, pref); - return pref; - } - - protected static Dictionary m_CloudPanelPref = new Dictionary(); - - public static int GetServiceEnv(string serviceName) - { - if (Unsupported.IsDeveloperMode() || UnityConnect.preferencesEnabled) - return EditorPrefs.GetInt(ServicePrefKey(kSvcEnvPref, serviceName)); - - for (var i = 0; i < kEnvironmentFamilies.Length; i++) - { - var environmentName = kEnvironmentFamilies[i]; - //By using the configuration it should default to production if there is no - //-cloudEnvironment or to the switch value in case it is specified - if (environmentName.Equals(UnityConnect.instance.configuration, StringComparison.InvariantCultureIgnoreCase)) - return i; - } - return 0; //Return production if there is an error - } - - public static string ServicePrefKey(string baseKey, string serviceName) - { - return baseKey + "/" + serviceName; - } - - public static string FixUrl(string url, string serviceName) - { - var fixUrl = url; - var panelEnv = GetServiceEnv(serviceName); - if (panelEnv != kProductionEnv) - { - if (fixUrl.StartsWith("http://") || fixUrl.StartsWith("https://")) - { - if (panelEnv == kCustomEnv) - { - var devUrl = EditorPrefs.GetString(ServicePrefKey(kSvcCustomUrlPref , serviceName)); - var devPort = EditorPrefs.GetInt(ServicePrefKey(kSvcCustomPortPref , serviceName)); - fixUrl = (devPort == 0) ? devUrl : (devUrl + ":" + devPort); - } - else - { - fixUrl = fixUrl.ToLower(); - fixUrl = fixUrl.Replace("/" + kEnvironmentFamilies[kProductionEnv].ToLower() + "/", "/" + kEnvironmentFamilies[panelEnv].ToLower() + "/"); - } - return fixUrl; - } - - if (fixUrl.StartsWith("file://")) - { - fixUrl = fixUrl.Substring(7); - - if (panelEnv == kCustomEnv) - { - var devUrl = EditorPrefs.GetString(ServicePrefKey(kSvcCustomUrlPref , serviceName)); - var devPort = EditorPrefs.GetInt(ServicePrefKey(kSvcCustomPortPref , serviceName)); - fixUrl = devUrl + ":" + devPort; - } - - return fixUrl; - } - - if (!fixUrl.StartsWith("file://") && !fixUrl.StartsWith("http://") && !fixUrl.StartsWith("https://")) - { - fixUrl = "http://" + fixUrl; - return fixUrl; - } - } - - return fixUrl; - } - - static public void ShowPanelPrefUI() - { - List cloudServiceNames = UnityConnectServiceCollection.instance.GetAllServiceNames(); - - bool changed = false; - - foreach (string service in cloudServiceNames) - { - CloudPanelPref pref = GetPanelPref(service); - - int nVal = EditorGUILayout.Popup(service, pref.m_CloudPanelServer, kEnvironmentFamilies); - if (nVal != pref.m_CloudPanelServer) - { - pref.m_CloudPanelServer = nVal; - changed = true; - } - - if (pref.m_CloudPanelServer == kCustomEnv) - { - EditorGUI.indentLevel++; - string nUrl = EditorGUILayout.TextField("Custom server URL", pref.m_CloudPanelCustomUrl); - if (nUrl != pref.m_CloudPanelCustomUrl) - { - pref.m_CloudPanelCustomUrl = nUrl; - changed = true; - } - - Int32.TryParse(EditorGUILayout.TextField("Custom server port", pref.m_CloudPanelCustomPort.ToString()), out nVal); - - if (nVal != pref.m_CloudPanelCustomPort) - { - pref.m_CloudPanelCustomPort = nVal; - changed = true; - } - EditorGUI.indentLevel--; - } - } - - if (changed) - UnityConnectServiceCollection.instance.ReloadServices(); - } - - public static void StorePanelPrefs() - { - if (!Unsupported.IsDeveloperMode() && !UnityConnect.preferencesEnabled) - return; - - foreach (KeyValuePair kvp in m_CloudPanelPref) - { - kvp.Value.StoreCloudServicePref(); - } - } - } -} diff --git a/Editor/Mono/UnityConnect/UnityConnectServiceData.cs b/Editor/Mono/UnityConnect/UnityConnectServiceData.cs deleted file mode 100644 index 468478fbb2..0000000000 --- a/Editor/Mono/UnityConnect/UnityConnectServiceData.cs +++ /dev/null @@ -1,66 +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.Web; - -namespace UnityEditor.Connect -{ - internal class UnityConnectServiceData - { - private readonly string m_ServiceName; - private readonly string m_HtmlSourcePath; - private readonly CloudServiceAccess m_JavascriptGlobalObject; - private readonly string m_JsGlobalObjectName; - public string serviceName { get { return m_ServiceName; }} - public string serviceUrl - { - get - { - return UnityConnectPrefs.FixUrl(m_HtmlSourcePath, m_ServiceName); - } - } - public CloudServiceAccess serviceJsGlobalObject { get { return m_JavascriptGlobalObject; }} - public string serviceJsGlobalObjectName {get { return m_JsGlobalObjectName; }} - - - public UnityConnectServiceData(string serviceName, string htmlSourcePath, CloudServiceAccess jsGlobalObject, string jsGlobalObjectName) - { - if (string.IsNullOrEmpty(serviceName)) - throw new ArgumentNullException("serviceName"); - - if (string.IsNullOrEmpty(htmlSourcePath)) - throw new ArgumentNullException("htmlSourcePath"); - - m_ServiceName = serviceName; - m_HtmlSourcePath = htmlSourcePath; - m_JavascriptGlobalObject = jsGlobalObject; - m_JsGlobalObjectName = jsGlobalObjectName; - if (m_JavascriptGlobalObject != null) - { - //If no name is specified use the service name - if (string.IsNullOrEmpty(m_JsGlobalObjectName)) - m_JsGlobalObjectName = m_ServiceName; - - JSProxyMgr.GetInstance().AddGlobalObject(m_JsGlobalObjectName, m_JavascriptGlobalObject); - } - } - - public void EnableService(bool enabled) - { - if (m_JavascriptGlobalObject != null) - { - m_JavascriptGlobalObject.EnableService(enabled); - } - } - - public void OnProjectUnbound() - { - if (m_JavascriptGlobalObject != null) - { - m_JavascriptGlobalObject.OnProjectUnbound(); - } - } - } -} diff --git a/Editor/Mono/Utils/AssemblyReferenceChecker.cs b/Editor/Mono/Utils/AssemblyReferenceChecker.cs deleted file mode 100644 index e908b6e719..0000000000 --- a/Editor/Mono/Utils/AssemblyReferenceChecker.cs +++ /dev/null @@ -1,309 +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 Mono.Cecil; -using Mono.Cecil.Cil; - -namespace UnityEditor -{ - internal class AssemblyReferenceChecker - { - private readonly HashSet _referencedMethods = new HashSet(); - private HashSet _referencedTypes = new HashSet(); - private readonly HashSet _userReferencedMethods = new HashSet(); - private readonly HashSet _definedMethods = new HashSet(); - private HashSet _assemblyDefinitions = new HashSet(); - private readonly HashSet _assemblyFileNames = new HashSet(); - - private DateTime _startTime = DateTime.MinValue; - private float _progressValue = 0.0f; - - private Action _updateProgressAction; - - public bool HasMouseEvent { get; private set; } - - public AssemblyReferenceChecker() - { - HasMouseEvent = false; - _updateProgressAction = DisplayProgress; - } - - public static AssemblyReferenceChecker AssemblyReferenceCheckerWithUpdateProgressAction(Action action) - { - var checker = new AssemblyReferenceChecker(); - checker._updateProgressAction = action; - return checker; - } - - // Follows actually referenced libraries only - private void CollectReferencesFromRootsRecursive(string dir, IEnumerable roots, bool ignoreSystemDlls) - { - var resolver = AssemblyResolverFor(dir); - - foreach (var assemblyFileName in roots) - { - var fileName = Path.Combine(dir, assemblyFileName); - if (_assemblyFileNames.Contains(assemblyFileName)) - continue; - - var assemblyDefinition = AssemblyDefinition.ReadAssembly(fileName, new ReaderParameters { AssemblyResolver = resolver }); - - if (ignoreSystemDlls && IsIgnoredSystemDll(assemblyDefinition)) - continue; - - _assemblyFileNames.Add(assemblyFileName); - _assemblyDefinitions.Add(assemblyDefinition); - - foreach (var reference in assemblyDefinition.MainModule.AssemblyReferences) - { - var refFileName = reference.Name + ".dll"; - if (_assemblyFileNames.Contains(refFileName)) - continue; - CollectReferencesFromRootsRecursive(dir, new string[] {refFileName}, ignoreSystemDlls); - } - } - } - - // Follows actually referenced libraries only - public void CollectReferencesFromRoots(string dir, IEnumerable roots, bool collectMethods, float progressValue, bool ignoreSystemDlls) - { - _progressValue = progressValue; - - CollectReferencesFromRootsRecursive(dir, roots, ignoreSystemDlls); - - var assemblyDefinitionsAsArray = _assemblyDefinitions.ToArray(); - _referencedTypes = MonoAOTRegistration.BuildReferencedTypeList(assemblyDefinitionsAsArray); - - if (collectMethods) - CollectReferencedAndDefinedMethods(assemblyDefinitionsAsArray); - } - - public void CollectReferences(string path, bool collectMethods, float progressValue, bool ignoreSystemDlls) - { - _progressValue = progressValue; - - _assemblyDefinitions = new HashSet(); - - var filePaths = Directory.Exists(path) ? Directory.GetFiles(path) : new string[0]; - - var resolver = AssemblyResolverFor(path); - - foreach (var filePath in filePaths) - { - if (Path.GetExtension(filePath) != ".dll") - continue; - - var assembly = AssemblyDefinition.ReadAssembly(filePath, new ReaderParameters { AssemblyResolver = resolver }); - - if (ignoreSystemDlls && IsIgnoredSystemDll(assembly)) - continue; - - _assemblyFileNames.Add(Path.GetFileName(filePath)); - _assemblyDefinitions.Add(assembly); - } - - var assemblyDefinitionsAsArray = _assemblyDefinitions.ToArray(); - _referencedTypes = MonoAOTRegistration.BuildReferencedTypeList(assemblyDefinitionsAsArray); - - if (collectMethods) - CollectReferencedAndDefinedMethods(assemblyDefinitionsAsArray); - } - - private void CollectReferencedAndDefinedMethods(IEnumerable assemblyDefinitions) - { - foreach (var assembly in assemblyDefinitions) - { - bool boolIsSystem = IsIgnoredSystemDll(assembly); - foreach (var type in assembly.MainModule.Types) - CollectReferencedAndDefinedMethods(type, boolIsSystem); - } - } - - internal void CollectReferencedAndDefinedMethods(TypeDefinition type) - { - CollectReferencedAndDefinedMethods(type, false); - } - - internal void CollectReferencedAndDefinedMethods(TypeDefinition type, bool isSystem) - { - if (_updateProgressAction != null) - _updateProgressAction(); - - foreach (var nestedType in type.NestedTypes) - CollectReferencedAndDefinedMethods(nestedType, isSystem); - - foreach (var method in type.Methods) - { - if (!method.HasBody) - continue; - - foreach (var instr in method.Body.Instructions) - { - if (OpCodes.Call == instr.OpCode) - { - var name = instr.Operand.ToString(); - if (!isSystem) - { - _userReferencedMethods.Add(name); - } - _referencedMethods.Add(name); - } - } - _definedMethods.Add(method.ToString()); - - HasMouseEvent |= MethodIsMouseEvent(method); - } - } - - private bool MethodIsMouseEvent(MethodDefinition method) - { - var methodNameIsMouseEvent = - method.Name == "OnMouseDown" - || method.Name == "OnMouseDrag" - || method.Name == "OnMouseEnter" - || method.Name == "OnMouseExit" - || method.Name == "OnMouseOver" - || method.Name == "OnMouseUp" - || method.Name == "OnMouseUpAsButton"; - - if (!methodNameIsMouseEvent) - return false; - - if (method.Parameters.Count != 0) - return false; - - bool isInUnityEngineBehavior = InheritsFromMonoBehaviour(method.DeclaringType); - - if (!isInUnityEngineBehavior) - return false; - - return true; - } - - private bool InheritsFromMonoBehaviour(TypeReference type) - { - // Case 833157: StagingArea\Data\Managed contains user and dependency assemblies, but doesn't contain UnityEngine.dll. This applies for all platforms - // Thus we wouldn't be able to load UnityEngine.dll when Resolve() is called. That's why we're delaying Resolve() as much as possible - if (type.Namespace == "UnityEngine" && type.Name == "MonoBehaviour") - return true; - - try - { - var typeDefinition = type.Resolve(); - if (typeDefinition.BaseType != null) - return InheritsFromMonoBehaviour(typeDefinition.BaseType); - } - catch (AssemblyResolutionException) - { - // We weren't able to resolve the base type - let's assume it's not a monobehaviour - } - - return false; - } - - private void DisplayProgress() - { - var elapsedTime = DateTime.Now - _startTime; - var progressStrings = new[] - { - "Fetching assembly references", - "Building list of referenced assemblies..." - }; - - if (elapsedTime.TotalMilliseconds >= 100) - { - if (EditorUtility.DisplayCancelableProgressBar(progressStrings[0], progressStrings[1], _progressValue)) - throw new OperationCanceledException(); - - _startTime = DateTime.Now; - } - } - - public bool HasReferenceToMethod(string methodName) - { - return HasReferenceToMethod(methodName, false); - } - - public bool HasReferenceToMethod(string methodName, bool ignoreSystemDlls) - { - return !ignoreSystemDlls? _referencedMethods.Any(item => item.Contains(methodName)) : _userReferencedMethods.Any(item => item.Contains(methodName)); - } - - public bool HasDefinedMethod(string methodName) - { - return _definedMethods.Any(item => item.Contains(methodName)); - } - - public bool HasReferenceToType(string typeName) - { - return _referencedTypes.Any(item => item.StartsWith(typeName)); - } - - public AssemblyDefinition[] GetAssemblyDefinitions() - { - return _assemblyDefinitions.ToArray(); - } - - public string[] GetAssemblyFileNames() - { - return _assemblyFileNames.ToArray(); - } - - public string WhoReferencesClass(string klass, bool ignoreSystemDlls) - { - foreach (var assembly in _assemblyDefinitions) - { - if (ignoreSystemDlls && IsIgnoredSystemDll(assembly)) - continue; - - var assemblyDefinitionsAsArray = new[] {assembly}; - var types = MonoAOTRegistration.BuildReferencedTypeList(assemblyDefinitionsAsArray); - - if (types.Any(item => item.StartsWith(klass))) - return assembly.Name.Name; - } - - return null; - } - - public static bool IsIgnoredSystemDll(AssemblyDefinition assembly) - { - if (AssemblyHelper.IsUnityEngineModule(assembly)) - return true; - var name = assembly.Name.Name; - return name.StartsWith("System") - || name.Equals("UnityEngine") - || name.Equals("UnityEngine.Networking") - || name.Equals("Mono.Posix") - || name.Equals("Moq"); - } - - public static bool GetScriptsHaveMouseEvents(string path) - { - var checker = new AssemblyReferenceChecker(); - checker.CollectReferences(path, true, 0.0f, true); - - return checker.HasMouseEvent; - } - - private static DefaultAssemblyResolver AssemblyResolverFor(string path) - { - var resolver = new DefaultAssemblyResolver(); - if (File.Exists(path) || Directory.Exists(path)) - { - var attributes = File.GetAttributes(path); - if ((attributes & FileAttributes.Directory) != FileAttributes.Directory) - path = Path.GetDirectoryName(path); - resolver.AddSearchDirectory(Path.GetFullPath(path)); - } - - return resolver; - } - } -} diff --git a/Editor/Mono/Utils/DirectoryExtensions.cs b/Editor/Mono/Utils/DirectoryExtensions.cs index 7079909df6..609bbae427 100644 --- a/Editor/Mono/Utils/DirectoryExtensions.cs +++ b/Editor/Mono/Utils/DirectoryExtensions.cs @@ -6,7 +6,7 @@ namespace UnityEditor.Utils { - internal static class DirectoryExtensions + static class DirectoryExtensions { public static void DeleteRecursive(this string directoryPath) { diff --git a/Editor/Mono/Utils/EditorExtensionMethods.cs b/Editor/Mono/Utils/EditorExtensionMethods.cs deleted file mode 100644 index 4d8e311798..0000000000 --- a/Editor/Mono/Utils/EditorExtensionMethods.cs +++ /dev/null @@ -1,84 +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 System; -using System.Linq; -using System.Collections.Generic; - -namespace UnityEditor -{ - internal static class EditorExtensionMethods - { - // Use this method when checking if user hit Space or Return in order to activate the main action - // for a control, such as opening a popup menu or color picker. - internal static bool MainActionKeyForControl(this UnityEngine.Event evt, int controlId) - { - if (EditorGUIUtility.keyboardControl != controlId) - return false; - - bool anyModifiers = (evt.alt || evt.shift || evt.command || evt.control); - - // Block window maximize (on OSX ML, we need to show the menu as part of the KeyCode event, so we can't do the usual check) - if (evt.type == EventType.KeyDown && evt.character == ' ' && !anyModifiers) - { - evt.Use(); - return false; - } - - // Space or return is action key - return evt.type == EventType.KeyDown && - (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter) && - !anyModifiers; - } - - internal static bool IsArrayOrList(this Type listType) - { - if (listType.IsArray) - { - return true; - } - else if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>)) - { - return true; - } - return false; - } - - internal static Type GetArrayOrListElementType(this Type listType) - { - if (listType.IsArray) - { - return listType.GetElementType(); - } - else if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>)) - { - return listType.GetGenericArguments()[0]; - } - return null; - } - - internal static List EnumGetNonObsoleteValues(this Type type) - { - // each enum value has the same position in both values and names arrays - string[] names = Enum.GetNames(type); - Enum[] values = Enum.GetValues(type).Cast().ToArray(); - var result = new List(); - for (int i = 0; i < names.Length; i++) - { - var info = type.GetMember(names[i]); - var attrs = info[0].GetCustomAttributes(typeof(ObsoleteAttribute), false); - var isObsolete = false; - foreach (var attr in attrs) - { - if (attr is ObsoleteAttribute) - isObsolete = true; - } - if (!isObsolete) - result.Add(values[i]); - } - return result; - } - } -} diff --git a/Editor/Mono/Utils/IDeviceUtils.cs b/Editor/Mono/Utils/IDeviceUtils.cs deleted file mode 100644 index a855a393a8..0000000000 --- a/Editor/Mono/Utils/IDeviceUtils.cs +++ /dev/null @@ -1,42 +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 UnityEditor.Modules; - - -namespace UnityEditor -{ - internal static class IDeviceUtils - { - // API for native calls - internal static RemoteAddress StartRemoteSupport(string deviceId) - { - IDevice device = ModuleManager.GetDevice(deviceId); - return device.StartRemoteSupport(); - } - - // API for native calls - internal static void StopRemoteSupport(string deviceId) - { - IDevice device = ModuleManager.GetDevice(deviceId); - device.StopRemoteSupport(); - } - - // API for native calls - internal static RemoteAddress StartPlayerConnectionSupport(string deviceId) - { - IDevice device = ModuleManager.GetDevice(deviceId); - return device.StartPlayerConnectionSupport(); - } - - // API for native calls - internal static void StopPlayerConnectionSupport(string deviceId) - { - IDevice device = ModuleManager.GetDevice(deviceId); - device.StopPlayerConnectionSupport(); - } - } -} diff --git a/Editor/Mono/Utils/LightProbeGroupSelection.cs b/Editor/Mono/Utils/LightProbeGroupSelection.cs deleted file mode 100644 index 5fcd207883..0000000000 --- a/Editor/Mono/Utils/LightProbeGroupSelection.cs +++ /dev/null @@ -1,14 +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.Collections.Generic; -using UnityEngine; - -namespace UnityEditor -{ - internal class LightProbeGroupSelection : ScriptableObject - { - public List m_Selection = new List(); - } -} diff --git a/Editor/Mono/Utils/ManagedProgram.cs b/Editor/Mono/Utils/ManagedProgram.cs deleted file mode 100644 index 475c8d3377..0000000000 --- a/Editor/Mono/Utils/ManagedProgram.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 System.Diagnostics; -using System.IO; -using UnityEditor.Scripting.Compilers; -using UnityEditor.Utils; -using UnityEngine; - -namespace UnityEditor.Scripting -{ - internal class ManagedProgram : Program - { - public ManagedProgram(string monodistribution, string profile, string executable, string arguments, Action setupStartInfo) : - this(monodistribution, profile, executable, arguments, true, setupStartInfo) - { - } - - public ManagedProgram(string monodistribution, string profile, string executable, string arguments, bool setMonoEnvironmentVariables, Action setupStartInfo) - { - var monoexe = PathCombine(monodistribution, "bin", "mono"); - if (Application.platform == RuntimePlatform.WindowsEditor) - monoexe = CommandLineFormatter.PrepareFileName(monoexe + ".exe"); - - var startInfo = new ProcessStartInfo - { - Arguments = CommandLineFormatter.PrepareFileName(executable) + " " + arguments, - CreateNoWindow = true, - FileName = monoexe, - RedirectStandardError = true, - RedirectStandardOutput = true, - WorkingDirectory = Application.dataPath + "/..", - UseShellExecute = false - }; - - if (setMonoEnvironmentVariables) - { - var profileAbspath = PathCombine(monodistribution, "lib", "mono", profile); - startInfo.EnvironmentVariables["MONO_PATH"] = profileAbspath; - startInfo.EnvironmentVariables["MONO_CFG_DIR"] = PathCombine(monodistribution, "etc"); - } - - // if you ever need to debug assembly loading, uncomment the following two lines - //startInfo.EnvironmentVariables["MONO_LOG_LEVEL"] = "info"; - //startInfo.EnvironmentVariables["MONO_LOG_MASK"] = "asm"; - - if (setupStartInfo != null) - setupStartInfo(startInfo); - - _process.StartInfo = startInfo; - } - - static string PathCombine(params string[] parts) - { - var path = parts[0]; - for (var i = 1; i < parts.Length; ++i) - path = Path.Combine(path, parts[i]); - return path; - } - } -} diff --git a/Editor/Mono/Utils/MathUtils.cs b/Editor/Mono/Utils/MathUtils.cs deleted file mode 100644 index a15e92e725..0000000000 --- a/Editor/Mono/Utils/MathUtils.cs +++ /dev/null @@ -1,498 +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.Collections; -using System.Collections.Generic; -using UnityEngine; - -namespace UnityEditor -{ - public class MathUtils - { - // We cannot round to more decimals than 15 according to docs for System.Math.Round. - private const int kMaxDecimals = 15; - - internal static float ClampToFloat(double value) - { - if (double.IsPositiveInfinity(value)) - return float.PositiveInfinity; - - if (double.IsNegativeInfinity(value)) - return float.NegativeInfinity; - - if (value < float.MinValue) - return float.MinValue; - - if (value > float.MaxValue) - return float.MaxValue; - - return (float)value; - } - - internal static int ClampToInt(long value) - { - if (value < int.MinValue) - return int.MinValue; - - if (value > int.MaxValue) - return int.MaxValue; - - return (int)value; - } - - internal static float RoundToMultipleOf(float value, float roundingValue) - { - if (roundingValue == 0) - return value; - return Mathf.Round(value / roundingValue) * roundingValue; - } - - internal static float GetClosestPowerOfTen(float positiveNumber) - { - if (positiveNumber <= 0) - return 1; - return Mathf.Pow(10, Mathf.RoundToInt(Mathf.Log10(positiveNumber))); - } - - internal static int GetNumberOfDecimalsForMinimumDifference(float minDifference) - { - return Mathf.Clamp(-Mathf.FloorToInt(Mathf.Log10(Mathf.Abs(minDifference))), 0, kMaxDecimals); - } - - internal static int GetNumberOfDecimalsForMinimumDifference(double minDifference) - { - return (int)System.Math.Max(0.0, -System.Math.Floor(System.Math.Log10(System.Math.Abs(minDifference)))); - } - - internal static float RoundBasedOnMinimumDifference(float valueToRound, float minDifference) - { - if (minDifference == 0) - return DiscardLeastSignificantDecimal(valueToRound); - return (float)System.Math.Round(valueToRound, GetNumberOfDecimalsForMinimumDifference(minDifference), System.MidpointRounding.AwayFromZero); - } - - internal static double RoundBasedOnMinimumDifference(double valueToRound, double minDifference) - { - if (minDifference == 0) - return DiscardLeastSignificantDecimal(valueToRound); - return System.Math.Round(valueToRound, GetNumberOfDecimalsForMinimumDifference(minDifference), System.MidpointRounding.AwayFromZero); - } - - internal static float DiscardLeastSignificantDecimal(float v) - { - int decimals = Mathf.Clamp((int)(5 - Mathf.Log10(Mathf.Abs(v))), 0, kMaxDecimals); - return (float)System.Math.Round(v, decimals, System.MidpointRounding.AwayFromZero); - } - - internal static double DiscardLeastSignificantDecimal(double v) - { - int decimals = System.Math.Max(0, (int)(5 - System.Math.Log10(System.Math.Abs(v)))); - try - { - return System.Math.Round(v, decimals); - } - catch (System.ArgumentOutOfRangeException) - { - // This can happen for very small numbers. - return 0; - } - } - - public static float GetQuatLength(Quaternion q) - { - return Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); - } - - public static Quaternion GetQuatConjugate(Quaternion q) - { - return new Quaternion(-q.x, -q.y, -q.z, q.w); - } - - public static Matrix4x4 OrthogonalizeMatrix(Matrix4x4 m) - { - Matrix4x4 n = Matrix4x4.identity; - - Vector3 i = m.GetColumn(0); - Vector3 j = m.GetColumn(1); - Vector3 k = m.GetColumn(2); - k = k.normalized; - i = Vector3.Cross(j, k).normalized; - j = Vector3.Cross(k, i).normalized; - - n.SetColumn(0, i); - n.SetColumn(1, j); - n.SetColumn(2, k); - - return n; - } - - public static void QuaternionNormalize(ref Quaternion q) - { - float invMag = 1.0f / Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); - q.x *= invMag; - q.y *= invMag; - q.z *= invMag; - q.w *= invMag; - } - - public static Quaternion QuaternionFromMatrix(Matrix4x4 m) - { - // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm - Quaternion q = new Quaternion(); - q.w = Mathf.Sqrt(Mathf.Max(0, 1 + m[0, 0] + m[1, 1] + m[2, 2])) / 2; - q.x = Mathf.Sqrt(Mathf.Max(0, 1 + m[0, 0] - m[1, 1] - m[2, 2])) / 2; - q.y = Mathf.Sqrt(Mathf.Max(0, 1 - m[0, 0] + m[1, 1] - m[2, 2])) / 2; - q.z = Mathf.Sqrt(Mathf.Max(0, 1 - m[0, 0] - m[1, 1] + m[2, 2])) / 2; - q.x *= Mathf.Sign(q.x * (m[2, 1] - m[1, 2])); - q.y *= Mathf.Sign(q.y * (m[0, 2] - m[2, 0])); - q.z *= Mathf.Sign(q.z * (m[1, 0] - m[0, 1])); - // normalize - QuaternionNormalize(ref q); - return q; - } - - /// - /// Logarithm of a unit quaternion. The result is not necessary a unit quaternion. - /// - public static Quaternion GetQuatLog(Quaternion q) - { - Quaternion res = q; - res.w = 0; - - if (Mathf.Abs(q.w) < 1.0f) - { - float theta = Mathf.Acos(q.w); - float sin_theta = Mathf.Sin(theta); - - if (Mathf.Abs(sin_theta) > 0.0001) - { - float coef = theta / sin_theta; - res.x = q.x * coef; - res.y = q.y * coef; - res.z = q.z * coef; - } - } - - return res; - } - - public static Quaternion GetQuatExp(Quaternion q) - { - Quaternion res = q; - - float fAngle = Mathf.Sqrt(q.x * q.x + q.y * q.y + q.z * q.z); - float fSin = Mathf.Sin(fAngle); - - res.w = Mathf.Cos(fAngle); - - if (Mathf.Abs(fSin) > 0.0001) - { - float coef = fSin / fAngle; - res.x = coef * q.x; - res.y = coef * q.y; - res.z = coef * q.z; - } - - return res; - } - - /// - /// SQUAD Spherical Quadrangle interpolation [Shoe87] - /// - public static Quaternion GetQuatSquad(float t, Quaternion q0, Quaternion q1, Quaternion a0, Quaternion a1) - { - float slerpT = 2.0f * t * (1.0f - t); - - Quaternion slerpP = Slerp(q0, q1, t); - Quaternion slerpQ = Slerp(a0, a1, t); - Quaternion slerp = Slerp(slerpP, slerpQ, slerpT); - - // normalize quaternion - float l = Mathf.Sqrt(slerp.x * slerp.x + slerp.y * slerp.y + slerp.z * slerp.z + slerp.w * slerp.w); - slerp.x /= l; - slerp.y /= l; - slerp.z /= l; - slerp.w /= l; - - return slerp; - } - - public static Quaternion GetSquadIntermediate(Quaternion q0, Quaternion q1, Quaternion q2) - { - Quaternion q1Inv = GetQuatConjugate(q1); - Quaternion p0 = GetQuatLog(q1Inv * q0); - Quaternion p2 = GetQuatLog(q1Inv * q2); - Quaternion sum = new Quaternion(-0.25f * (p0.x + p2.x), -0.25f * (p0.y + p2.y), -0.25f * (p0.z + p2.z), -0.25f * (p0.w + p2.w)); - - return q1 * GetQuatExp(sum); - } - - /// - /// Smooths the input parameter t. - /// If less than k1 ir greater than k2, it uses a sin. - /// Between k1 and k2 it uses linear interp. - /// - public static float Ease(float t, float k1, float k2) - { - float f; float s; - - f = k1 * 2 / Mathf.PI + k2 - k1 + (1.0f - k2) * 2 / Mathf.PI; - - if (t < k1) - { - s = k1 * (2 / Mathf.PI) * (Mathf.Sin((t / k1) * Mathf.PI / 2 - Mathf.PI / 2) + 1); - } - else if (t < k2) - { - s = (2 * k1 / Mathf.PI + t - k1); - } - else - { - s = 2 * k1 / Mathf.PI + k2 - k1 + ((1 - k2) * (2 / Mathf.PI)) * Mathf.Sin(((t - k2) / (1.0f - k2)) * Mathf.PI / 2); - } - - return (s / f); - } - - /// - /// We need this because Quaternion.Slerp always uses the shortest arc. - /// - public static Quaternion Slerp(Quaternion p, Quaternion q, float t) - { - Quaternion ret; - - float fCos = Quaternion.Dot(p, q); - - if ((1.0f + fCos) > 0.00001) - { - float fCoeff0, fCoeff1; - - if ((1.0f - fCos) > 0.00001) - { - float omega = Mathf.Acos(fCos); - float invSin = 1.0f / Mathf.Sin(omega); - fCoeff0 = Mathf.Sin((1.0f - t) * omega) * invSin; - fCoeff1 = Mathf.Sin(t * omega) * invSin; - } - else - { - fCoeff0 = 1.0f - t; - fCoeff1 = t; - } - - ret.x = fCoeff0 * p.x + fCoeff1 * q.x; - ret.y = fCoeff0 * p.y + fCoeff1 * q.y; - ret.z = fCoeff0 * p.z + fCoeff1 * q.z; - ret.w = fCoeff0 * p.w + fCoeff1 * q.w; - } - else - { - float fCoeff0 = Mathf.Sin((1.0f - t) * Mathf.PI * 0.5f); - float fCoeff1 = Mathf.Sin(t * Mathf.PI * 0.5f); - - ret.x = fCoeff0 * p.x - fCoeff1 * p.y; - ret.y = fCoeff0 * p.y + fCoeff1 * p.x; - ret.z = fCoeff0 * p.z - fCoeff1 * p.w; - ret.w = p.z; - } - - return ret; - } - - // intersect_RayTriangle(): intersect a ray with a 3D triangle - // Input: a ray R, and 3 vector3 forming a triangle - // Output: *I = intersection point (when it exists) - // Return: null = no intersection - // RaycastHit = intersection - - // -1 = triangle is degenerate (a segment or point) - // 0 = disjoint (no intersect) - // 1 = intersect in unique point I1 - // 2 = are in the same plane - public static object IntersectRayTriangle(Ray ray, Vector3 v0, Vector3 v1, Vector3 v2, bool bidirectional) - { - Vector3 ab = v1 - v0; - Vector3 ac = v2 - v0; - - // Compute triangle normal. Can be precalculated or cached if - // intersecting multiple segments against the same triangle - Vector3 n = Vector3.Cross(ab, ac); - - // Compute denominator d. If d <= 0, segment is parallel to or points - // away from triangle, so exit early - float d = Vector3.Dot(-ray.direction, n); - if (d <= 0.0f) return null; - - // Compute intersection t value of pq with plane of triangle. A ray - // intersects iff 0 <= t. Segment intersects iff 0 <= t <= 1. Delay - // dividing by d until intersection has been found to pierce triangle - Vector3 ap = ray.origin - v0; - float t = Vector3.Dot(ap, n); - if ((t < 0.0f) && (!bidirectional)) return null; - //if (t > d) return null; // For segment; exclude this code line for a ray test - - // Compute barycentric coordinate components and test if within bounds - Vector3 e = Vector3.Cross(-ray.direction, ap); - float v = Vector3.Dot(ac, e); - if (v < 0.0f || v > d) return null; - - float w = -Vector3.Dot(ab, e); - if (w < 0.0f || v + w > d) return null; - - // Segment/ray intersects triangle. Perform delayed division and - // compute the last barycentric coordinate component - float ood = 1.0f / d; - t *= ood; - v *= ood; - w *= ood; - float u = 1.0f - v - w; - - RaycastHit hit = new RaycastHit(); - - hit.point = ray.origin + t * ray.direction; - hit.distance = t; - hit.barycentricCoordinate = new Vector3(u, v, w); - hit.normal = Vector3.Normalize(n); - - return hit; - } - - // Returns closest point on segment - // squaredDist = squared distance between the two closest points - // s = offset along segment - public static Vector3 ClosestPtSegmentRay(Vector3 p1, Vector3 q1, Ray ray, out float squaredDist, out float s, out Vector3 closestRay) - { - Vector3 p2 = ray.origin; - Vector3 q2 = ray.GetPoint(10000.0f); - - Vector3 d1 = q1 - p1; // Direction vector of segment S1 - Vector3 d2 = q2 - p2; // Direction vector of segment S2 - Vector3 r = p1 - p2; - float a = Vector3.Dot(d1, d1); // Squared length of segment S1, always nonnegative - float e = Vector3.Dot(d2, d2); // Squared length of segment S2, always nonnegative - float f = Vector3.Dot(d2, r); - - float t = 0.0f; - - // Check if either or both segments degenerate into points - if (a <= Mathf.Epsilon && e <= Mathf.Epsilon) - { - // Both segments degenerate into points - squaredDist = Vector3.Dot(p1 - p2, p1 - p2); - s = 0.0f; - closestRay = p2; - return p1; - } - - if (a <= Mathf.Epsilon) - { - // First segment degenerates into a point - s = 0.0f; - t = f / e; // s = 0 => t = (b*s + f) / e = f / e - t = Mathf.Clamp(t, 0.0f, 1.0f); - } - else - { - float c = Vector3.Dot(d1, r); - if (e <= Mathf.Epsilon) - { - // Second segment degenerates into a point - t = 0.0f; - s = Mathf.Clamp(-c / a, 0.0f, 1.0f); // t = 0 => s = (b*t - c) / a = -c / a - } - else - { - // The general nondegenerate case starts here - float b = Vector3.Dot(d1, d2); - float denom = a * e - b * b; // Always nonnegative - - // If segments not parallel, compute closest point on L1 to L2, and - // clamp to segment S1. Else pick arbitrary s (here 0) - if (denom != 0.0f) - { - s = Mathf.Clamp((b * f - c * e) / denom, 0.0f, 1.0f); - } - else s = 0.0f; - - // Compute point on L2 closest to S1(s) using - // t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e - t = (b * s + f) / e; - - // If t in [0,1] done. Else clamp t, recompute s for the new value - // of t using s = Dot((P2+D2*t)-P1,D1) / Dot(D1,D1)= (t*b - c) / a - // and clamp s to [0, 1] - if (t < 0.0f) - { - t = 0.0f; - s = Mathf.Clamp(-c / a, 0.0f, 1.0f); - } - else if (t > 1.0f) - { - t = 1.0f; - s = Mathf.Clamp((b - c) / a, 0.0f, 1.0f); - } - } - } - - Vector3 c1 = p1 + d1 * s; - Vector3 c2 = p2 + d2 * t; - squaredDist = Vector3.Dot(c1 - c2, c1 - c2); - closestRay = c2; - return c1; - } - - public static bool IntersectRaySphere(Ray ray, Vector3 sphereOrigin, float sphereRadius, ref float t, ref Vector3 q) - { - Vector3 m = ray.origin - sphereOrigin; - float b = Vector3.Dot(m, ray.direction); - float c = Vector3.Dot(m, m) - (sphereRadius * sphereRadius); - // Exit if r�s origin outside s (c > 0)and r pointing away from s (b > 0) - if ((c > 0.0f) && (b > 0.0f)) return false; - float discr = (b * b) - c; - - // A negative discriminant corresponds to ray missing sphere - if (discr < 0.0f) return false; - - // Ray now found to intersect sphere, compute smallest t value of intersection - t = -b - Mathf.Sqrt(discr); - - // If t is negative, ray started inside sphere so clamp t to zero - if (t < 0.0f) t = 0.0f; - q = ray.origin + t * ray.direction; - return true; - } - - // Closest point - public static bool ClosestPtRaySphere(Ray ray, Vector3 sphereOrigin, float sphereRadius, ref float t, ref Vector3 q) - { - Vector3 m = ray.origin - sphereOrigin; - float b = Vector3.Dot(m, ray.direction); - float c = Vector3.Dot(m, m) - (sphereRadius * sphereRadius); - // Exit if r�s origin outside s (c > 0)and r pointing away from s (b > 0) - if ((c > 0.0f) && (b > 0.0f)) - { - // ray origin is closest - t = 0.0f; - q = ray.origin; - return true; - } - - float discr = (b * b) - c; - - // A negative discriminant corresponds to ray missing sphere - if (discr < 0.0f) - { - discr = 0.0f; - } - - // Ray now found to intersect sphere, compute smallest t value of intersection - t = -b - Mathf.Sqrt(discr); - - // If t is negative, ray started inside sphere so clamp t to zero - if (t < 0.0f) t = 0.0f; - q = ray.origin + t * ray.direction; - return true; - } - } -} diff --git a/Editor/Mono/Utils/MenuUtils.cs b/Editor/Mono/Utils/MenuUtils.cs deleted file mode 100644 index f41528fd1a..0000000000 --- a/Editor/Mono/Utils/MenuUtils.cs +++ /dev/null @@ -1,71 +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 System.Collections.Generic; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class MenuUtils - { - public static void MenuCallback(object callbackObject) - { - MenuCallbackObject menuCallBackObject = callbackObject as MenuCallbackObject; - - if (menuCallBackObject.onBeforeExecuteCallback != null) - menuCallBackObject.onBeforeExecuteCallback(menuCallBackObject.menuItemPath, menuCallBackObject.temporaryContext, menuCallBackObject.userData); - - if (menuCallBackObject.temporaryContext != null) - { - EditorApplication.ExecuteMenuItemWithTemporaryContext(menuCallBackObject.menuItemPath, menuCallBackObject.temporaryContext); - } - else - { - EditorApplication.ExecuteMenuItem(menuCallBackObject.menuItemPath); - } - - if (menuCallBackObject.onAfterExecuteCallback != null) - menuCallBackObject.onAfterExecuteCallback(menuCallBackObject.menuItemPath, menuCallBackObject.temporaryContext, menuCallBackObject.userData); - } - - public static void ExtractSubMenuWithPath(string path, GenericMenu menu, string replacementPath, Object[] temporaryContext) - { - HashSet menusWithCommands = new HashSet(Unsupported.GetSubmenus(path)); - string[] menus = Unsupported.GetSubmenusIncludingSeparators(path); - for (int i = 0; i < menus.Length; i++) - { - string menuString = menus[i]; - string replacedMenuString = replacementPath + menuString.Substring(path.Length); - if (menusWithCommands.Contains(menuString)) - { - ExtractMenuItemWithPath(menuString, menu, replacedMenuString, temporaryContext, -1, null, null); - } - //else // Comment back in when GenericMenu can handle separators - // menu.AddSeparator(replacedMenuString); - } - } - - public static void ExtractMenuItemWithPath(string menuString, GenericMenu menu, string replacementMenuString, Object[] temporaryContext, int userData, Action onBeforeExecuteCallback, Action onAfterExecuteCallback) - { - MenuCallbackObject callbackObject = new MenuCallbackObject(); - callbackObject.menuItemPath = menuString; - callbackObject.temporaryContext = temporaryContext; - callbackObject.onBeforeExecuteCallback = onBeforeExecuteCallback; - callbackObject.onAfterExecuteCallback = onAfterExecuteCallback; - callbackObject.userData = userData; - menu.AddItem(new GUIContent(L10n.TrPath(replacementMenuString)), false, MenuCallback, callbackObject); - } - - private class MenuCallbackObject - { - public string menuItemPath; - public Object[] temporaryContext; - public Action onBeforeExecuteCallback; // - public Action onAfterExecuteCallback; // - public int userData; - } - } -} diff --git a/Editor/Mono/Utils/MetroCertificatePasswordWindow.cs b/Editor/Mono/Utils/MetroCertificatePasswordWindow.cs deleted file mode 100644 index 6eddac1699..0000000000 --- a/Editor/Mono/Utils/MetroCertificatePasswordWindow.cs +++ /dev/null @@ -1,129 +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 UnityEditor; - -namespace UnityEditor -{ - internal class MetroCertificatePasswordWindow : EditorWindow - { - private static readonly GUILayoutOption kLabelWidth = GUILayout.Width(110); - private static readonly GUILayoutOption kButtonWidth = GUILayout.Width(110); - private const float kSpace = 5; - private const char kPasswordChar = '\u25cf'; - private const string kPasswordId = "password"; - - private string path; - private string password; - private GUIContent message; - private GUIStyle messageStyle; - private string focus; - - public static void Show(string path) - { - var windows = (MetroCertificatePasswordWindow[])Resources.FindObjectsOfTypeAll(typeof(MetroCertificatePasswordWindow)); - var window = ((windows.Length > 0) ? windows[0] : ScriptableObject.CreateInstance()); - - window.path = path; - window.password = string.Empty; - window.message = GUIContent.none; - - window.messageStyle = new GUIStyle(GUI.skin.label); - window.messageStyle.fontStyle = FontStyle.Italic; - - window.focus = kPasswordId; - - if (windows.Length > 0) - { - window.Focus(); - } - else - { - window.titleContent = EditorGUIUtility.TrTextContent("Enter Windows Store Certificate Password"); - - window.position = new Rect(100, 100, 350, 90); - window.minSize = new Vector2(window.position.width, window.position.height); - window.maxSize = window.minSize; - - window.ShowUtility(); - } - } - - public void OnGUI() - { - var e = Event.current; - var close = false; - var enter = false; - - if (e.type == EventType.KeyDown) - { - close = (e.keyCode == KeyCode.Escape); - enter = ((e.keyCode == KeyCode.Return) || (e.keyCode == KeyCode.KeypadEnter)); - } - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Space(kSpace * 2); - - using (VerticalLayout.DoLayout()) - { - GUILayout.FlexibleSpace(); - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Label(EditorGUIUtility.TrTextContent("Password", "Certificate password."), kLabelWidth); - GUI.SetNextControlName(kPasswordId); - password = GUILayout.PasswordField(password, kPasswordChar); - } - - GUILayout.Space(kSpace * 2); - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Label(message, messageStyle); - - GUILayout.FlexibleSpace(); - - if (GUILayout.Button(EditorGUIUtility.TrTextContent("Ok"), kButtonWidth) || enter) - { - message = GUIContent.none; - - try - { - if (PlayerSettings.WSA.SetCertificate(path, password)) - { - close = true; - } - else - { - message = EditorGUIUtility.TrTextContent("Invalid password."); - } - } - catch (UnityException ex) - { - Debug.LogError(ex.Message); - } - } - } - - GUILayout.FlexibleSpace(); - } - - GUILayout.Space(kSpace * 2); - } - - if (close) - { - Close(); - } - else if (focus != null) - { - EditorGUI.FocusTextInControl(focus); - focus = null; - } - } - } -} diff --git a/Editor/Mono/Utils/MetroCreateTestCertificateWindow.cs b/Editor/Mono/Utils/MetroCreateTestCertificateWindow.cs deleted file mode 100644 index 2d63000e67..0000000000 --- a/Editor/Mono/Utils/MetroCreateTestCertificateWindow.cs +++ /dev/null @@ -1,231 +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.IO; -using System.Text.RegularExpressions; -using UnityEngine; -using UnityEditor; - -namespace UnityEditor -{ - internal sealed class HorizontalLayout : IDisposable - { - private static readonly HorizontalLayout instance = new HorizontalLayout(); - - public static IDisposable DoLayout() - { - GUILayout.BeginHorizontal(); - return instance; - } - - private HorizontalLayout() - { - } - - void IDisposable.Dispose() - { - GUILayout.EndHorizontal(); - } - } - internal sealed class VerticalLayout : IDisposable - { - private static readonly VerticalLayout instance = new VerticalLayout(); - - public static IDisposable DoLayout() - { - GUILayout.BeginVertical(); - return instance; - } - - private VerticalLayout() - { - } - - void IDisposable.Dispose() - { - GUILayout.EndVertical(); - } - } - - internal class MetroCreateTestCertificateWindow : EditorWindow - { - private static readonly GUILayoutOption kLabelWidth = GUILayout.Width(110); - private static readonly GUILayoutOption kButtonWidth = GUILayout.Width(110); - private const float kSpace = 5; - private const char kPasswordChar = '\u25cf'; - private const string kPublisherId = "publisher"; - private const string kPasswordId = "password"; - private const string kConfirmId = "confirm"; - - private string path; - private string publisher; - private string password; - private string confirm; - private GUIContent message; - private GUIStyle messageStyle; - private string focus; - - /*private static readonly Regex publisherRegex = new Regex(@"^[A-Za-z0-9\.\-]+$", (RegexOptions.Compiled | RegexOptions.CultureInvariant)); - - private static bool IsValidPublisher(string value) - { - return publisherRegex.IsMatch(value); - }*/ - - public static void Show(string publisher) - { - var windows = (MetroCreateTestCertificateWindow[])Resources.FindObjectsOfTypeAll(typeof(MetroCreateTestCertificateWindow)); - var window = ((windows.Length > 0) ? windows[0] : ScriptableObject.CreateInstance()); - - window.path = Path.Combine(Application.dataPath, "WSATestCertificate.pfx").Replace('\\', '/'); - window.publisher = publisher; - window.password = string.Empty; - window.confirm = window.password; - window.message = (File.Exists(window.path) ? EditorGUIUtility.TrTextContent("Current file will be overwritten.") : GUIContent.none); - - window.messageStyle = new GUIStyle(GUI.skin.label); - window.messageStyle.fontStyle = FontStyle.Italic; - - window.focus = kPublisherId; - - if (windows.Length > 0) - { - window.Focus(); - } - else - { - window.titleContent = EditorGUIUtility.TrTextContent("Create Test Certificate for Windows Store"); - - window.position = new Rect(100, 100, 350, 140); - window.minSize = new Vector2(window.position.width, window.position.height); - window.maxSize = window.minSize; - - window.ShowUtility(); - } - } - - public void OnGUI() - { - var e = Event.current; - var close = false; - var enter = false; - - if (e.type == EventType.KeyDown) - { - close = (e.keyCode == KeyCode.Escape); - enter = ((e.keyCode == KeyCode.Return) || (e.keyCode == KeyCode.KeypadEnter)); - } - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Space(kSpace * 2); - - using (VerticalLayout.DoLayout()) - { - GUILayout.FlexibleSpace(); - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Label(EditorGUIUtility.TrTextContent("Publisher", "Publisher of the package."), kLabelWidth); - GUI.SetNextControlName(kPublisherId); - publisher = GUILayout.TextField(publisher); - } - - GUILayout.Space(kSpace); - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Label(EditorGUIUtility.TrTextContent("Password", "Certificate password."), kLabelWidth); - GUI.SetNextControlName(kPasswordId); - password = GUILayout.PasswordField(password, kPasswordChar); - } - - GUILayout.Space(kSpace); - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Label(EditorGUIUtility.TrTextContent("Confirm password", "Re-enter certificate password."), kLabelWidth); - GUI.SetNextControlName(kConfirmId); - confirm = GUILayout.PasswordField(confirm, kPasswordChar); - } - - GUILayout.Space(kSpace * 2); - - using (HorizontalLayout.DoLayout()) - { - GUILayout.Label(message, messageStyle); - - GUILayout.FlexibleSpace(); - - if (GUILayout.Button(EditorGUIUtility.TrTextContent("Create"), kButtonWidth) || enter) - { - message = GUIContent.none; - - if (string.IsNullOrEmpty(publisher)) - { - message = EditorGUIUtility.TrTextContent("Publisher must be specified."); - focus = kPublisherId; - } - /*else if (!IsValidPublisher(publisher)) - { - message = EditorGUIUtility.TrTextContent("Invalid publisher."); - focus = kPublisherId; - }*/ - else if (password != confirm) - { - if (string.IsNullOrEmpty(confirm)) - { - message = EditorGUIUtility.TrTextContent("Confirm the password."); - focus = kConfirmId; - } - else - { - message = EditorGUIUtility.TrTextContent("Passwords do not match."); - password = string.Empty; - confirm = password; - focus = kPasswordId; - } - } - else - { - try - { - EditorUtility.WSACreateTestCertificate(path, publisher, password, true); - - AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); - - if (!PlayerSettings.WSA.SetCertificate(FileUtil.GetProjectRelativePath(path), password)) - { - message = EditorGUIUtility.TrTextContent("Invalid password."); - } - - close = true; - } - catch (UnityException ex) - { - Debug.LogError(ex.Message); - } - } - } - } - - GUILayout.FlexibleSpace(); - } - - GUILayout.Space(kSpace * 2); - } - - if (close) - { - Close(); - } - else if (focus != null) - { - EditorGUI.FocusTextInControl(focus); - focus = null; - } - } - } -} diff --git a/Editor/Mono/Utils/MonoInstallationFinder.cs b/Editor/Mono/Utils/MonoInstallationFinder.cs deleted file mode 100644 index a85ea382ec..0000000000 --- a/Editor/Mono/Utils/MonoInstallationFinder.cs +++ /dev/null @@ -1,65 +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.IO; -using UnityEngine; - -namespace UnityEditor.Utils -{ - class MonoInstallationFinder - { - public const string MonoInstallation = "Mono"; - public const string MonoBleedingEdgeInstallation = "MonoBleedingEdge"; - - public static string GetFrameWorksFolder() - { - var editorAppPath = FileUtil.NiceWinPath(EditorApplication.applicationPath); - if (Application.platform == RuntimePlatform.WindowsEditor) - return Path.Combine(Path.GetDirectoryName(editorAppPath), "Data"); - else if (Application.platform == RuntimePlatform.OSXEditor) - return Path.Combine(editorAppPath, "Contents"); - else // Linux...? - return Path.Combine(Path.GetDirectoryName(editorAppPath), "Data"); - } - - public static string GetProfileDirectory(string profile) - { - var monoprefix = GetMonoInstallation(); - return Path.Combine(monoprefix, Path.Combine("lib", Path.Combine("mono", profile))); - } - - public static string GetProfileDirectory(string profile, string monoInstallation) - { - var monoprefix = GetMonoInstallation(monoInstallation); - return Path.Combine(monoprefix, Path.Combine("lib", Path.Combine("mono", profile))); - } - - public static string GetProfilesDirectory(string monoInstallation) - { - var monoprefix = GetMonoInstallation(monoInstallation); - return Path.Combine(monoprefix, Path.Combine("lib", "mono")); - } - - public static string GetEtcDirectory(string monoInstallation) - { - var monoprefix = GetMonoInstallation(monoInstallation); - return Path.Combine(monoprefix, Path.Combine("etc", "mono")); - } - - public static string GetMonoInstallation() - { - return GetMonoInstallation(MonoInstallation); - } - - public static string GetMonoBleedingEdgeInstallation() - { - return GetMonoInstallation(MonoBleedingEdgeInstallation); - } - - public static string GetMonoInstallation(string monoName) - { - return Path.Combine(GetFrameWorksFolder(), monoName); - } - } -} diff --git a/Editor/Mono/Utils/NetCoreProgram.cs b/Editor/Mono/Utils/NetCoreProgram.cs deleted file mode 100644 index 2ee9f74814..0000000000 --- a/Editor/Mono/Utils/NetCoreProgram.cs +++ /dev/null @@ -1,114 +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.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using UnityEditor.Scripting.Compilers; -using UnityEditor.Utils; -using UnityEngine; -using Debug = UnityEngine.Debug; - -namespace UnityEditor.Scripting -{ - internal class NetCoreProgram : Program - { - public NetCoreProgram(string executable, string arguments, Action setupStartInfo) - { - if (!IsNetCoreAvailable()) - { - Debug.LogError("Creating NetCoreProgram, but IsNetCoreAvailable() == false; fix the caller!"); - // let it happen anyway to preserve previous behaviour - } - - var startInfo = CreateDotNetCoreStartInfoForArgs(CommandLineFormatter.PrepareFileName(executable) + " " + arguments); - - if (setupStartInfo != null) - setupStartInfo(startInfo); - - _process.StartInfo = startInfo; - } - - private static ProcessStartInfo CreateDotNetCoreStartInfoForArgs(string arguments) - { - var dotnetExe = Paths.Combine(GetSdkRoot(), "dotnet"); - if (Application.platform == RuntimePlatform.WindowsEditor) - dotnetExe = CommandLineFormatter.PrepareFileName(dotnetExe + ".exe"); - - var startInfo = new ProcessStartInfo - { - Arguments = arguments, - CreateNoWindow = true, - FileName = dotnetExe, - WorkingDirectory = Application.dataPath + "/..", - }; - - if (Application.platform == RuntimePlatform.OSXEditor) - { - // .NET Core needs to be able to find the newer openssl libraries that it requires on OSX - var nativeDepsPath = Path.Combine(Path.Combine(Path.Combine(GetNetCoreRoot(), "NativeDeps"), "osx"), "lib"); - - if (startInfo.EnvironmentVariables.ContainsKey("DYLD_LIBRARY_PATH")) - startInfo.EnvironmentVariables["DYLD_LIBRARY_PATH"] = string.Format("{0}:{1}", nativeDepsPath, startInfo.EnvironmentVariables["DYLD_LIBRARY_PATH"]); - else - startInfo.EnvironmentVariables.Add("DYLD_LIBRARY_PATH", nativeDepsPath); - } - - return startInfo; - } - - private static string GetSdkRoot() - { - return Path.Combine(GetNetCoreRoot(), "Sdk"); - } - - private static string GetNetCoreRoot() - { - return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "NetCore"); - } - - private static bool s_NetCoreAvailableChecked = false; - private static bool s_NetCoreAvailable = false; - public static bool IsNetCoreAvailable() - { - if (!s_NetCoreAvailableChecked) - { - s_NetCoreAvailableChecked = true; - - var startInfo = CreateDotNetCoreStartInfoForArgs("--version"); - var getVersionProg = new Program(startInfo); - try - { - getVersionProg.Start(); - } - catch (Exception ex) - { - Debug.LogWarningFormat("Disabling CoreCLR, got exception trying to run with --version: {0}", ex); - return false; - } - - getVersionProg.WaitForExit(5000); - if (!getVersionProg.HasExited) - { - getVersionProg.Kill(); - Debug.LogWarning("Disabling CoreCLR, timed out trying to run with --version"); - return false; - } - - if (getVersionProg.ExitCode != 0) - { - Debug.LogWarningFormat("Disabling CoreCLR, got non-zero exit code: {0}, stderr: '{1}'", - getVersionProg.ExitCode, getVersionProg.GetErrorOutputAsString()); - return false; - } - - s_NetCoreAvailable = true; - } - return s_NetCoreAvailable; - } - } -} diff --git a/Editor/Mono/Utils/ProcessOutputStreamReader.cs b/Editor/Mono/Utils/ProcessOutputStreamReader.cs deleted file mode 100644 index 705f254413..0000000000 --- a/Editor/Mono/Utils/ProcessOutputStreamReader.cs +++ /dev/null @@ -1,73 +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.Diagnostics; -using System.IO; -using System.Threading; - -namespace UnityEditor.Utils -{ - internal class ProcessOutputStreamReader - { - private readonly Func hostProcessExited; - private readonly StreamReader stream; - internal List lines; - private Thread thread; - - internal ProcessOutputStreamReader(Process p, StreamReader stream) : this(() => p.HasExited, stream) - { - } - - internal ProcessOutputStreamReader(Func hostProcessExited, StreamReader stream) - { - this.hostProcessExited = hostProcessExited; - this.stream = stream; - lines = new List(); - - thread = new Thread(ThreadFunc); - thread.Start(); - } - - private void ThreadFunc() - { - if (hostProcessExited()) return; - try - { - while (true) - { - if (stream.BaseStream == null) return; - string line = stream.ReadLine(); - if (line == null) - return; - lock (lines) - { - lines.Add(line); - } - } - } - catch (ObjectDisposedException) - { - // We have had this throw in a run on Katana in what appears to be a case of a very short running - // process exiting between the check to hostProcessExited() and the call to stream.ReadLine(); - // So catch this case to avoid this from happening again. - lock (lines) - { - lines.Add("Could not read output because an ObjectDisposedException was thrown."); - } - } - } - - internal string[] GetOutput() - { - if (hostProcessExited()) - thread.Join(); - lock (lines) - { - return lines.ToArray(); - } - } - } -} diff --git a/Editor/Mono/Utils/Program.cs b/Editor/Mono/Utils/Program.cs deleted file mode 100644 index c200bfd662..0000000000 --- a/Editor/Mono/Utils/Program.cs +++ /dev/null @@ -1,187 +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.Diagnostics; -using System.IO; - -namespace UnityEditor.Utils -{ - internal class Program : IDisposable - { - private ProcessOutputStreamReader _stdout; - private ProcessOutputStreamReader _stderr; - private Stream _stdin; - public Process _process; - - protected Program() - { - _process = new Process(); - } - - public Program(ProcessStartInfo si) - : this() - { - _process.StartInfo = si; - } - - public void Start() - { - Start(null); - } - - public void Start(EventHandler exitCallback) - { - if (exitCallback != null) - { - _process.EnableRaisingEvents = true; - _process.Exited += exitCallback; - } - - _process.StartInfo.RedirectStandardInput = true; - _process.StartInfo.RedirectStandardError = true; - _process.StartInfo.RedirectStandardOutput = true; - _process.StartInfo.UseShellExecute = false; - - _process.Start(); - _stdout = new ProcessOutputStreamReader(_process, _process.StandardOutput); - _stderr = new ProcessOutputStreamReader(_process, _process.StandardError); - _stdin = _process.StandardInput.BaseStream; - } - - public ProcessStartInfo GetProcessStartInfo() - { - return _process.StartInfo; - } - - public void LogProcessStartInfo() - { - if (_process != null) - LogProcessStartInfo(_process.StartInfo); - else - Console.WriteLine("Failed to retrieve process startInfo"); - } - - //please dont kill this code. - private static void LogProcessStartInfo(ProcessStartInfo si) - { - Console.WriteLine("Filename: " + si.FileName); - Console.WriteLine("Arguments: " + si.Arguments); - - foreach (DictionaryEntry envVar in si.EnvironmentVariables) - if (envVar.Key.ToString().StartsWith("MONO")) - Console.WriteLine("{0}: {1}", envVar.Key, envVar.Value); - - int responsefileindex = si.Arguments.IndexOf("Temp/UnityTempFile"); - Console.WriteLine("index: " + responsefileindex); - - if (responsefileindex > 0) - { - var responsefile = si.Arguments.Substring(responsefileindex); - Console.WriteLine("Responsefile: " + responsefile + " Contents: "); - Console.WriteLine(System.IO.File.ReadAllText(responsefile)); - } - } - - public string GetAllOutput() - { - var sb = new System.Text.StringBuilder(); - sb.AppendLine("stdout:"); - foreach (var s in GetStandardOutput()) - sb.AppendLine(s); - sb.AppendLine("stderr:"); - foreach (var s in GetErrorOutput()) - sb.AppendLine(s); - return sb.ToString(); - } - - public bool HasExited - { - get - { - if (_process == null) - throw new InvalidOperationException("You cannot call HasExited before calling Start"); - try - { - return _process.HasExited; - } - catch (InvalidOperationException) - { - return true; - } - } - } - - public int ExitCode - { - get { return _process.ExitCode; } - } - - public int Id - { - get { return _process.Id; } - } - - public void Dispose() - { - Kill(); - _process.Dispose(); - } - - public void Kill() - { - if (!HasExited) - { - _process.Kill(); - _process.WaitForExit(); - } - } - - public Stream GetStandardInput() - { - return _stdin; - } - - public string[] GetStandardOutput() - { - return _stdout.GetOutput(); - } - - public string GetStandardOutputAsString() - { - var output = GetStandardOutput(); - return GetOutputAsString(output); - } - - public string[] GetErrorOutput() - { - return _stderr.GetOutput(); - } - - public string GetErrorOutputAsString() - { - var output = GetErrorOutput(); - return GetOutputAsString(output); - } - - private static string GetOutputAsString(string[] output) - { - var sb = new System.Text.StringBuilder(); - foreach (var t in output) - sb.AppendLine(t); - return sb.ToString(); - } - - public void WaitForExit() - { - _process.WaitForExit(); - } - - public bool WaitForExit(int milliseconds) - { - return _process.WaitForExit(milliseconds); - } - } -} diff --git a/Editor/Mono/Utils/ProgressBarUtils.cs b/Editor/Mono/Utils/ProgressBarUtils.cs deleted file mode 100644 index 24a98fdd49..0000000000 --- a/Editor/Mono/Utils/ProgressBarUtils.cs +++ /dev/null @@ -1,109 +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; - -namespace UnityEditor -{ - // Class used as a callback handler for progress bar notifications. - // Supports clamping to a sub range of a complete process (defined from 0.0f to 1.0f). - // When using a ProgressHandler with a sub range, processes can refer to their local completion rate - // and the ProgressHandler will report back progress within that sub range. - internal class ProgressHandler - { - public delegate void ProgressCallback(string title, string message, float globalProgress); - private ProgressCallback m_ProgressCallback; - private string m_Title; - private float m_ProgressRangeMin; - private float m_ProgressRangeMax; - - public ProgressHandler(string title, ProgressCallback callback, float progressRangeMin = 0.0f, float progressRangeMax = 1.0f) - { - m_Title = title; - m_ProgressCallback += callback; - m_ProgressRangeMin = progressRangeMin; - m_ProgressRangeMax = progressRangeMax; - } - - private float CalcGlobalProcess(float localProcess) - { - return Mathf.Clamp(m_ProgressRangeMin * (1.0f - localProcess) + m_ProgressRangeMax * localProcess, 0.0f, 1.0f); - } - - public void OnProgress(string message, float progress) - { - m_ProgressCallback(m_Title, message, CalcGlobalProcess(progress)); - } - - public ProgressHandler SpawnFromLocalSubRange(float localRangeMin, float localRangeMax) - { - return new ProgressHandler(m_Title, m_ProgressCallback, CalcGlobalProcess(localRangeMin), CalcGlobalProcess(localRangeMax)); - } - } - - // A helper class that attaches to a ProgressHandler - // Supports queueing tasks which will automatically notify the ProgressHandler when executed - internal class ProgressTaskManager - { - private ProgressHandler m_Handler; - private List m_Tasks = new List(); - private int m_ProgressUpdatesForCurrentTask; - private int m_StartedTasks; - - public ProgressTaskManager(ProgressHandler handler) - { - m_Handler = handler; - } - - public void AddTask(Action task) - { - m_Tasks.Add(task); - } - - public void Run() - { - // Run should not be run within a previous run - System.Diagnostics.Debug.Assert(m_StartedTasks == 0); - - foreach (var task in m_Tasks) - { - m_StartedTasks++; - m_ProgressUpdatesForCurrentTask = 0; - task(); - } - } - - public void UpdateProgress(string message) - { - if (m_Handler != null) - { - // Get some movement of the bar, even for unknown number of progress updates - float taskProgress = 1.0f - Mathf.Pow(0.85f, m_ProgressUpdatesForCurrentTask); - int totalTasks = m_Tasks.Count; - if (totalTasks <= m_StartedTasks) - totalTasks = m_StartedTasks; - float taskStep = 1.0f / totalTasks; - float runProgress = (m_StartedTasks - 1) * taskStep + taskProgress * taskStep; - m_Handler.OnProgress(message, runProgress); - } - - m_ProgressUpdatesForCurrentTask++; - } - - public ProgressHandler SpawnProgressHandlerFromCurrentTask() - { - if (m_Handler != null) - { - int totalTasks = m_Tasks.Count; - float taskStep = 1.0f / totalTasks; - float minRange = (m_StartedTasks - 1) * taskStep; - float maxRange = m_StartedTasks * taskStep; - return m_Handler.SpawnFromLocalSubRange(minRange, maxRange); - } - return null; - } - } -} diff --git a/Editor/Mono/Utils/SimpleProfiler.cs b/Editor/Mono/Utils/SimpleProfiler.cs deleted file mode 100644 index 3faa890586..0000000000 --- a/Editor/Mono/Utils/SimpleProfiler.cs +++ /dev/null @@ -1,64 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - -//#define SIMPLE_PROFILER -using UnityEngine; -using UnityEditor; -using System.Collections.Generic; - -namespace UnityEditor -{ - // Simple profiler that can measure time spend inside code blocks. - // If the same code block is hit multiple times, the times are summed up. - // Measured blocks may be nested, although the profiler does not do anything intelligent with it. - // Ie. you can measure a big code block as well as smaller code blocks within it. - // All measured times are printed when calling PrintTimes, at which point the timer is also reset. - - // Note, out built-in profiler in Unity did not catch the code I needed to profile, - // hence I had to make this one. - internal class SimpleProfiler - { - // Lazy coding with parallel stacks - private static Stack m_Names = new Stack(); - private static Stack m_StartTime = new Stack(); - private static Dictionary m_Timers = new Dictionary(); - private static Dictionary m_Calls = new Dictionary(); - - [System.Diagnostics.Conditional("SIMPLE_PROFILER")] - public static void Begin(string label) - { - m_Names.Push(label); - m_StartTime.Push(Time.realtimeSinceStartup); - } - - [System.Diagnostics.Conditional("SIMPLE_PROFILER")] - public static void End() - { - string str = m_Names.Pop(); - float duration = (Time.realtimeSinceStartup - m_StartTime.Pop()); - if (m_Timers.ContainsKey(str)) - m_Timers[str] += duration; - else - m_Timers[str] = duration; - - if (m_Calls.ContainsKey(str)) - m_Calls[str] += 1; - else - m_Calls[str] = 1; - } - - [System.Diagnostics.Conditional("SIMPLE_PROFILER")] - public static void PrintTimes() - { - string str = "Measured execution times:\n----------------------------\n"; - foreach (KeyValuePair kvp in m_Timers) - str += string.Format("{0,6:0.0} ms: {1} in {2} calls\n", kvp.Value * 1000, kvp.Key, m_Calls[kvp.Key]); - Debug.Log(str); - m_Names.Clear(); - m_StartTime.Clear(); - m_Timers.Clear(); - m_Calls.Clear(); - } - } -} diff --git a/Editor/Mono/Utils/TickTimerHelper.cs b/Editor/Mono/Utils/TickTimerHelper.cs deleted file mode 100644 index fc67f3329d..0000000000 --- a/Editor/Mono/Utils/TickTimerHelper.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 - -namespace UnityEditor -{ - internal class TickTimerHelper - { - double m_NextTick; - double m_Interval; - - public TickTimerHelper(double intervalBetweenTicksInSeconds) - { - m_Interval = intervalBetweenTicksInSeconds; - } - - public bool DoTick() - { - if (EditorApplication.timeSinceStartup > m_NextTick) - { - m_NextTick = EditorApplication.timeSinceStartup + m_Interval; - return true; - } - return false; - } - - public void Reset() - { - m_NextTick = 0; - } - } -} diff --git a/Editor/Mono/Utils/TimeAgo.cs b/Editor/Mono/Utils/TimeAgo.cs deleted file mode 100644 index 30dafb4119..0000000000 --- a/Editor/Mono/Utils/TimeAgo.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 System; - -namespace UnityEditor -{ - internal static class TimeAgo - { - const int k_Second = 1; - const int k_Minute = 60 * k_Second; - const int k_Hour = 60 * k_Minute; - const int k_Day = 24 * k_Hour; - const int k_Month = 30 * k_Day; - - public static string GetString(DateTime dateTime) - { - var ts = new TimeSpan(DateTime.UtcNow.Ticks - dateTime.ToUniversalTime().Ticks); - double delta = Math.Abs(ts.TotalSeconds); - - if (delta < 1 * k_Minute) - return "less than a minute ago"; - - if (delta < 2 * k_Minute) - return "a minute ago"; - - if (delta < 45 * k_Minute) - return ts.Minutes + " minutes ago"; - - if (delta < 90 * k_Minute) - return "an hour ago"; - - if (delta < 24 * k_Hour) - return ts.Hours + " hours ago"; - - if (delta < 48 * k_Hour) - return "yesterday"; - - if (delta < 30 * k_Day) - return ts.Days + " days ago"; - - if (delta < 12 * k_Month) - { - int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); - return months <= 1 ? "a month ago" : months + " months ago"; - } - - int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); - return years <= 1 ? "one year ago" : years + " years ago"; - } - } -} diff --git a/Editor/Mono/Utils/TimeHelper.cs b/Editor/Mono/Utils/TimeHelper.cs deleted file mode 100644 index 4124908c2f..0000000000 --- a/Editor/Mono/Utils/TimeHelper.cs +++ /dev/null @@ -1,25 +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 -{ - // Silly helper to get proper deltatime inside events - internal struct TimeHelper - { - public float deltaTime; - long lastTime; - - public void Begin() - { - lastTime = System.DateTime.Now.Ticks; - } - - public float Update() - { - deltaTime = (System.DateTime.Now.Ticks - lastTime) / 10000000.0f; - lastTime = System.DateTime.Now.Ticks; - return deltaTime; - } - } -} diff --git a/Editor/Mono/Utils/UnityEventTools.cs b/Editor/Mono/Utils/UnityEventTools.cs deleted file mode 100644 index 68f0d0f074..0000000000 --- a/Editor/Mono/Utils/UnityEventTools.cs +++ /dev/null @@ -1,171 +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.Events; -using Object = UnityEngine.Object; - -namespace UnityEditor.Events -{ - public static class UnityEventTools - { - public static void AddPersistentListener(UnityEventBase unityEvent) - { - unityEvent.AddPersistentListener(); - } - - public static void RemovePersistentListener(UnityEventBase unityEvent, int index) - { - unityEvent.RemovePersistentListener(index); - } - - // Add functions - public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) - { - unityEvent.AddPersistentListener(call); - } - - public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) - { - unityEvent.AddPersistentListener(call); - } - - public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) - { - unityEvent.AddPersistentListener(call); - } - - public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) - { - unityEvent.AddPersistentListener(call); - } - - public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) - { - unityEvent.AddPersistentListener(call); - } - - // register functions - public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) - { - unityEvent.RegisterPersistentListener(index, call); - } - - public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) - { - unityEvent.RegisterPersistentListener(index, call); - } - - public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) - { - unityEvent.RegisterPersistentListener(index, call); - } - - public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) - { - unityEvent.RegisterPersistentListener(index, call); - } - - public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) - { - unityEvent.RegisterPersistentListener(index, call); - } - - // Removal functions - public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) - { - unityEvent.RemovePersistentListener(call.Target as Object, call.Method); - } - - public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) - { - unityEvent.RemovePersistentListener(call.Target as Object, call.Method); - } - - public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) - { - unityEvent.RemovePersistentListener(call.Target as Object, call.Method); - } - - public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) - { - unityEvent.RemovePersistentListener(call.Target as Object, call.Method); - } - - public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) - { - unityEvent.RemovePersistentListener(call.Target as Object, call.Method); - } - - public static void UnregisterPersistentListener(UnityEventBase unityEvent, int index) - { - unityEvent.UnregisterPersistentListener(index); - } - - // void - public static void AddVoidPersistentListener(UnityEventBase unityEvent, UnityAction call) - { - unityEvent.AddVoidPersistentListener(call); - } - - public static void RegisterVoidPersistentListener(UnityEventBase unityEvent, int index, UnityAction call) - { - unityEvent.RegisterVoidPersistentListener(index, call); - } - - // int - public static void AddIntPersistentListener(UnityEventBase unityEvent, UnityAction call, int argument) - { - unityEvent.AddIntPersistentListener(call, argument); - } - - public static void RegisterIntPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, int argument) - { - unityEvent.RegisterIntPersistentListener(index, call, argument); - } - - // float - public static void AddFloatPersistentListener(UnityEventBase unityEvent, UnityAction call, float argument) - { - unityEvent.AddFloatPersistentListener(call, argument); - } - - public static void RegisterFloatPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, float argument) - { - unityEvent.RegisterFloatPersistentListener(index, call, argument); - } - - // bool - public static void AddBoolPersistentListener(UnityEventBase unityEvent, UnityAction call, bool argument) - { - unityEvent.AddBoolPersistentListener(call, argument); - } - - public static void RegisterBoolPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, bool argument) - { - unityEvent.RegisterBoolPersistentListener(index, call, argument); - } - - // string - public static void AddStringPersistentListener(UnityEventBase unityEvent, UnityAction call, string argument) - { - unityEvent.AddStringPersistentListener(call, argument); - } - - public static void RegisterStringPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, string argument) - { - unityEvent.RegisterStringPersistentListener(index, call, argument); - } - - // object - public static void AddObjectPersistentListener(UnityEventBase unityEvent, UnityAction call, T argument) where T : Object - { - unityEvent.AddObjectPersistentListener(call, argument); - } - - public static void RegisterObjectPersistentListener(UnityEventBase unityEvent, int index, UnityAction call, T argument) where T : Object - { - unityEvent.RegisterObjectPersistentListener(index, call, argument); - } - } -} diff --git a/Editor/Mono/VersionControl/Common/VCAsset.cs b/Editor/Mono/VersionControl/Common/VCAsset.cs deleted file mode 100644 index 47e71f0bcf..0000000000 --- a/Editor/Mono/VersionControl/Common/VCAsset.cs +++ /dev/null @@ -1,162 +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.VersionControl -{ - public partial class Asset - { - internal static bool IsState(Asset.States isThisState, Asset.States partOfThisState) - { - return (isThisState & partOfThisState) != 0; - } - - public bool IsState(Asset.States state) - { - return IsState(this.state, state); - } - - public bool IsOneOfStates(Asset.States[] states) - { - foreach (Asset.States st in states) - { - if ((this.state & st) != 0) return true; - } - return false; - } - - internal bool IsUnderVersionControl - { - get { return IsState(Asset.States.Synced) || IsState(Asset.States.OutOfSync) || IsState(Asset.States.AddedLocal); } - } - - public void Edit() - { - UnityEngine.Object load = Load(); - - if (load != null) - AssetDatabase.OpenAsset(load); - } - - public UnityEngine.Object Load() - { - if (state == States.DeletedLocal || isMeta) - { - return null; - } - - // Standard asset loading - return AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Object)); - } - - internal static string StateToString(Asset.States state) - { - if (IsState(state, Asset.States.AddedLocal)) - return "Added Local"; - - if (IsState(state, Asset.States.AddedRemote)) - return "Added Remote"; - - if (IsState(state, Asset.States.CheckedOutLocal) && !IsState(state, Asset.States.LockedLocal)) - return "Checked Out Local"; - - if (IsState(state, Asset.States.CheckedOutRemote) && !IsState(state, Asset.States.LockedRemote)) - return "Checked Out Remote"; - - if (IsState(state, Asset.States.Conflicted)) - return "Conflicted"; - - if (IsState(state, Asset.States.DeletedLocal)) - return "Deleted Local"; - - if (IsState(state, Asset.States.DeletedRemote)) - return "Deleted Remote"; - - if (IsState(state, Asset.States.Local)) - return "Local"; - - if (IsState(state, Asset.States.LockedLocal)) - return "Locked Local"; - - if (IsState(state, Asset.States.LockedRemote)) - return "Locked Remote"; - - if (IsState(state, Asset.States.OutOfSync)) - return "Out Of Sync"; - - if (IsState(state, Asset.States.Updating)) - return "Updating Status"; - - return ""; - } - - internal static string AllStateToString(Asset.States state) - { - var sb = new System.Text.StringBuilder(); - - if (IsState(state, Asset.States.AddedLocal)) - sb.AppendLine("Added Local"); - - if (IsState(state, Asset.States.AddedRemote)) - sb.AppendLine("Added Remote"); - - if (IsState(state, Asset.States.CheckedOutLocal)) - sb.AppendLine("Checked Out Local"); - - if (IsState(state, Asset.States.CheckedOutRemote)) - sb.AppendLine("Checked Out Remote"); - - if (IsState(state, Asset.States.Conflicted)) - sb.AppendLine("Conflicted"); - - if (IsState(state, Asset.States.DeletedLocal)) - sb.AppendLine("Deleted Local"); - - if (IsState(state, Asset.States.DeletedRemote)) - sb.AppendLine("Deleted Remote"); - - if (IsState(state, Asset.States.Local)) - sb.AppendLine("Local"); - - if (IsState(state, Asset.States.LockedLocal)) - sb.AppendLine("Locked Local"); - - if (IsState(state, Asset.States.LockedRemote)) - sb.AppendLine("Locked Remote"); - - if (IsState(state, Asset.States.OutOfSync)) - sb.AppendLine("Out Of Sync"); - - if (IsState(state, Asset.States.Synced)) - sb.AppendLine("Synced"); - - if (IsState(state, Asset.States.Missing)) - sb.AppendLine("Missing"); - - if (IsState(state, Asset.States.ReadOnly)) - sb.AppendLine("ReadOnly"); - - return sb.ToString(); - } - - internal string AllStateToString() - { - return AllStateToString(this.state); - } - - internal string StateToString() - { - return StateToString(this.state); - } - - public string prettyPath - { - get - { - return path; - } - } - } -} diff --git a/Editor/Mono/VersionControl/Common/VCAssetList.cs b/Editor/Mono/VersionControl/Common/VCAssetList.cs deleted file mode 100644 index f73b8ef34c..0000000000 --- a/Editor/Mono/VersionControl/Common/VCAssetList.cs +++ /dev/null @@ -1,85 +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.Collections.Generic; - -namespace UnityEditor.VersionControl -{ - // A class which encapsualtes a list of VC assets. This class was made to add some extra functionaility - // for filtering and counting items in the list of certain types. - public class AssetList : List - { - public AssetList() {} - public AssetList(AssetList src) - { - // Deep Copy - //foreach (Asset asset in src) - // Add(new Asset(asset)); - } - - // Filter a list of assets by a given set of states - public AssetList Filter(bool includeFolder, params Asset.States[] states) - { - AssetList filter = new AssetList(); - - if (includeFolder == false && (states == null || states.Length == 0)) - return filter; - - foreach (Asset asset in this) - { - if (asset.isFolder) - { - if (includeFolder) - filter.Add(asset); - } - else - { - if (asset.IsOneOfStates(states)) - { - filter.Add(asset); - } - } - } - - return filter; - } - - // Count the list of assets by given a set of states. - // TODO: This is called quite often so it may be an idea to cache this - public int FilterCount(bool includeFolder, params Asset.States[] states) - { - int count = 0; - - if (includeFolder == false && states == null) - return this.Count; - - foreach (Asset asset in this) - { - if (asset.isFolder) - ++count; - else - { - if (asset.IsOneOfStates(states)) - { - ++count; - } - } - } - - return count; - } - - // Create an optimised list of assets by removing children of folders in the same list - public AssetList FilterChildren() - { - AssetList unique = new AssetList(); - unique.AddRange(this); - - foreach (Asset asset in this) - unique.RemoveAll(p => p.IsChildOf(asset)); - - return unique; - } - } -} diff --git a/Editor/Mono/VersionControl/Common/VCChangeSet.cs b/Editor/Mono/VersionControl/Common/VCChangeSet.cs deleted file mode 100644 index c30a565e79..0000000000 --- a/Editor/Mono/VersionControl/Common/VCChangeSet.cs +++ /dev/null @@ -1,36 +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.VersionControl -{ - public partial class ChangeSet - { - public static string defaultID = "-1"; - - public ChangeSet() - { - InternalCreate(); - } - - public ChangeSet(string description) - { - InternalCreateFromString(description); - } - - public ChangeSet(string description, string revision) - { - InternalCreateFromStringString(description, revision); - } - - public ChangeSet(ChangeSet other) - { - InternalCopyConstruct(other); - } - - ~ChangeSet() - { - Dispose(); - } - } -} diff --git a/Editor/Mono/VersionControl/Common/VCChangeSets.cs b/Editor/Mono/VersionControl/Common/VCChangeSets.cs deleted file mode 100644 index da803255ab..0000000000 --- a/Editor/Mono/VersionControl/Common/VCChangeSets.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 - -using System.Collections.Generic; - -namespace UnityEditor.VersionControl -{ - public class ChangeSets : List - { - } -} diff --git a/Editor/Mono/VersionControl/Common/VCMessage.cs b/Editor/Mono/VersionControl/Common/VCMessage.cs deleted file mode 100644 index 960c12c142..0000000000 --- a/Editor/Mono/VersionControl/Common/VCMessage.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 UnityEngine; - -namespace UnityEditor.VersionControl -{ - // Shared message class to give plugin messages consistency - public partial class Message - { - public void Show() - { - Message.Info(message); - } - - private static void Info(string message) - { - Debug.Log("Version control:\n" + message); - } - } -} diff --git a/Editor/Mono/VersionControl/Common/VCProvider.cs b/Editor/Mono/VersionControl/Common/VCProvider.cs deleted file mode 100644 index 6e9a2dd22c..0000000000 --- a/Editor/Mono/VersionControl/Common/VCProvider.cs +++ /dev/null @@ -1,374 +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; -namespace UnityEditor.VersionControl -{ - [System.Flags] - public enum CheckoutMode { Asset = 1, Meta = 2, Both = 3, Exact = 4 }; - - [System.Flags] - public enum ResolveMethod { UseMine = 1, UseTheirs = 2, UseMerged }; - - [System.Flags] - public enum MergeMethod - { - MergeNone = 0, - MergeAll = 1, - [System.Obsolete("This member is no longer supported (UnityUpgradable) -> MergeNone", true)] - MergeNonConflicting = 2 - }; - - [System.Flags] - public enum OnlineState { Updating = 0, Online = 1, Offline = 2 }; - - [System.Flags] - public enum RevertMode { Normal = 0, Unchanged = 1, KeepModifications = 2 }; - - [System.Flags] - public enum FileMode { None = 0, Binary = 1, Text = 2 }; - - public partial class Provider - { - //*Undocumented - static internal Asset CacheStatus(string assetPath) - { - return Internal_CacheStatus(assetPath); - } - - static public Task Status(AssetList assets) - { - return Internal_Status(assets.ToArray(), true); - } - - static public Task Status(Asset asset) - { - return Internal_Status(new Asset[] { asset }, true); - } - - static public Task Status(AssetList assets, bool recursively) - { - return Internal_Status(assets.ToArray(), recursively); - } - - static public Task Status(Asset asset, bool recursively) - { - return Internal_Status(new Asset[] { asset }, recursively); - } - - static public Task Status(string[] assets) - { - return Internal_StatusStrings(assets, true); - } - - static public Task Status(string[] assets, bool recursively) - { - return Internal_StatusStrings(assets, recursively); - } - - static public Task Status(string asset) - { - return Internal_StatusStrings(new string[] { asset }, true); - } - - static public Task Status(string asset, bool recursively) - { - return Internal_StatusStrings(new string[] { asset }, recursively); - } - - static public Task Move(string from, string to) - { - return Internal_MoveAsStrings(from, to); - } - - static public bool CheckoutIsValid(AssetList assets) - { - return CheckoutIsValid(assets, CheckoutMode.Exact); - } - - static public bool CheckoutIsValid(AssetList assets, CheckoutMode mode) - { - return Internal_CheckoutIsValid(assets.ToArray(), mode); - } - - static public Task Checkout(AssetList assets, CheckoutMode mode) - { - return Internal_Checkout(assets.ToArray(), mode); - } - - static public Task Checkout(string[] assets, CheckoutMode mode) - { - return Internal_CheckoutStrings(assets, mode); - } - - static public Task Checkout(UnityEngine.Object[] assets, CheckoutMode mode) - { - AssetList assetList = new AssetList(); - foreach (Object o in assets) - { - string path = AssetDatabase.GetAssetPath(o); - Asset asset = GetAssetByPath(path); - assetList.Add(asset); - } - - return Internal_Checkout(assetList.ToArray(), mode); - } - - static public bool CheckoutIsValid(Asset asset) - { - return CheckoutIsValid(asset, CheckoutMode.Exact); - } - - static public bool CheckoutIsValid(Asset asset, CheckoutMode mode) - { - return Internal_CheckoutIsValid(new Asset[] { asset }, mode); - } - - static public Task Checkout(Asset asset, CheckoutMode mode) - { - return Internal_Checkout(new Asset[] { asset }, mode); - } - - static public Task Checkout(string asset, CheckoutMode mode) - { - return Internal_CheckoutStrings(new string[] { asset }, mode); - } - - static public Task Checkout(UnityEngine.Object asset, CheckoutMode mode) - { - string path = AssetDatabase.GetAssetPath(asset); - Asset vcasset = GetAssetByPath(path); - return Internal_Checkout(new Asset[] { vcasset }, mode); - } - - //*Undocumented - static internal bool PromptAndCheckoutIfNeeded(string[] assets, string promptIfCheckoutIsNeeded) - { - return Internal_PromptAndCheckoutIfNeeded(assets, promptIfCheckoutIsNeeded); - } - - static public Task Delete(string assetProjectPath) - { - return Internal_DeleteAtProjectPath(assetProjectPath); - } - - static public Task Delete(AssetList assets) - { - return Internal_Delete(assets.ToArray()); - } - - static public Task Delete(Asset asset) - { - return Internal_Delete(new Asset[] { asset }); - } - - static public bool AddIsValid(AssetList assets) - { - return Internal_AddIsValid(assets.ToArray()); - } - - static public Task Add(AssetList assets, bool recursive) - { - return Internal_Add(assets.ToArray(), recursive); - } - - static public Task Add(Asset asset, bool recursive) - { - return Internal_Add(new Asset[] { asset }, recursive); - } - - static public bool DeleteChangeSetsIsValid(ChangeSets changesets) - { - return Internal_DeleteChangeSetsIsValid(changesets.ToArray()); - } - - static public Task DeleteChangeSets(ChangeSets changesets) - { - return Internal_DeleteChangeSets(changesets.ToArray()); - } - - static internal Task RevertChangeSets(ChangeSets changesets, RevertMode mode) - { - return Internal_RevertChangeSets(changesets.ToArray(), mode); - } - - static public bool SubmitIsValid(ChangeSet changeset, AssetList assets) - { - return Internal_SubmitIsValid(changeset, assets != null ? assets.ToArray() : null); - } - - static public Task Submit(ChangeSet changeset, AssetList list, string description, bool saveOnly) - { - return Internal_Submit(changeset, list != null ? list.ToArray() : null, description, saveOnly); - } - - static public bool DiffIsValid(AssetList assets) - { - Asset[] a = assets.ToArray(); - return Internal_DiffIsValid(a); - } - - static public Task DiffHead(AssetList assets, bool includingMetaFiles) - { - return Internal_DiffHead(assets.ToArray(), includingMetaFiles); - } - - static public bool ResolveIsValid(AssetList assets) - { - Asset[] a = assets.ToArray(); - return Internal_ResolveIsValid(a); - } - - static public Task Resolve(AssetList assets, ResolveMethod resolveMethod) - { - return Internal_Resolve(assets.ToArray(), resolveMethod); - } - - static public Task Merge(AssetList assets, MergeMethod method) - { - return Internal_Merge(assets.ToArray(), method); - } - - static public bool LockIsValid(AssetList assets) - { - return Internal_LockIsValid(assets.ToArray()); - } - - static public bool LockIsValid(Asset asset) - { - return Internal_LockIsValid(new Asset[] { asset }); - } - - static public bool UnlockIsValid(AssetList assets) - { - return Internal_UnlockIsValid(assets.ToArray()); - } - - static public bool UnlockIsValid(Asset asset) - { - return Internal_UnlockIsValid(new Asset[] { asset }); - } - - static public Task Lock(AssetList assets, bool locked) - { - return Internal_Lock(assets.ToArray(), locked); - } - - static public Task Lock(Asset asset, bool locked) - { - return Internal_Lock(new Asset[] { asset }, locked); - } - - static public bool RevertIsValid(AssetList assets, RevertMode mode) - { - return Internal_RevertIsValid(assets.ToArray(), mode); - } - - static public Task Revert(AssetList assets, RevertMode mode) - { - return Internal_Revert(assets.ToArray(), mode); - } - - static public bool RevertIsValid(Asset asset, RevertMode mode) - { - return Internal_RevertIsValid(new Asset[] { asset }, mode); - } - - static public Task Revert(Asset asset, RevertMode mode) - { - return Internal_Revert(new Asset[] { asset }, mode); - } - - static public bool GetLatestIsValid(AssetList assets) - { - return Internal_GetLatestIsValid(assets.ToArray()); - } - - static public bool GetLatestIsValid(Asset asset) - { - return Internal_GetLatestIsValid(new Asset[] { asset }); - } - - static public Task GetLatest(AssetList assets) - { - return Internal_GetLatest(assets.ToArray()); - } - - static public Task GetLatest(Asset asset) - { - return Internal_GetLatest(new Asset[] { asset }); - } - - static internal Task SetFileMode(AssetList assets, FileMode mode) - { - return Internal_SetFileMode(assets.ToArray(), mode); - } - - static internal Task SetFileMode(string[] assets, FileMode mode) - { - return Internal_SetFileModeStrings(assets, mode); - } - - static public Task ChangeSetDescription(ChangeSet changeset) - { - return Internal_ChangeSetDescription(changeset); - } - - static public Task ChangeSetStatus(ChangeSet changeset) - { - return Internal_ChangeSetStatus(changeset); - } - - static public Task ChangeSetStatus(string changesetID) - { - ChangeSet cl = new ChangeSet("", changesetID); - return Internal_ChangeSetStatus(cl); - } - - static public Task IncomingChangeSetAssets(ChangeSet changeset) - { - return Internal_IncomingChangeSetAssets(changeset); - } - - static public Task IncomingChangeSetAssets(string changesetID) - { - ChangeSet cl = new ChangeSet("", changesetID); - return Internal_IncomingChangeSetAssets(cl); - } - - static public Task ChangeSetMove(AssetList assets, ChangeSet changeset) - { - return Internal_ChangeSetMove(assets.ToArray(), changeset); - } - - static public Task ChangeSetMove(Asset asset, ChangeSet changeset) - { - return Internal_ChangeSetMove(new Asset[] { asset }, changeset); - } - - static public Task ChangeSetMove(AssetList assets, string changesetID) - { - ChangeSet cl = new ChangeSet("", changesetID); - return Internal_ChangeSetMove(assets.ToArray(), cl); - } - - static public Task ChangeSetMove(Asset asset, string changesetID) - { - ChangeSet cl = new ChangeSet("", changesetID); - return Internal_ChangeSetMove(new Asset[] { asset }, cl); - } - - static public AssetList GetAssetListFromSelection() - { - AssetList list = new AssetList(); - Asset[] assets = Internal_GetAssetArrayFromSelection(); - foreach (Asset asset in assets) - { - list.Add(asset); - } - - return list; - } - } -} diff --git a/Editor/Mono/VersionControl/Common/VCTask.cs b/Editor/Mono/VersionControl/Common/VCTask.cs deleted file mode 100644 index 99485be0f0..0000000000 --- a/Editor/Mono/VersionControl/Common/VCTask.cs +++ /dev/null @@ -1,39 +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.VersionControl -{ - public partial class Task - { - public AssetList assetList - { - get - { - AssetList list = new AssetList(); - Asset[] assets = Internal_GetAssetList(); - foreach (Asset asset in assets) - { - list.Add(asset); - } - - return list; - } - } - - public ChangeSets changeSets - { - get - { - ChangeSets list = new ChangeSets(); - ChangeSet[] changes = Internal_GetChangeSets(); - foreach (ChangeSet change in changes) - { - list.Add(change); - } - - return list; - } - } - } -} diff --git a/Editor/Mono/VersionControl/UI/VCListItem.cs b/Editor/Mono/VersionControl/UI/VCListItem.cs deleted file mode 100644 index 5e3bae9171..0000000000 --- a/Editor/Mono/VersionControl/UI/VCListItem.cs +++ /dev/null @@ -1,454 +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 UnityEditor; - -using UnityEditor.VersionControl; - -namespace UnityEditorInternal.VersionControl -{ - // This is a custom nested, double linked list. This provides flexibility to search quickly up and down - // the list. Particularly when parts of the list are expanded or not. - public class ListItem - { - ///@TODO: Violation of unity convention.... m_ on member variables... - - ListItem parent; - ListItem firstChild; - ListItem lastChild; - ListItem prev; - ListItem next; - - Texture icon; - string name; - int indent; - bool expanded; - bool exclusive; - bool dummy; - bool hidden; - bool accept; - object item; - string[] actions; - int identifier; - - public ListItem() - { - Clear(); - identifier = (int)(VCSProviderIdentifier.UnsetIdentifier); - } - - ~ListItem() - { - Clear(); - } - - public Texture Icon - { - get - { - Asset asset = item as Asset; - if (icon == null && asset != null) - return AssetDatabase.GetCachedIcon(asset.path); - - return icon; - } - set { icon = value; } - } - - public int Identifier - { - get - { - if (identifier == (int)(VCSProviderIdentifier.UnsetIdentifier)) - { - identifier = Provider.GenerateID(); - } - return identifier; - } - } - - public string Name - { - get { return name; } - set { name = value; } - } - - public int Indent - { - get { return indent; } - set { SetIntent(this, value); } - } - - public object Item - { - get { return item; } - set { item = value; } - } - - public Asset Asset - { - get { return item as Asset; } - set { item = value; } - } - - public bool HasPath() - { - Asset a = item as Asset; - return a != null && a.path != null; - } - - public ChangeSet Change - { - get { return item as ChangeSet; } - set { item = value; } - } - - public bool Expanded - { - get { return expanded; } - set { expanded = value; } - } - - public bool Exclusive - { - get { return exclusive; } - set { exclusive = value; } - } - - public bool Dummy - { - get { return dummy; } - set { dummy = value; } - } - - public bool Hidden - { - get { return hidden; } - set { hidden = value; } - } - - public bool HasChildren - { - get { return FirstChild != null; } - } - - public bool HasActions - { - get { return actions != null && actions.Length != 0; } - } - - public string[] Actions - { - get { return actions; } - set { actions = value; } - } - - public bool CanExpand - { - get - { - // Asset asset = item as Asset; - ChangeSet change = item as ChangeSet; - // return ((asset != null && asset.isFolder) || - // change != null || - // HasChildren); - return (change != null || HasChildren); - } - } - - public bool CanAccept - { - get { return accept; } - set { accept = value; } - } - - public int OpenCount - { - get - { - if (!Expanded) - return 0; - - int count = 0; - ListItem listItem = firstChild; - - while (listItem != null) - { - if (!listItem.Hidden) - { - ++count; - count += listItem.OpenCount; - } - - listItem = listItem.next; - } - - return count; - } - } - - public int ChildCount - { - get - { - int count = 0; - ListItem listItem = firstChild; - - while (listItem != null) - { - ++count; - listItem = listItem.next; - } - - return count; - } - } - - public ListItem Parent - { - get { return parent; } - } - - public ListItem FirstChild - { - get { return firstChild; } - } - - public ListItem LastChild - { - get { return lastChild; } - } - - public ListItem Prev - { - get { return prev; } - } - - public ListItem Next - { - get { return next; } - } - - public ListItem PrevOpen - { - get - { - // Previous sibbling or its last open child - ListItem enumChild = prev; - - while (enumChild != null) - { - if (enumChild.lastChild == null || !enumChild.Expanded) - return enumChild; - - enumChild = enumChild.lastChild; - } - - // Move to parent as long as its not the root - if (parent != null && parent.parent != null) - return parent; - - return null; - } - } - - public ListItem NextOpen - { - get - { - // Next child - if (Expanded && firstChild != null) - return firstChild; - - // Next sibbling - if (next != null) - return next; - - // Find a parent with a next - ListItem enumParent = parent; - - while (enumParent != null) - { - if (enumParent.Next != null) - return enumParent.Next; - - enumParent = enumParent.parent; - } - - return null; - } - } - - public ListItem PrevOpenSkip - { - get - { - ListItem listItem = PrevOpen; - while (listItem != null && (listItem.Dummy || listItem.Hidden)) - listItem = listItem.PrevOpen; - - return listItem; - } - } - - public ListItem NextOpenSkip - { - get - { - ListItem listItem = NextOpen; - while (listItem != null && (listItem.Dummy || listItem.Hidden)) - listItem = listItem.NextOpen; - - return listItem; - } - } - - public ListItem PrevOpenVisible - { - get - { - ListItem listItem = PrevOpen; - while (listItem != null && listItem.Hidden) - listItem = listItem.PrevOpen; - - return listItem; - } - } - - public ListItem NextOpenVisible - { - get - { - ListItem listItem = NextOpen; - while (listItem != null && listItem.Hidden) - listItem = listItem.NextOpen; - - return listItem; - } - } - - public bool IsChildOf(ListItem listItem) - { - ListItem it = Parent; - - while (it != null) - { - if (it == listItem) - return true; - - it = it.Parent; - } - - return false; - } - - public void Clear() - { - parent = null; - firstChild = null; - lastChild = null; - prev = null; - next = null; - - icon = null; - name = string.Empty; - indent = 0; - expanded = false; - exclusive = false; - dummy = false; - accept = false; - item = null; - } - - public void Add(ListItem listItem) - { - listItem.parent = this; - listItem.next = null; - listItem.prev = lastChild; - - // recursively update the indent - listItem.Indent = indent + 1; - - if (firstChild == null) - firstChild = listItem; - - if (lastChild != null) - lastChild.next = listItem; - - lastChild = listItem; - } - - public bool Remove(ListItem listItem) - { - if (listItem == null) - return false; - - // Can only remove children of this item - if (listItem.parent != this) - return false; - - if (listItem == firstChild) - firstChild = listItem.next; - - if (listItem == lastChild) - lastChild = listItem.prev; - - if (listItem.prev != null) - listItem.prev.next = listItem.next; - - if (listItem.next != null) - listItem.next.prev = listItem.prev; - - listItem.parent = null; - listItem.prev = null; - listItem.next = null; - - return true; - } - - public void RemoveAll() - { - ListItem en = firstChild; - while (en != null) - { - en.parent = null; - en = en.next; - } - - firstChild = null; - lastChild = null; - } - - public ListItem FindWithIdentifierRecurse(int inIdentifier) - { - if (Identifier == inIdentifier) - return this; - - ListItem listItem = firstChild; - while (listItem != null) - { - ListItem found = listItem.FindWithIdentifierRecurse(inIdentifier); - if (found != null) - return found; - - listItem = listItem.next; - } - return null; - } - - void SetIntent(ListItem listItem, int indent) - { - listItem.indent = indent; - - // Update children - ListItem en = listItem.FirstChild; - while (en != null) - { - SetIntent(en, indent + 1); - en = en.Next; - } - } - } -} diff --git a/Editor/Mono/VersionControl/UI/VCMenuChange.cs b/Editor/Mono/VersionControl/UI/VCMenuChange.cs deleted file mode 100644 index b64ade19ec..0000000000 --- a/Editor/Mono/VersionControl/UI/VCMenuChange.cs +++ /dev/null @@ -1,149 +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 UnityEditor; -using UnityEditor.VersionControl; - -namespace UnityEditorInternal.VersionControl -{ - // Menu used when right clicking on change lists only. As they are single select they will not get mixed up with asset selections. - public class ChangeSetContextMenu - { - // Get the selected change list. Only one valid at a time - static ChangeSet GetChangeSet(ChangeSets changes) - { - if (changes.Count == 0) - return null; - - return changes[0]; - } - - //[MenuItem ("CONTEXT/Change/Submit...", true)] - static bool SubmitTest(int userData) - { - ChangeSets sets = ListControl.FromID(userData).SelectedChangeSets; - return (sets.Count > 0 && Provider.SubmitIsValid(sets[0], null)); - } - - //[MenuItem ("CONTEXT/Change/Submit...", false, 100)] - static void Submit(int userData) - { - ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; - ChangeSet change = GetChangeSet(set); - - if (change != null) - WindowChange.Open(change, new AssetList(), true); - } - - //[MenuItem ("CONTEXT/Change/Revert...", true)] - static bool RevertTest(int userData) - { - ChangeSets list = ListControl.FromID(userData).SelectedChangeSets; - return list.Count > 0; - } - - //[MenuItem ("CONTEXT/Change/Revert...", false, 200)] - static void Revert(int userData) - { - ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; - ChangeSet change = GetChangeSet(set); - - if (change != null) - WindowRevert.Open(change); - } - - //[MenuItem ("CONTEXT/Change/Revert Unchanged", true)] - static bool RevertUnchangedTest(int userData) - { - ChangeSets sets = ListControl.FromID(userData).SelectedChangeSets; - return sets.Count > 0; - } - - //[MenuItem ("CONTEXT/Change/Revert Unchanged", false, 201)] - static void RevertUnchanged(int userData) - { - ChangeSets sets = ListControl.FromID(userData).SelectedChangeSets; - Provider.RevertChangeSets(sets, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); - Provider.InvalidateCache(); - } - - //[MenuItem ("CONTEXT/Change/Resolve Conflicts...", true)] - private static bool ResolveTest(int userData) - { - return ListControl.FromID(userData).SelectedChangeSets.Count > 0; - } - - //[MenuItem ("CONTEXT/Change/Resolve Conflicts...", false, 202)] - private static void Resolve(int userData) - { - ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; - ChangeSet change = GetChangeSet(set); - - if (change != null) - WindowResolve.Open(change); - } - - //[MenuItem ("CONTEXT/Change/New Changeset...", true)] - static bool NewChangeSetTest(int userDatad) - { - return Provider.isActive; - } - - //[MenuItem ("CONTEXT/Change/New Changeset...", false, 300)] - static void NewChangeSet(int userData) - { - WindowChange.Open(new AssetList(), false); - } - - //[MenuItem ("CONTEXT/Change/Edit Changeset...", true)] - static bool EditChangeSetTest(int userData) - { - ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; - if (set.Count == 0) return false; - ChangeSet change = GetChangeSet(set); - return (change.id != "-1" && Provider.SubmitIsValid(set[0], null)); - } - - //[MenuItem ("CONTEXT/Change/Edit Changeset...", false, 301)] - static void EditChangeSet(int userData) - { - ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; - ChangeSet change = GetChangeSet(set); - - if (change != null) - WindowChange.Open(change, new AssetList(), false); - } - - //[MenuItem ("CONTEXT/Change/Delete Empty Changeset", true)] - static bool DeleteChangeSetTest(int userData) - { - ListControl l = ListControl.FromID(userData); - ChangeSets set = l.SelectedChangeSets; - if (set.Count == 0) return false; - ChangeSet change = GetChangeSet(set); - - if (change.id == "-1") - return false; - - ListItem item = l.GetChangeSetItem(change); - // TODO: Make changelist cache nonmanaged side to fix this! - bool hasAssets = item != null && item.HasChildren && item.FirstChild.Asset != null && item.FirstChild.Name != ListControl.c_emptyChangeListMessage; - if (!hasAssets) - { - Task task = Provider.ChangeSetStatus(change); - task.Wait(); - hasAssets = task.assetList.Count != 0; - } - - return !hasAssets && Provider.DeleteChangeSetsIsValid(set); - } - - //[MenuItem ("CONTEXT/Change/Delete Empty Changeset", false, 302)] - static void DeleteChangeSet(int userData) - { - ChangeSets set = ListControl.FromID(userData).SelectedChangeSets; - Provider.DeleteChangeSets(set).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - } -} diff --git a/Editor/Mono/VersionControl/UI/VCMenuPending.cs b/Editor/Mono/VersionControl/UI/VCMenuPending.cs deleted file mode 100644 index 8b1436bf9d..0000000000 --- a/Editor/Mono/VersionControl/UI/VCMenuPending.cs +++ /dev/null @@ -1,146 +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 UnityEditor; - -using UnityEditor.VersionControl; - -namespace UnityEditorInternal.VersionControl -{ - // Standard menu used in the change list window when selecting assets. - public class PendingWindowContextMenu - { - //[MenuItem("CONTEXT/Pending/Submit...", true, 100)] - static bool SubmitTest(int userData) - { - return Provider.SubmitIsValid(null, ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Submit...", false, 100)] - static void Submit(int userData) - { - WindowChange.Open(ListControl.FromID(userData).SelectedAssets, true); - } - - //[MenuItem("CONTEXT/Pending/Revert...", true, 200)] - static bool RevertTest(int userData) - { - return Provider.RevertIsValid(ListControl.FromID(userData).SelectedAssets, RevertMode.Normal); - } - - //[MenuItem ("CONTEXT/Pending/Revert...", false, 200)] - static void Revert(int userData) - { - WindowRevert.Open(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Revert Unchanged", true, 201)] - static bool RevertUnchangedTest(int userData) - { - return Provider.RevertIsValid(ListControl.FromID(userData).SelectedAssets, RevertMode.Normal); - } - - //[MenuItem ("CONTEXT/Pending/Revert Unchanged", false, 201)] - static void RevertUnchanged(int userData) - { - AssetList list = ListControl.FromID(userData).SelectedAssets; - Provider.Revert(list, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); - Provider.Status(list); - } - - //[MenuItem("CONTEXT/Pending/Resolve Conflicts...", true, 202)] - static bool ResolveTest(int userData) - { - return Provider.ResolveIsValid(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Resolve Conflicts...", false, 202)] - static void Resolve(int userData) - { - WindowResolve.Open(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem("CONTEXT/Pending/Lock", true, 300)] - static bool LockTest(int userData) - { - return Provider.LockIsValid(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Lock", false, 300)] - static void Lock(int userData) - { - AssetList list = ListControl.FromID(userData).SelectedAssets; - Provider.Lock(list, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - - //[MenuItem("CONTEXT/Pending/Unlock", true, 301)] - static bool UnlockTest(int userData) - { - return Provider.UnlockIsValid(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Unlock", false, 301)] - static void Unlock(int userData) - { - AssetList list = ListControl.FromID(userData).SelectedAssets; - Provider.Lock(list, false).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - - //[MenuItem("CONTEXT/Pending/Diff/Against Head...", true, 400)] - static bool DiffHeadTest(int userData) - { - return Provider.DiffIsValid(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Diff/Against Head...", false, 400)] - static void DiffHead(int userData) - { - Provider.DiffHead(ListControl.FromID(userData).SelectedAssets, false); - } - - //[MenuItem("CONTEXT/Pending/Diff/Against Head with .meta...", true, 401)] - static bool DiffHeadWithMetaTest(int userData) - { - return Provider.DiffIsValid(ListControl.FromID(userData).SelectedAssets); - } - - //[MenuItem ("CONTEXT/Pending/Diff/Against Head with .meta...", false, 401)] - static void DiffHeadWithMeta(int userData) - { - Provider.DiffHead(ListControl.FromID(userData).SelectedAssets, true); - } - - //[MenuItem("CONTEXT/Pending/Reveal in Finder", true, 402)] - static bool ShowInExplorerTest(int userData) - { - return (ListControl.FromID(userData)).SelectedAssets.Count > 0; - } - - //[MenuItem ("CONTEXT/Pending/Reveal in Finder", false, 402)] - static void ShowInExplorer(int userData) - { - if (System.Environment.OSVersion.Platform == System.PlatformID.MacOSX || - System.Environment.OSVersion.Platform == System.PlatformID.Unix) - { - EditorApplication.ExecuteMenuItem("Assets/Reveal in Finder"); - } - else - { - EditorApplication.ExecuteMenuItem("Assets/Show in Explorer"); - } - } - - //[MenuItem("CONTEXT/Pending/New Changeset...", true, 501)] - static bool NewChangeSetTest(int userData) - { - return Provider.isActive; - } - - //[MenuItem ("CONTEXT/Pending/New Changeset...", false, 501)] - static void NewChangeSet(int userData) - { - WindowChange.Open(ListControl.FromID(userData).SelectedAssets, false); - } - } -} diff --git a/Editor/Mono/VersionControl/UI/VCMenuProject.cs b/Editor/Mono/VersionControl/UI/VCMenuProject.cs deleted file mode 100644 index e61a5863bc..0000000000 --- a/Editor/Mono/VersionControl/UI/VCMenuProject.cs +++ /dev/null @@ -1,213 +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 UnityEditor; - -using UnityEditor.VersionControl; - -namespace UnityEditorInternal.VersionControl -{ - // Menu popup for the main unity project window. Items are greyed out when not available to help with usability. - public class ProjectContextMenu - { - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Get Latest" menu handler - static bool GetLatestTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.GetLatestIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Get Latest" menu handler - static void GetLatest(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.GetLatest(list).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Submit..." menu handler - static bool SubmitTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.SubmitIsValid(null, selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Submit..." menu handler - static void Submit(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - WindowChange.Open(selected, true); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out" menu handler - static bool CheckOutTest(MenuCommand cmd) - { - // TODO: Retrieve CheckoutMode from settings (depends on asset type; native vs. imported) - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.CheckoutIsValid(selected, CheckoutMode.Both); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out" menu handler - static void CheckOut(MenuCommand cmd) - { - // TODO: Retrieve CheckoutMode from settings (depends on asset type; native vs. imported) - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Checkout(list, CheckoutMode.Both); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out (Other)/Only asset file" menu handler - static bool CheckOutAssetTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.CheckoutIsValid(selected, CheckoutMode.Asset); - } - - /// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out (Other)/Only asset file" menu handler - static void CheckOutAsset(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Checkout(list, CheckoutMode.Asset); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out (Other)/Only .meta file" menu handler - static bool CheckOutMetaTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.CheckoutIsValid(selected, CheckoutMode.Meta); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out (Other)/Only .meta file" menu handler - static void CheckOutMeta(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Checkout(list, CheckoutMode.Meta); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out (Other)/Both" menu handler - static bool CheckOutBothTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.CheckoutIsValid(selected, CheckoutMode.Both); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Check Out (Other)/Both" menu handler - static void CheckOutBoth(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Checkout(list, CheckoutMode.Both); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Mark Add" menu handler - static bool MarkAddTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.AddIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Mark Add" menu handler - static void MarkAdd(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Add(list, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - - /// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert..." menu handler - static bool RevertTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.RevertIsValid(selected, RevertMode.Normal); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert..." menu handler - static void Revert(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - WindowRevert.Open(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert Unchanged" menu handler - static bool RevertUnchangedTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.RevertIsValid(selected, RevertMode.Normal); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert Unchanged" menu handler - static void RevertUnchanged(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Revert(list, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); - Provider.Status(list); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff Against Head..." menu handler - static bool ResolveTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.ResolveIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff Against Head..." menu handler - static void Resolve(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - WindowResolve.Open(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Lock" menu handler - static bool LockTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.LockIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Lock" menu handler - static void Lock(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Lock(list, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Unlock" menu handler - static bool UnlockTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.UnlockIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Unlock" menu handler - static void Unlock(MenuCommand cmd) - { - AssetList list = Provider.GetAssetListFromSelection(); - Provider.Lock(list, false).SetCompletionAction(CompletionAction.UpdatePendingWindow); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff/Against Head..." menu handler - static bool DiffHeadTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.DiffIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff/Against Head..." menu handler - static void DiffHead(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - Provider.DiffHead(selected, false); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff/Against Head with .meta..." menu handler - static bool DiffHeadWithMetaTest(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - return Provider.enabled && Provider.DiffIsValid(selected); - } - - // Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff/Against Head with .meta..." menu handler - static void DiffHeadWithMeta(MenuCommand cmd) - { - AssetList selected = Provider.GetAssetListFromSelection(); - Provider.DiffHead(selected, true); - } - } -} diff --git a/Editor/Mono/VersionControl/UI/VCWindowCheckoutFailure.cs b/Editor/Mono/VersionControl/UI/VCWindowCheckoutFailure.cs deleted file mode 100644 index 60f6ccab5f..0000000000 --- a/Editor/Mono/VersionControl/UI/VCWindowCheckoutFailure.cs +++ /dev/null @@ -1,156 +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 UnityEditorInternal.VersionControl; - -namespace UnityEditor.VersionControl -{ - // Window allowing you to review files that could not be checked out. - internal class WindowCheckoutFailure : EditorWindow - { - private AssetList assetList = new AssetList(); - private ListControl checkoutSuccessList = new ListControl(); - private ListControl checkoutFailureList = new ListControl(); - - public void OnEnable() - { - position = new Rect(100, 100, 700, 230); - minSize = new Vector2(700, 230); - - checkoutSuccessList.ReadOnly = true; - checkoutFailureList.ReadOnly = true; - } - - public static void OpenIfCheckoutFailed(AssetList assets) - { - Object[] windows = Resources.FindObjectsOfTypeAll(typeof(WindowCheckoutFailure)); - WindowCheckoutFailure window = (windows.Length > 0 ? windows[0] as WindowCheckoutFailure : null); - - bool alreadyOpen = (window != null); - bool shouldOpen = alreadyOpen; - - if (!shouldOpen) - { - foreach (var asset in assets) - { - if (!asset.IsState(Asset.States.CheckedOutLocal)) - { - shouldOpen = true; - break; - } - } - } - - if (shouldOpen) - GetWindow().DoOpen(assets, alreadyOpen); - } - - private static WindowCheckoutFailure GetWindow() - { - return EditorWindow.GetWindow(true, "Version Control Check Out Failed"); - } - - private void DoOpen(AssetList assets, bool alreadyOpen) - { - if (alreadyOpen) - { - foreach (var asset in assets) - { - bool found = false; - int count = assetList.Count; - - for (int i = 0; i < count; i++) - { - if (assetList[i].path == asset.path) - { - found = true; - assetList[i] = asset; - break; - } - } - - if (!found) - assetList.Add(asset); - } - } - else - assetList.AddRange(assets); - - RefreshList(); - } - - private void RefreshList() - { - checkoutSuccessList.Clear(); - checkoutFailureList.Clear(); - - foreach (var asset in assetList) - { - if (asset.IsState(Asset.States.CheckedOutLocal)) - checkoutSuccessList.Add(null, asset.prettyPath, asset); - else - checkoutFailureList.Add(null, asset.prettyPath, asset); - } - - checkoutSuccessList.Refresh(); - checkoutFailureList.Refresh(); - - Repaint(); - } - - public void OnGUI() - { - float h = (position.height - 122) / 2; - - // TODO: Show the reason: Who has the exclusive lock? - GUILayout.Label("Some files could not be checked out:", EditorStyles.boldLabel); - - Rect r1 = new Rect(6, 40, position.width - 12, h); - GUILayout.BeginArea(r1); - GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); - GUILayout.EndArea(); - checkoutFailureList.OnGUI(new Rect(r1.x + 2, r1.y + 2, r1.width - 4, r1.height - 4), true); - - GUILayout.Space(20 + h); - GUILayout.Label("The following files were successfully checked out:", EditorStyles.boldLabel); - - Rect r2 = new Rect(6, 40 + h + 40, position.width - 12, h); - GUILayout.BeginArea(r2); - GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); - GUILayout.EndArea(); - checkoutSuccessList.OnGUI(new Rect(r2.x + 2, r2.y + 2, r2.width - 4, r2.height - 4), true); - - GUILayout.FlexibleSpace(); - GUILayout.BeginHorizontal(); - - EditorUserSettings.showFailedCheckout = !GUILayout.Toggle(!EditorUserSettings.showFailedCheckout, "Don't show this window again."); - - GUILayout.FlexibleSpace(); - - bool enabled = GUI.enabled; - GUI.enabled = checkoutFailureList.Size > 0; - - if (GUILayout.Button("Retry Check Out")) - Provider.Checkout(assetList, CheckoutMode.Exact); - - GUI.enabled = checkoutSuccessList.Size > 0; - - if (GUILayout.Button("Revert Unchanged")) - { - Provider.Revert(assetList, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); - Provider.Status(assetList); - Close(); - } - - GUI.enabled = enabled; - - if (GUILayout.Button("OK")) - Close(); - - GUILayout.EndHorizontal(); - GUILayout.Space(12); - } - } -} diff --git a/Editor/Mono/VersionControl/UI/VCWindowResolve.cs b/Editor/Mono/VersionControl/UI/VCWindowResolve.cs deleted file mode 100644 index 901c11cd75..0000000000 --- a/Editor/Mono/VersionControl/UI/VCWindowResolve.cs +++ /dev/null @@ -1,204 +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 UnityEditorInternal.VersionControl; - -namespace UnityEditor.VersionControl -{ - // Window allowing you to review files who will be resolved. As this may be throwing changes away this - // window gives you the opportunty to see what will change and if required the user can apply or cancel. - internal class WindowResolve : EditorWindow - { - ListControl resolveList = new ListControl(); - AssetList assetList = new AssetList(); - bool cancelled = false; - - public void OnEnable() - { - position = new Rect(100, 100, 650, 330); - minSize = new Vector2(650, 330); - } - - public void OnDisable() - { - if (!cancelled) - WindowPending.UpdateAllWindows(); - } - - // Resolve all files within a change list - static public void Open(ChangeSet change) - { - Task task = Provider.ChangeSetStatus(change); - task.Wait(); - WindowResolve win = GetWindow(); - win.DoOpen(task.assetList); - } - - // Resolve a list of files - static public void Open(AssetList assets) - { - Task task = Provider.Status(assets); - task.Wait(); - WindowResolve win = GetWindow(); - win.DoOpen(task.assetList); - } - - static private WindowResolve GetWindow() - { - return EditorWindow.GetWindow(true, "Version Control Resolve"); - } - - void DoOpen(AssetList resolve) - { - bool includeFolders = true; - assetList = resolve.Filter(includeFolders, Asset.States.Conflicted); - RefreshList(); - } - - void RefreshList() - { - resolveList.Clear(); - - bool first = true; - foreach (Asset it in assetList) - { - ListItem newItem = resolveList.Add(null, it.prettyPath, it); - if (first) - { - resolveList.SelectedSet(newItem); - first = false; - } - else - { - resolveList.SelectedAdd(newItem); - } - } - - // Show a dummy entry if there is nothing to do - if (assetList.Count == 0) - { - ChangeSet change = new ChangeSet("no files to resolve"); - ListItem item = resolveList.Add(null, change.description, change); - item.Dummy = true; - } - - resolveList.Refresh(); - Repaint(); - } - - void OnGUI() - { - cancelled = false; - GUILayout.Label("Conflicting files to resolve", EditorStyles.boldLabel); - GUILayout.FlexibleSpace(); - - // I would use GUIUtility.GetLastRect() here after the box but that seems to have wierd side effects. - Rect r1 = new Rect(6, 40, position.width - 12, position.height - 112); // 82 - GUILayout.BeginArea(r1); - GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); - GUILayout.EndArea(); - - bool repaint = resolveList.OnGUI(new Rect(r1.x + 2, r1.y + 2, r1.width - 4, r1.height - 4), true); - - GUILayout.FlexibleSpace(); - - GUILayout.BeginHorizontal(); - GUI.enabled = assetList.Count > 0; - - GUILayout.Label("Resolve selection by:"); - if (GUILayout.Button("using local version")) - { - AssetList selAssets = resolveList.SelectedAssets; - Provider.Resolve(selAssets, ResolveMethod.UseMine).Wait(); - AssetDatabase.Refresh(); - Close(); - } - - if (GUILayout.Button("using incoming version")) - { - AssetList selAssets = resolveList.SelectedAssets; - Provider.Resolve(selAssets, ResolveMethod.UseTheirs).Wait(); - AssetDatabase.Refresh(); - Close(); - } - - MergeMethod mergeMethod = MergeMethod.MergeNone; - if (GUILayout.Button("merging")) - { - mergeMethod = MergeMethod.MergeAll; - } - - if (mergeMethod != MergeMethod.MergeNone) - { - Task t = Provider.Merge(resolveList.SelectedAssets, mergeMethod); - t.Wait(); - - if (t.success) - { - t = Provider.Resolve(t.assetList, ResolveMethod.UseMerged); - t.Wait(); - if (t.success) - { - // Check that there are not more conflicts for the specified - // asset. This is possible in e.g. perforce where you handle - // one version conflict at a time. - t = Provider.Status(assetList); - t.Wait(); - - DoOpen(t.assetList); - - if (t.success && assetList.Count == 0) - Close(); - - // The view will be updated with the new conflicts - } - else - { - EditorUtility.DisplayDialog("Error resolving", "Error during resolve of files. Inspect log for details", "Close"); - AssetDatabase.Refresh(); - } - } - else - { - EditorUtility.DisplayDialog("Error merging", "Error during merge of files. Inspect log for details", "Close"); - AssetDatabase.Refresh(); - } - } - - GUILayout.FlexibleSpace(); - - GUILayout.EndHorizontal(); - GUILayout.Space(12); - - GUILayout.BeginHorizontal(); - GUILayout.FlexibleSpace(); - - GUI.enabled = true; - - if (GUILayout.Button("Cancel")) - { - cancelled = true; - Close(); - } - /* - GUI.enabled = assetList.Count > 0; - - - if (GUILayout.Button ("Resolve")) - { - Provider.Resolve (assetList, true).Wait (); - VCCache.Invalidate (assetList); - AssetDatabase.Refresh (); - Close (); - } - */ - GUILayout.EndHorizontal(); - GUILayout.Space(12); - //GUI.enabled = true; - if (repaint) - Repaint(); - } - } -} diff --git a/Editor/Mono/View.cs b/Editor/Mono/View.cs deleted file mode 100644 index 0e0ca1d58b..0000000000 --- a/Editor/Mono/View.cs +++ /dev/null @@ -1,249 +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.Scripting; -using UnityEditor; -using System.Collections; -using System.Linq; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; -using IntPtr = System.IntPtr; -using System; - -namespace UnityEditor -{ - [StructLayout(LayoutKind.Sequential)] - [UsedByNativeCode] - internal partial class View : ScriptableObject - { - internal virtual void Reflow() - { - foreach (View c in children) - c.Reflow(); - } - - internal string DebugHierarchy(int level) - { - string prefix = "", s = ""; - for (int i = 0; i < level; i++) - { - prefix = prefix + " "; - } - s = s + prefix + this.ToString() + " p:" + position; - if (children.Length > 0) - { - s += " {\n"; - foreach (View child in children) - { - s += child.DebugHierarchy(level + 2); - } - s += prefix + " }\n"; - } - else - s += "\n"; - return s; - } - - // Can be used by concrete subclasses to store C++ objects - [SerializeField] - MonoReloadableIntPtr m_ViewPtr; - [SerializeField] - View[] m_Children = new View[0]; - [System.NonSerialized] - View m_Parent; - [System.NonSerialized] - ContainerWindow m_Window; - - // Workaround for nonserialized stuff above - internal virtual void Initialize(ContainerWindow win) - { - SetWindow(win); - foreach (View i in m_Children) - { - i.m_Parent = this; - i.Initialize(win); - } - } - - [SerializeField] - Rect m_Position = new Rect(0, 0, 100, 100); - - [SerializeField] - internal Vector2 m_MinSize; - [SerializeField] - internal Vector2 m_MaxSize; - - public Vector2 minSize { get { return m_MinSize; } } - public Vector2 maxSize { get { return m_MaxSize; } } - - internal void SetMinMaxSizes(Vector2 min, Vector2 max) - { - if (minSize == min && maxSize == max) - { - return; - } - m_MinSize = min; - m_MaxSize = max; - if (m_Parent) - m_Parent.ChildrenMinMaxChanged(); - if (window && window.rootView == this) - window.SetMinMaxSizes(min, max); - } - - // Notification so other views can respond to this. - protected virtual void ChildrenMinMaxChanged() {} - - // Get all children of this view, using bottom-first recursion - public View[] allChildren - { - get - { - ArrayList arr = new ArrayList(); - foreach (View i in m_Children) - { - arr.AddRange(i.allChildren); - } - arr.Add(this); - return (View[])arr.ToArray(typeof(View)); - } - } - - private void __internalAwake() - { - hideFlags = HideFlags.DontSave; - } - - // position in the parent's space. - public Rect position - { - get { return m_Position; } - set { SetPosition(value); } - } - - // Override to resize subviews - protected virtual void SetPosition(Rect newPos) - { - m_Position = newPos; - } - - // Only set the position. - internal void SetPositionOnly(Rect newPos) - { - m_Position = newPos; - } - - // position in the window - public Rect windowPosition - { - get - { - if (m_Parent == null) - return position; - - Rect p = parent.windowPosition; - return new Rect(p.x + position.x, p.y + position.y, position.width, position.height); - } - } - - // absolute screen position - public Rect screenPosition - { - get - { - Rect r = windowPosition; - if (window != null) - { - Vector2 p = window.WindowToScreenPoint(Vector2.zero); - r.x += p.x; r.y += p.y; - } - return r; - } - } - - // Which window we're inside. don't set this directly, but change use AddChild, RemoveChild instead. - public ContainerWindow window { get { return m_Window; } } - // The parent view. - public View parent { get { return m_Parent; } } - - // please don't modify this array directly. use AddChild or set the child's parent view - public View[] children { get { return m_Children; } } - public int IndexOfChild(View child) - { - int i = 0; - foreach (View c in m_Children) - { - if (c == child) - return i; - i++; - } - return -1; - } - - protected virtual void OnDestroy() - { - foreach (View v in m_Children) - { - UnityEngine.Object.DestroyImmediate(v, true); - } - } - - // Add/remove child views - public void AddChild(View child) - {AddChild(child, m_Children.Length); } - public virtual void AddChild(View child, int idx) - { - System.Array.Resize(ref m_Children, m_Children.Length + 1); - if (idx != m_Children.Length - 1) - System.Array.Copy(m_Children, idx, m_Children, idx + 1, m_Children.Length - idx - 1); - - m_Children[idx] = child; - - if (child.m_Parent) - child.m_Parent.RemoveChild(child); - child.m_Parent = this; - child.SetWindowRecurse(window); - ChildrenMinMaxChanged(); - } - - public virtual void RemoveChild(View child) - { - int idx = System.Array.IndexOf(m_Children, child); - if (idx == -1) - Debug.LogError("Unable to remove child - it's not IN the view"); - else - RemoveChild(idx); - } - - public virtual void RemoveChild(int idx) - { - View child = m_Children[idx]; - child.m_Parent = null; - child.SetWindowRecurse(null); - System.Array.Copy(m_Children, idx + 1, m_Children, idx, m_Children.Length - idx - 1); - System.Array.Resize(ref m_Children, m_Children.Length - 1); - ChildrenMinMaxChanged(); - } - - protected virtual void SetWindow(ContainerWindow win) - { - m_Window = win; - } - - internal void SetWindowRecurse(ContainerWindow win) - { - SetWindow(win); - foreach (View i in m_Children) - { - i.SetWindowRecurse(win); - } - } - - virtual protected bool OnFocus() - { - return true; - } - } -} //namespace diff --git a/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs index 5392398c9f..998704dfca 100644 --- a/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs +++ b/Editor/Mono/VisualStudioIntegration/SolutionSynchronizer.cs @@ -18,8 +18,8 @@ using UnityEditorInternal; using UnityEditor.Scripting.Compilers; -using Mono.Cecil; using UnityEditor.Compilation; +using UnityEditor.Modules; namespace UnityEditor.VisualStudioIntegration { @@ -205,6 +205,12 @@ private bool ShouldSyncOnReimportedAsset(string asset) public void Sync() { + // Do not sync solution until all Unity extensions are registered and initialized. + // Otherwise Unity might emit errors when VSTU tries to generate the solution and + // get all managed extensions, which not yet initialized. + if (!InternalEditorUtility.IsUnityExtensionsInitialized()) + return; + SetupProjectSupportedExtensions(); bool externalCodeAlreadyGeneratedProjects = AssetPostprocessingInternal.OnPreGeneratingCSProjectFiles(); @@ -227,25 +233,44 @@ internal void GenerateAndWriteSolutionAndProjects(ScriptEditorUtility.ScriptEdit var allAssetProjectParts = GenerateAllAssetProjectParts(); - var responseFilePath = Path.Combine("Assets", MonoCSharpCompiler.ReponseFilename); + var responseFilePath = Path.Combine("Assets", MonoCSharpCompiler.ResponseFilename); - var responseFileData = ScriptCompilerBase.ParseResponseFileFromFile(Path.Combine(_projectDirectory, responseFilePath)); + var monoIslands = islands.ToList(); - if (responseFileData.Errors.Length > 0) - { - foreach (var error in responseFileData.Errors) - UnityEngine.Debug.LogErrorFormat("{0} Parse Error : {1}", responseFilePath, error); - } - SyncSolution(islands); - var allProjectIslands = RelevantIslandsForMode(islands, ModeForCurrentExternalEditor()).ToList(); + SyncSolution(monoIslands); + var allProjectIslands = RelevantIslandsForMode(monoIslands, ModeForCurrentExternalEditor()).ToList(); foreach (MonoIsland island in allProjectIslands) + { + var responseFileData = parseResponseFileData(island, responseFilePath); SyncProject(island, allAssetProjectParts, responseFileData, allProjectIslands); + } if (scriptEditor == ScriptEditorUtility.ScriptEditor.VisualStudioCode) WriteVSCodeSettingsFiles(); } + ScriptCompilerBase.ResponseFileData parseResponseFileData(MonoIsland island, string responseFilePath) + { + var systemReferenceDirectories = CSharpLanguage.GetCSharpCompiler(island._target, true, "Assembly-CSharp") == CSharpCompiler.Microsoft + && PlayerSettings.GetScriptingBackend(BuildPipeline.GetBuildTargetGroup(island._target)) == ScriptingImplementation.WinRTDotNET + ? MicrosoftCSharpCompiler.GetClassLibraries(island._target) + : MonoLibraryHelpers.GetSystemReferenceDirectories(island._api_compatibility_level); + + ScriptCompilerBase.ResponseFileData responseFileData = ScriptCompilerBase.ParseResponseFileFromFile( + Path.Combine(_projectDirectory, responseFilePath), + _projectDirectory, + systemReferenceDirectories); + + if (responseFileData.Errors.Length > 0) + { + foreach (var error in responseFileData.Errors) + UnityEngine.Debug.LogErrorFormat("{0} Parse Error : {1}", responseFilePath, error); + } + + return responseFileData; + } + Dictionary GenerateAllAssetProjectParts() { Dictionary stringBuilders = new Dictionary(); @@ -395,8 +420,9 @@ string ProjectText(MonoIsland island, projectBuilder.Append(additionalAssetsForProject); var allAdditionalReferenceFilenames = new List(); + var islandRefs = references.Union(island._references); - foreach (string reference in references.Union(island._references).Union(responseFileData.References.Select(r => r.Assembly))) + foreach (string reference in islandRefs) { if (reference.EndsWith("/UnityEditor.dll") || reference.EndsWith("/UnityEngine.dll") || reference.EndsWith("\\UnityEditor.dll") || reference.EndsWith("\\UnityEngine.dll")) continue; @@ -433,13 +459,13 @@ string ProjectText(MonoIsland island, allAdditionalReferenceFilenames.Add(referenceName); } - //replace \ with / and \\ with / - var escapedFullPath = SecurityElement.Escape(fullReference); - escapedFullPath = escapedFullPath.Replace("\\", "/"); - escapedFullPath = escapedFullPath.Replace("\\\\", "/"); - projectBuilder.AppendFormat(" {1}", Path.GetFileNameWithoutExtension(escapedFullPath), WindowsNewline); - projectBuilder.AppendFormat(" {0}{1}", escapedFullPath, WindowsNewline); - projectBuilder.AppendFormat(" {0}", WindowsNewline); + AppendReference(fullReference, projectBuilder); + } + + var responseRefs = responseFileData.FullPathReferences.Select(r => r.Assembly); + foreach (var reference in responseRefs) + { + AppendReference(reference, projectBuilder); } if (0 < projectReferences.Count) @@ -466,6 +492,17 @@ string ProjectText(MonoIsland island, return projectBuilder.ToString(); } + static void AppendReference(string fullReference, StringBuilder projectBuilder) + { + //replace \ with / and \\ with / + var escapedFullPath = SecurityElement.Escape(fullReference); + escapedFullPath = escapedFullPath.Replace("\\", "/"); + escapedFullPath = escapedFullPath.Replace("\\\\", "/"); + projectBuilder.AppendFormat(" {1}", Path.GetFileNameWithoutExtension(escapedFullPath), WindowsNewline); + projectBuilder.AppendFormat(" {0}{1}", escapedFullPath, WindowsNewline); + projectBuilder.AppendFormat(" {0}", WindowsNewline); + } + public string ProjectFile(MonoIsland island) { ScriptingLanguage language = ScriptingLanguageFor(island); @@ -498,7 +535,7 @@ private string ProjectHeader(MonoIsland island, { targetframeworkversion = "v4.7.1"; } - targetLanguageVersion = "7.2"; + targetLanguageVersion = "latest"; } else if (_settings.VisualStudioVersion == 9) { diff --git a/Editor/Mono/VisualStudioUtil.bindings.cs b/Editor/Mono/VisualStudioUtil.bindings.cs deleted file mode 100644 index 213aa65f2c..0000000000 --- a/Editor/Mono/VisualStudioUtil.bindings.cs +++ /dev/null @@ -1,51 +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.Bindings; - -namespace UnityEditorInternal -{ - //*undocumented* - [NativeType(Header = "Editor/Platform/Windows/VisualStudioUtilities.h")] - internal static class VisualStudioUtil - { - public class VisualStudio - { - public readonly string DevEnvPath; - public readonly string Edition; - public readonly Version Version; - public readonly string[] Workloads; - - internal VisualStudio(string devEnvPath, string edition, Version version, string[] workloads) - { - DevEnvPath = devEnvPath; - Edition = edition; - Version = version; - Workloads = workloads; - } - } - - public static IEnumerable ParseRawDevEnvPaths(string[] rawDevEnvPaths) - { - if (rawDevEnvPaths != null) - { - for (int i = 0; i < rawDevEnvPaths.Length / 4; i++) - { - yield return new VisualStudio( - devEnvPath: rawDevEnvPaths[i * 4], - edition: rawDevEnvPaths[i * 4 + 1], - version: new Version(rawDevEnvPaths[i * 4 + 2]), - workloads: rawDevEnvPaths[i * 4 + 3].Split('|')); - } - } - } - - [FreeFunction("VisualStudioUtilities::FindVisualStudioDevEnvPaths")] - [NativeConditional("UNITY_WIN")] - internal extern static string[] FindVisualStudioDevEnvPaths(int visualStudioVersion, string[] requiredWorkloads); - } -} diff --git a/Editor/Mono/WebViewEditorWindow/WebViewEditorStaticWindow.cs b/Editor/Mono/WebViewEditorWindow/WebViewEditorStaticWindow.cs deleted file mode 100644 index 4085f6d7c6..0000000000 --- a/Editor/Mono/WebViewEditorWindow/WebViewEditorStaticWindow.cs +++ /dev/null @@ -1,47 +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.Collections.Generic; -using UnityEngine; -using System.Text; -using System.IO; -using System; -using UnityEditor; -using UnityEditorInternal; - -namespace UnityEditor.Web -{ - internal abstract class WebViewEditorStaticWindow : WebViewEditorWindow , IHasCustomMenu - { - protected object m_GlobalObject = null; - - // In order to use this class as a parent - // You must copy paste the section below in the child class. - // - //static internal WebView s_WebView; - //internal override WebView webView - //{ - // get {return s_WebView;} - // set {s_WebView = value;} - //} - - - // Use EditorWindow.GetWindow to get/create an instance of this class; - protected WebViewEditorStaticWindow() - { - m_GlobalObject = null; - } - - override public void OnDestroy() - { - OnBecameInvisible(); - m_GlobalObject = null; - } - - override public void OnInitScripting() - { - base.SetScriptObject(); - } - } -} diff --git a/Editor/Mono/WebViewEditorWindow/WebViewEditorWindowsTabs.cs b/Editor/Mono/WebViewEditorWindow/WebViewEditorWindowsTabs.cs deleted file mode 100644 index b47719a678..0000000000 --- a/Editor/Mono/WebViewEditorWindow/WebViewEditorWindowsTabs.cs +++ /dev/null @@ -1,197 +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.Collections.Generic; -using UnityEngine; -using System.Text; -using System.IO; -using System; -using UnityEditor; -using UnityEditorInternal; - -namespace UnityEditor.Web -{ - // This class is used to create a window that has an array of webViews which can be toggled - // visible/hidden. They will appear as one window (such as the services tab). - internal class WebViewEditorWindowTabs : WebViewEditorWindow , IHasCustomMenu, ISerializationCallbackReceiver - { - protected object m_GlobalObject = null; - - internal WebView m_WebView; - - [SerializeField] - private List m_RegisteredViewURLs; - - [SerializeField] - private List m_RegisteredViewInstances; - - private Dictionary m_RegisteredViews; - - // Use EditorWindow.GetWindow to get/create an instance of this class; - protected WebViewEditorWindowTabs() - { - m_RegisteredViewURLs = new List(); - m_RegisteredViewInstances = new List(); - m_RegisteredViews = new Dictionary(); - m_GlobalObject = null; - } - - public override void Init() - { - if (m_GlobalObject == null && !string.IsNullOrEmpty(m_GlobalObjectTypeName)) - { - var instanceType = Type.GetType(m_GlobalObjectTypeName); - if (instanceType != null) - { - m_GlobalObject = ScriptableObject.CreateInstance(instanceType); - JSProxyMgr.GetInstance().AddGlobalObject(m_GlobalObject.GetType().Name, m_GlobalObject); - } - } - } - - public override void OnDestroy() - { - if (webView != null) - { - DestroyImmediate(webView); - } - - m_GlobalObject = null; - - foreach (WebView view in m_RegisteredViews.Values) - { - if (view != null) - DestroyImmediate(view); - } - - m_RegisteredViews.Clear(); - m_RegisteredViewURLs.Clear(); - m_RegisteredViewInstances.Clear(); - } - - public void OnBeforeSerialize() - { - m_RegisteredViewURLs = new List(); - m_RegisteredViewInstances = new List(); - foreach (var kvp in m_RegisteredViews) - { - m_RegisteredViewURLs.Add(kvp.Key); - m_RegisteredViewInstances.Add(kvp.Value); - } - } - - public void OnAfterDeserialize() - { - m_RegisteredViews = new Dictionary(); - for (int i = 0; i != Math.Min(m_RegisteredViewURLs.Count, m_RegisteredViewInstances.Count); i++) - { - m_RegisteredViews.Add(m_RegisteredViewURLs[i], m_RegisteredViewInstances[i]); - } - } - - static string MakeUrlKey(string webViewUrl) - { - string result; - int index = webViewUrl.IndexOf("#"); - if (index != -1) - { - result = webViewUrl.Substring(0, index); - } - else - { - result = webViewUrl; - } - - index = result.LastIndexOf("/"); - if (index == (result.Length - 1)) - { - return result.Substring(0, index); - } - - return result; - } - - protected void UnregisterWebviewUrl(string webViewUrl) - { - var url = MakeUrlKey(webViewUrl); - m_RegisteredViews[url] = null; - } - - private void RegisterWebviewUrl(string webViewUrl, WebView view) - { - var url = MakeUrlKey(webViewUrl); - m_RegisteredViews[url] = view; - } - - private bool FindWebView(string webViewUrl, out WebView webView) - { - webView = null; - var url = MakeUrlKey(webViewUrl); - return m_RegisteredViews.TryGetValue(url, out webView); - } - - public WebView GetWebViewFromURL(string url) - { - var urlKey = MakeUrlKey(url); - return m_RegisteredViews[urlKey]; - } - - public override void OnInitScripting() - { - base.SetScriptObject(); - } - - protected override void InitWebView(Rect webViewRect) - { - base.InitWebView(webViewRect); - if (m_InitialOpenURL != null && webView != null) - { - RegisterWebviewUrl(m_InitialOpenURL, webView); - } - } - - protected override void LoadPage() - { - if (!webView) - return; - - WebView tmpWebView; - - if (!FindWebView(m_InitialOpenURL, out tmpWebView) || tmpWebView == null) - { - NotifyVisibility(false); - //We have to create a webview cache for this url - webView.SetHostView(null); - webView = null; - var webViewRect = GUIClip.Unclip(new Rect(0, 0, position.width, position.height)); - InitWebView(webViewRect); - RegisterWebviewUrl(m_InitialOpenURL, webView); - NotifyVisibility(true); - } - else - { - if (tmpWebView != webView) - { - NotifyVisibility(false); - - tmpWebView.SetHostView(m_Parent); - webView.SetHostView(null); - webView = tmpWebView; - NotifyVisibility(true); - webView.Show(); - } - - //This load Uri causes the flashing. We have NotifyVisibilty we can use to - //to tell the javascript it's being shown - LoadUri(); - } - } - - internal override WebView webView - { - get {return m_WebView; } - set {m_WebView = value; } - } - } -} diff --git a/Editor/Mono/WebViewEditorWindow/WebViewTestFunctions.cs b/Editor/Mono/WebViewEditorWindow/WebViewTestFunctions.cs deleted file mode 100644 index fc9a673fbe..0000000000 --- a/Editor/Mono/WebViewEditorWindow/WebViewTestFunctions.cs +++ /dev/null @@ -1,138 +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 Debug = UnityEngine.Debug; - -namespace UnityEditor.Web -{ - internal class WebViewTestFunctions - { - public int ReturnInt() - { - return 5; - } - - public string ReturnString() - { - return "Five"; - } - - public bool ReturnBool() - { - return true; - } - - public int[] ReturnNumberArray() - { - return new[] {1, 2, 3}; - } - - public string[] ReturnStringArray() - { - return new[] {"One", "Two", "Three"}; - } - - public bool[] ReturnBoolArray() - { - return new[] {true, false, true}; - } - - public TestObject ReturnObject() - { - TestObject testObject = new TestObject {NumberProperty = 5, StringProperty = "Five", BoolProperty = true}; - return testObject; - } - - public void AcceptInt(int passedInt) - { - Debug.Log("A value was passed from JS: " + passedInt); - } - - public void AcceptString(string passedString) - { - Debug.Log("A value was passed from JS: " + passedString); - } - - public void AcceptBool(bool passedBool) - { - Debug.Log("A value was passed from JS: " + passedBool); - } - - public void AcceptIntArray(int[] passedArray) - { - Debug.Log("An array was passed from the JS. Array elements were:"); - for (int i = 0; i <= passedArray.Length; i++) - { - Debug.Log("Element at index " + i + ": " + passedArray[i]); - } - } - - public void AcceptStringArray(string[] passedArray) - { - Debug.Log("An array was passed from the JS. Array elements were:"); - for (int i = 0; i <= passedArray.Length; i++) - { - Debug.Log("Element at index " + i + ": " + passedArray[i]); - } - } - - public void AcceptBoolArray(bool[] passedArray) - { - Debug.Log("An array was passed from the JS. Array elements were:"); - for (int i = 1; i <= passedArray.Length; i++) - { - Debug.Log("Element at index " + i + ": " + passedArray[i]); - } - } - - public void AcceptTestObject(TestObject passedObject) - { - Debug.Log("An object was passed from the JS. Properties were:"); - Debug.Log("StringProperty: " + passedObject.StringProperty); - Debug.Log("NumberProperty: " + passedObject.NumberProperty); - Debug.Log("BoolProperty: " + passedObject.BoolProperty); - } - - //For testing function calls with no parameters or return value - public void VoidMethod(string logMessage) - { - Debug.Log("A method was called from the CEF: " + logMessage); - } - - //For testing access control on CEF function calls - private string APrivateMethod(string input) - { - return "This method is private and not for CEF"; - } - - //For testing function calls that supply and expect an array of strings - public string[] ArrayReverse(string[] input) - { - var outputStrings = (string[])input.Reverse(); - return outputStrings; - } - - public void LogMessage(string message) - { - Debug.Log(message); - } - - public static void RunTestScript(string path) - { - var url = "file:///" + path; - - JSProxyMgr.GetInstance().AddGlobalObject("WebViewTestFunctions", new WebViewTestFunctions()); - var window = WebViewEditorWindowTabs.Create("Test Window", url, 0, 0, 0, 0); - window.OnBatchMode(); - } - } - - internal class TestObject - { - public string StringProperty { get; set; } - public int NumberProperty { get; set; } - public bool BoolProperty { get; set; } - } -} diff --git a/Editor/Src/VR/Mono/GoogleVR/VRCustomOptionsGoogleVR.cs b/Editor/Src/VR/Mono/GoogleVR/VRCustomOptionsGoogleVR.cs index 9f52de4a7e..3eb316accf 100644 --- a/Editor/Src/VR/Mono/GoogleVR/VRCustomOptionsGoogleVR.cs +++ b/Editor/Src/VR/Mono/GoogleVR/VRCustomOptionsGoogleVR.cs @@ -47,7 +47,7 @@ public override Rect Draw(BuildTargetGroup target, Rect rect) return rect; } - public override float GetHeight() + public override float GetHeight(BuildTargetGroup target) { return EditorGUIUtility.singleLineHeight + (EditorGUIUtility.standardVerticalSpacing * 2.0f); } @@ -87,9 +87,9 @@ public override Rect Draw(BuildTargetGroup target, Rect rect) return rect; } - public override float GetHeight() + public override float GetHeight(BuildTargetGroup target) { - return base.GetHeight() + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; + return base.GetHeight(target) + EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing; } } @@ -266,7 +266,7 @@ public override Rect Draw(BuildTargetGroup target, Rect rect) return rect; } - public override float GetHeight() + public override float GetHeight(BuildTargetGroup target) { float singleLineCount = 5.0f; float thumbnailCount = 2.0f; @@ -278,7 +278,7 @@ public override float GetHeight() verticalSpacingCount += 1.0f; } - return base.GetHeight() + (EditorGUIUtility.singleLineHeight * singleLineCount) + + return base.GetHeight(target) + (EditorGUIUtility.singleLineHeight * singleLineCount) + (EditorGUI.kObjectFieldThumbnailHeight * thumbnailCount) + (EditorGUIUtility.standardVerticalSpacing * verticalSpacingCount); } diff --git a/Editor/Src/VR/Mono/Oculus/VRCustomOptionsOculus.cs b/Editor/Src/VR/Mono/Oculus/VRCustomOptionsOculus.cs index 162bf65800..a76b51cb62 100644 --- a/Editor/Src/VR/Mono/Oculus/VRCustomOptionsOculus.cs +++ b/Editor/Src/VR/Mono/Oculus/VRCustomOptionsOculus.cs @@ -13,6 +13,7 @@ internal class VRCustomOptionsOculus : VRCustomOptions { static GUIContent s_SharedDepthBufferLabel = EditorGUIUtility.TextContent("Shared Depth Buffer|Enable depth buffer submission to allow for overlay depth occlusion, etc."); static GUIContent s_DashSupportLabel = EditorGUIUtility.TextContent("Dash Support|If enabled, pressing the home button brings up Dash, otherwise it brings up the older universal menu."); + static GUIContent s_SharedDepthAndroidInfo = EditorGUIUtility.TrTextContent("Shared Depth Buffer and Dash Support aren't available when targeting mobile."); SerializedProperty m_SharedDepthBuffer; SerializedProperty m_DashSupport; @@ -33,39 +34,51 @@ public override Rect Draw(BuildTargetGroup target, Rect rect) { rect.y += EditorGUIUtility.standardVerticalSpacing; - EditorGUI.BeginDisabled(target == BuildTargetGroup.Android); - - rect.height = EditorGUIUtility.singleLineHeight; - GUIContent label = EditorGUI.BeginProperty(rect, s_SharedDepthBufferLabel, m_SharedDepthBuffer); - EditorGUI.BeginChangeCheck(); - bool boolValue = EditorGUI.Toggle(rect, label, m_SharedDepthBuffer.boolValue); - if (EditorGUI.EndChangeCheck()) + if (target != BuildTargetGroup.Android) { - m_SharedDepthBuffer.boolValue = boolValue; - } - EditorGUI.EndProperty(); - rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; + rect.height = EditorGUIUtility.singleLineHeight; + GUIContent label = EditorGUI.BeginProperty(rect, s_SharedDepthBufferLabel, m_SharedDepthBuffer); + EditorGUI.BeginChangeCheck(); + bool boolValue = EditorGUI.Toggle(rect, label, m_SharedDepthBuffer.boolValue); + if (EditorGUI.EndChangeCheck()) + { + m_SharedDepthBuffer.boolValue = boolValue; + } + EditorGUI.EndProperty(); + rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; - rect.height = EditorGUIUtility.singleLineHeight; - label = EditorGUI.BeginProperty(rect, s_DashSupportLabel, m_DashSupport); - EditorGUI.BeginChangeCheck(); - boolValue = EditorGUI.Toggle(rect, label, m_DashSupport.boolValue); - if (EditorGUI.EndChangeCheck()) + rect.height = EditorGUIUtility.singleLineHeight; + label = EditorGUI.BeginProperty(rect, s_DashSupportLabel, m_DashSupport); + EditorGUI.BeginChangeCheck(); + boolValue = EditorGUI.Toggle(rect, label, m_DashSupport.boolValue); + if (EditorGUI.EndChangeCheck()) + { + m_DashSupport.boolValue = boolValue; + } + EditorGUI.EndProperty(); + } + else { - m_DashSupport.boolValue = boolValue; + EditorGUI.BeginDisabled(true); + EditorGUI.LabelField(rect, s_SharedDepthAndroidInfo.text, EditorStyles.wordWrappedMiniLabel); + EditorGUI.EndDisabled(); } - EditorGUI.EndProperty(); - - EditorGUI.EndDisabled(); rect.y += rect.height + EditorGUIUtility.standardVerticalSpacing; return rect; } - public override float GetHeight() + public override float GetHeight(BuildTargetGroup target) { - return (EditorGUIUtility.singleLineHeight * 2.0f) + (EditorGUIUtility.standardVerticalSpacing * 3.0f); + if (target != BuildTargetGroup.Android) + { + return (EditorGUIUtility.singleLineHeight * 2.0f) + (EditorGUIUtility.standardVerticalSpacing * 3.0f); + } + else + { + return (EditorGUIUtility.singleLineHeight * 1.0f) + (EditorGUIUtility.standardVerticalSpacing * 2.0f); + } } } } diff --git a/Editor/Src/VR/Mono/PlayerSettingsEditorVR.cs b/Editor/Src/VR/Mono/PlayerSettingsEditorVR.cs index 69162be0eb..82b85d1157 100644 --- a/Editor/Src/VR/Mono/PlayerSettingsEditorVR.cs +++ b/Editor/Src/VR/Mono/PlayerSettingsEditorVR.cs @@ -22,19 +22,21 @@ static class Styles { public static readonly GUIContent singlepassAndroidWarning = EditorGUIUtility.TrTextContent("Single Pass stereo rendering requires OpenGL ES 3. Please make sure that it's the first one listed under Graphics APIs."); public static readonly GUIContent singlepassAndroidWarning2 = EditorGUIUtility.TrTextContent("Multi Pass will be used on Android devices that don't support Single Pass."); + public static readonly GUIContent singlepassAndroidWarning3 = EditorGUIUtility.TrTextContent("When using a Scriptable Render Pipeline, Single Pass Double Wide will be used on Android devices that don't support Single Pass Instancing or Multi-view."); public static readonly GUIContent singlePassInstancedWarning = EditorGUIUtility.TrTextContent("Single Pass Instanced is only supported on Windows. Multi Pass will be used on other platforms."); + public static readonly GUIContent multiPassNotSupportedWithSRP = EditorGUIUtility.TrTextContent("Multi Pass is only supported using the legacy render pipelies. Stereo Rendering Mode is set to the fallback mode of Single Pass."); public static readonly GUIContent[] kDefaultStereoRenderingPaths = { EditorGUIUtility.TrTextContent("Multi Pass"), EditorGUIUtility.TrTextContent("Single Pass"), - EditorGUIUtility.TrTextContent("Single Pass Instanced (Preview)") + EditorGUIUtility.TrTextContent("Single Pass Instanced") }; public static readonly GUIContent[] kMultiviewStereoRenderingPaths = { EditorGUIUtility.TrTextContent("Multi Pass"), - EditorGUIUtility.TrTextContent("Single Pass Multiview or Instanced (Preview)") + EditorGUIUtility.TrTextContent("Single Pass") }; public static readonly GUIContent xrSettingsTitle = EditorGUIUtility.TrTextContent("XR Settings"); @@ -60,6 +62,7 @@ static class Styles private bool m_InstallsRequired = false; private bool m_VuforiaInstalled = false; + private bool m_ShowMultiPassSRPInfoBox = false; internal int GUISectionIndex { get; set; } @@ -101,6 +104,7 @@ private void RefreshVRDeviceList(BuildTargetGroup targetGroup) customOptions = new VRCustomOptionsNone(); } customOptions.Initialize(m_Settings.serializedObject); + customOptions.IsExpanded = true; m_CustomOptions.Add(deviceInfo.deviceNameKey, customOptions); } } @@ -159,6 +163,8 @@ internal void XRSectionGUI(BuildTargetGroup targetGroup, int sectionIndex) VuforiaGUI(targetGroup); + RemotingWSAHolographicGUI(targetGroup); + Stereo360CaptureGUI(targetGroup); ErrorOnARDeviceIncompatibility(targetGroup); @@ -169,6 +175,11 @@ internal void XRSectionGUI(BuildTargetGroup targetGroup, int sectionIndex) m_Settings.EndSettingsBox(); } + internal bool TargetGroupSupportsWSAHolographicRemoting(BuildTargetGroup targetGroup) + { + return targetGroup == BuildTargetGroup.WSA; + } + private void DevicesGUI(BuildTargetGroup targetGroup) { if (!TargetGroupSupportsVirtualReality(targetGroup)) @@ -297,16 +308,44 @@ private static GUIContent[] GetStereoRenderingPaths(BuildTargetGroup targetGroup return DoesBuildTargetSupportStereoMultiviewRendering(targetGroup) ? Styles.kMultiviewStereoRenderingPaths : Styles.kDefaultStereoRenderingPaths; } + private bool IsStereoRenderingModeSupported(BuildTargetGroup targetGroup, StereoRenderingPath stereoRenderingPath) + { + switch (stereoRenderingPath) + { + case StereoRenderingPath.MultiPass: + return (UnityEngine.Rendering.GraphicsSettings.renderPipelineAsset == null); + + case StereoRenderingPath.SinglePass: + return DoesBuildTargetSupportSinglePassStereoRendering(targetGroup); + + case StereoRenderingPath.Instancing: + return DoesBuildTargetSupportStereoInstancingRendering(targetGroup); + } + ; + + return false; + } + + void OnStereoModeSelected(SerializedProperty stereoRenderingPath, object userData) + { + stereoRenderingPath.intValue = (int)userData; + m_ShowMultiPassSRPInfoBox = false; + + m_Settings.serializedObject.ApplyModifiedProperties(); + } + private void SinglePassStereoGUI(BuildTargetGroup targetGroup, SerializedProperty stereoRenderingPath) { if (!PlayerSettings.virtualRealitySupported) return; - bool supportsSinglePass = DoesBuildTargetSupportSinglePassStereoRendering(targetGroup); - bool supportsSinglePassInstanced = DoesBuildTargetSupportStereoInstancingRendering(targetGroup); + bool supportsMultiPass = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.MultiPass); + bool supportsSinglePass = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.SinglePass); + bool supportsSinglePassInstanced = IsStereoRenderingModeSupported(targetGroup, StereoRenderingPath.Instancing); // populate the dropdown with the valid options based on target platform. - int validStereoRenderingOptionsCount = 1 + (supportsSinglePass ? 1 : 0) + (supportsSinglePassInstanced ? 1 : 0); + int multiPassAndSinglePass = 2; + int validStereoRenderingOptionsCount = multiPassAndSinglePass + (supportsSinglePassInstanced ? 1 : 0); var validStereoRenderingPaths = new GUIContent[validStereoRenderingOptionsCount]; var validStereoRenderingValues = new int[validStereoRenderingOptionsCount]; @@ -316,11 +355,8 @@ private void SinglePassStereoGUI(BuildTargetGroup targetGroup, SerializedPropert validStereoRenderingPaths[addedStereoRenderingOptionsCount] = stereoRenderingPaths[(int)StereoRenderingPath.MultiPass]; validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.MultiPass; - if (supportsSinglePass) - { - validStereoRenderingPaths[addedStereoRenderingOptionsCount] = stereoRenderingPaths[(int)StereoRenderingPath.SinglePass]; - validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.SinglePass; - } + validStereoRenderingPaths[addedStereoRenderingOptionsCount] = stereoRenderingPaths[(int)StereoRenderingPath.SinglePass]; + validStereoRenderingValues[addedStereoRenderingOptionsCount++] = (int)StereoRenderingPath.SinglePass; if (supportsSinglePassInstanced) { @@ -329,20 +365,56 @@ private void SinglePassStereoGUI(BuildTargetGroup targetGroup, SerializedPropert } // setup fallbacks + if (!supportsMultiPass && (stereoRenderingPath.intValue == (int)StereoRenderingPath.MultiPass)) + { + stereoRenderingPath.intValue = (int)StereoRenderingPath.SinglePass; + m_ShowMultiPassSRPInfoBox = true; + } + if (!supportsSinglePassInstanced && (stereoRenderingPath.intValue == (int)StereoRenderingPath.Instancing)) stereoRenderingPath.intValue = (int)StereoRenderingPath.SinglePass; if (!supportsSinglePass && (stereoRenderingPath.intValue == (int)StereoRenderingPath.SinglePass)) stereoRenderingPath.intValue = (int)StereoRenderingPath.MultiPass; - EditorGUILayout.IntPopup(stereoRenderingPath, validStereoRenderingPaths, validStereoRenderingValues, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*")); + if (m_ShowMultiPassSRPInfoBox) + EditorGUILayout.HelpBox(Styles.multiPassNotSupportedWithSRP.text, MessageType.Info); + + var rect = EditorGUILayout.GetControlRect(); + EditorGUI.BeginProperty(rect, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*"), stereoRenderingPath); + rect = EditorGUI.PrefixLabel(rect, EditorGUIUtility.TrTextContent("Stereo Rendering Mode*")); + + int index = Math.Max(0, Array.IndexOf(validStereoRenderingValues, stereoRenderingPath.intValue)); + if (EditorGUI.DropdownButton(rect, validStereoRenderingPaths[index], FocusType.Passive)) + { + var menu = new GenericMenu(); + for (int i = 0; i < validStereoRenderingValues.Length; i++) + { + int value = validStereoRenderingValues[i]; + bool selected = (value == stereoRenderingPath.intValue); + + if (!IsStereoRenderingModeSupported(targetGroup, (StereoRenderingPath)value)) + menu.AddDisabledItem(validStereoRenderingPaths[i], selected); + else + menu.AddItem(validStereoRenderingPaths[i], selected, (object userData) => { OnStereoModeSelected(stereoRenderingPath, userData); }, value); + } + menu.DropDown(rect); + } + EditorGUI.EndProperty(); if ((stereoRenderingPath.intValue == (int)StereoRenderingPath.SinglePass) && (targetGroup == BuildTargetGroup.Android)) { var apisAndroid = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android); if ((apisAndroid.Length > 0) && (apisAndroid[0] == GraphicsDeviceType.OpenGLES3)) { - EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning2.text, MessageType.Info); + if (supportsMultiPass) + { + EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning2.text, MessageType.Info); + } + else + { + EditorGUILayout.HelpBox(Styles.singlepassAndroidWarning3.text, MessageType.Info); + } } else { @@ -353,6 +425,8 @@ private void SinglePassStereoGUI(BuildTargetGroup targetGroup, SerializedPropert { EditorGUILayout.HelpBox(Styles.singlePassInstancedWarning.text, MessageType.Warning); } + + m_Settings.serializedObject.ApplyModifiedProperties(); } private void Stereo360CaptureGUI(BuildTargetGroup targetGroup) @@ -390,7 +464,16 @@ private void AddVRDeviceElement(BuildTargetGroup target, Rect rect, ReorderableL private void RemoveVRDeviceElement(BuildTargetGroup target, ReorderableList list) { var devices = VREditor.GetVREnabledDevicesOnTargetGroup(target).ToList(); + var device = devices[list.index]; devices.RemoveAt(list.index); + + VRCustomOptions customOptions; + if (m_CustomOptions.TryGetValue(device, out customOptions)) + { + customOptions.IsExpanded = true; + } + + ApplyChangedVRDeviceList(target, devices.ToArray()); } @@ -464,7 +547,7 @@ private float GetVRDeviceElementHeight(BuildTargetGroup target, int index) VRCustomOptions customOptions; if (m_CustomOptions.TryGetValue(name, out customOptions)) { - customOptionsHeight = customOptions.IsExpanded ? customOptions.GetHeight() + EditorGUI.kControlVerticalSpacing : 0.0f; + customOptionsHeight = customOptions.IsExpanded ? customOptions.GetHeight(target) + EditorGUI.kControlVerticalSpacing : 0.0f; } return list.elementHeight + customOptionsHeight; @@ -560,18 +643,6 @@ internal void TangoGUI(BuildTargetGroup targetGroup) // Google Tango settings EditorGUILayout.PropertyField(m_AndroidEnableTango, EditorGUIUtility.TrTextContent("ARCore Supported")); - - if (PlayerSettings.Android.ARCoreEnabled) - { - EditorGUI.indentLevel++; - - if ((int)PlayerSettings.Android.minSdkVersion < 24) - { - GUIContent tangoAndroidWarning = EditorGUIUtility.TrTextContent("ARCore requires 'Minimum API Level' to be at least Android 7.0"); - EditorGUILayout.HelpBox(tangoAndroidWarning.text, MessageType.Warning); - } - EditorGUI.indentLevel--; - } } internal void VuforiaGUI(BuildTargetGroup targetGroup) @@ -602,5 +673,26 @@ internal void VuforiaGUI(BuildTargetGroup targetGroup) EditorGUILayout.HelpBox("Vuforia Augmented Reality is required when using the Vuforia Virtual Reality SDK.", MessageType.Info); } } + + internal void RemotingWSAHolographicGUI(BuildTargetGroup targetGroup) + { + if (!TargetGroupSupportsWSAHolographicRemoting(targetGroup)) + return; + var shouldEnableScope = VREditor.GetVREnabledOnTargetGroup(targetGroup) && GetVRDeviceElementIsInList(targetGroup, "WindowsMR"); + using (new EditorGUI.DisabledScope(!shouldEnableScope)) + { + var remotingEnabled = PlayerSettings.GetWsaHolographicRemotingEnabled(); + EditorGUI.BeginChangeCheck(); + remotingEnabled = EditorGUILayout.Toggle(EditorGUIUtility.TrTextContent("WSA Holographic Remoting Supported"), remotingEnabled); + if (EditorGUI.EndChangeCheck()) + { + PlayerSettings.SetWsaHolographicRemotingEnabled(remotingEnabled); + } + } + if (shouldEnableScope) + { + EditorGUILayout.HelpBox("WindowsMR is required when using WSA Holographic Remoting.", MessageType.Info); + } + } } } diff --git a/Editor/Src/VR/Mono/VRCustomOptions.cs b/Editor/Src/VR/Mono/VRCustomOptions.cs index 4f2987cfd7..e6b810c3bb 100644 --- a/Editor/Src/VR/Mono/VRCustomOptions.cs +++ b/Editor/Src/VR/Mono/VRCustomOptions.cs @@ -65,12 +65,12 @@ public virtual void Initialize(SerializedObject settings, string propertyName) } abstract public Rect Draw(BuildTargetGroup target, Rect rect); - abstract public float GetHeight(); + abstract public float GetHeight(BuildTargetGroup target); } internal class VRCustomOptionsNone : VRCustomOptions { public override Rect Draw(BuildTargetGroup target, Rect rect) { return rect; } - public override float GetHeight() { return 0.0f; } + public override float GetHeight(BuildTargetGroup target) { return 0.0f; } } } diff --git a/Editor/Src/VR/Mono/VREditor.cs b/Editor/Src/VR/Mono/VREditor.cs deleted file mode 100644 index b43f4464ea..0000000000 --- a/Editor/Src/VR/Mono/VREditor.cs +++ /dev/null @@ -1,119 +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 UnityEditor; -using UnityEditorInternal.VR; - -namespace UnityEditorInternal.VR -{ - partial class VREditor - { - private static Dictionary dirtyDeviceLists = new Dictionary(); - - public static bool IsDeviceListDirty(BuildTargetGroup targetGroup) - { - if (dirtyDeviceLists.ContainsKey(targetGroup)) - return dirtyDeviceLists[targetGroup]; - - return false; - } - - private static void SetDeviceListDirty(BuildTargetGroup targetGroup) - { - if (dirtyDeviceLists.ContainsKey(targetGroup)) - dirtyDeviceLists[targetGroup] = true; - else - dirtyDeviceLists.Add(targetGroup, true); - } - - public static void ClearDeviceListDirty(BuildTargetGroup targetGroup) - { - if (dirtyDeviceLists.ContainsKey(targetGroup)) - dirtyDeviceLists[targetGroup] = false; - } - - public static VRDeviceInfoEditor[] GetEnabledVRDeviceInfo(BuildTargetGroup targetGroup) - { - string[] enabledVRDevices = GetVREnabledDevicesOnTargetGroup(targetGroup); - return GetAllVRDeviceInfo(targetGroup).Where(d => enabledVRDevices.Contains(d.deviceNameKey)).ToArray(); - } - - public static VRDeviceInfoEditor[] GetEnabledVRDeviceInfo(BuildTarget target) - { - string[] enabledVRDevices = GetVREnabledDevicesOnTarget(target); - return GetAllVRDeviceInfoByTarget(target).Where(d => enabledVRDevices.Contains(d.deviceNameKey)).ToArray(); - } - - public static bool IsVRDeviceEnabledForBuildTarget(BuildTarget target, string deviceName) - { - string[] vrDevices = GetVREnabledDevicesOnTarget(target); - foreach (string device in vrDevices) - { - if (device == deviceName) - return true; - } - return false; - } - - public static string[] GetAvailableVirtualRealitySDKs(BuildTargetGroup targetGroup) - { - VRDeviceInfoEditor[] deviceInfos = GetAllVRDeviceInfo(targetGroup); - string[] sdks = new string[deviceInfos.Length]; - - for (int i = 0; i < deviceInfos.Length; ++i) - { - sdks[i] = deviceInfos[i].deviceNameKey; - } - - return sdks; - } - - // APIs Exposed to PlayerSettings for Scripting Reference - public static string[] GetVirtualRealitySDKs(BuildTargetGroup targetGroup) - { - return GetVREnabledDevicesOnTargetGroup(targetGroup); - } - - public static void SetVirtualRealitySDKs(BuildTargetGroup targetGroup, string[] sdks) - { - SetVREnabledDevicesOnTargetGroup(targetGroup, sdks); - SetDeviceListDirty(targetGroup); - } - } -} - -namespace UnityEditor -{ - partial class PlayerSettings - { - public static string[] GetAvailableVirtualRealitySDKs(BuildTargetGroup targetGroup) - { - return VREditor.GetAvailableVirtualRealitySDKs(targetGroup); - } - - public static bool GetVirtualRealitySupported(BuildTargetGroup targetGroup) - { - return VREditor.GetVREnabledOnTargetGroup(targetGroup); - } - - public static void SetVirtualRealitySupported(BuildTargetGroup targetGroup, bool value) - { - VREditor.SetVREnabledOnTargetGroup(targetGroup, value); - } - - public static string[] GetVirtualRealitySDKs(BuildTargetGroup targetGroup) - { - return VREditor.GetVirtualRealitySDKs(targetGroup); - } - - public static void SetVirtualRealitySDKs(BuildTargetGroup targetGroup, string[] sdks) - { - VREditor.SetVirtualRealitySDKs(targetGroup, sdks); - } - } -} diff --git a/Editor/Src/VR/Mono/WindowsHolographic/VRCustomOptionsWindowsHolographic.cs b/Editor/Src/VR/Mono/WindowsHolographic/VRCustomOptionsWindowsHolographic.cs index 23cacc5175..0dec8b4b95 100644 --- a/Editor/Src/VR/Mono/WindowsHolographic/VRCustomOptionsWindowsHolographic.cs +++ b/Editor/Src/VR/Mono/WindowsHolographic/VRCustomOptionsWindowsHolographic.cs @@ -61,7 +61,7 @@ public override Rect Draw(BuildTargetGroup target, Rect rect) return rect; } - public override float GetHeight() + public override float GetHeight(BuildTargetGroup target) { return EditorGUIUtility.singleLineHeight * 2.0f; } diff --git a/Extensions/Networking/Weaver/AssemblyInfo.cs b/Extensions/Networking/Weaver/AssemblyInfo.cs deleted file mode 100644 index da8f1d8e11..0000000000 --- a/Extensions/Networking/Weaver/AssemblyInfo.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 System; -using System.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("Unity.UNetWeaver")] -[assembly: AssemblyDescription("UNET assembly post processor for code generation.")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Unity Technologies")] -[assembly: AssemblyProduct("Unity.UNetWeaver")] -[assembly: AssemblyCopyright("Copyright © 2014")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] -[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] - -// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". -// The form "{Major}.{Minor}.*" will automatically update the build and revision, -// and "{Major}.{Minor}.{Build}.*" will update just the revision. - -[assembly: AssemblyVersion("1.0.*")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] diff --git a/Extensions/Networking/Weaver/Helpers.cs b/Extensions/Networking/Weaver/Helpers.cs deleted file mode 100644 index 8a6151310c..0000000000 --- a/Extensions/Networking/Weaver/Helpers.cs +++ /dev/null @@ -1,231 +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 System.Diagnostics; -using System.IO; -using System.Reflection; -using Mono.Cecil; -using Mono.Cecil.Cil; -using Mono.Cecil.Mdb; -using Mono.Cecil.Pdb; - -namespace Unity.UNetWeaver -{ - class Helpers - { - // This code is taken from SerializationWeaver - - class AddSearchDirectoryHelper - { - delegate void AddSearchDirectoryDelegate(string directory); - readonly AddSearchDirectoryDelegate _addSearchDirectory; - - public AddSearchDirectoryHelper(IAssemblyResolver assemblyResolver) - { - // reflection is used because IAssemblyResolver doesn't implement AddSearchDirectory but both DefaultAssemblyResolver and NuGetAssemblyResolver do - var addSearchDirectory = assemblyResolver.GetType().GetMethod("AddSearchDirectory", BindingFlags.Instance | BindingFlags.Public, null, new Type[] { typeof(string) }, null); - if (addSearchDirectory == null) - throw new Exception("Assembly resolver doesn't implement AddSearchDirectory method."); - _addSearchDirectory = (AddSearchDirectoryDelegate)Delegate.CreateDelegate(typeof(AddSearchDirectoryDelegate), assemblyResolver, addSearchDirectory); - } - - public void AddSearchDirectory(string directory) - { - _addSearchDirectory(directory); - } - } - - public static string UnityEngineDLLDirectoryName() - { - var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); - return directoryName != null ? directoryName.Replace(@"file:\", "") : null; - } - - public static ISymbolReaderProvider GetSymbolReaderProvider(string inputFile) - { - string nakedFileName = inputFile.Substring(0, inputFile.Length - 4); - if (File.Exists(nakedFileName + ".pdb")) - { - Console.WriteLine("Symbols will be read from " + nakedFileName + ".pdb"); - return new PdbReaderProvider(); - } - if (File.Exists(nakedFileName + ".dll.mdb")) - { - Console.WriteLine("Symbols will be read from " + nakedFileName + ".dll.mdb"); - return new MdbReaderProvider(); - } - Console.WriteLine("No symbols for " + inputFile); - return null; - } - - public static bool InheritsFromSyncList(TypeReference typeRef) - { - try - { - // value types cant inherit from SyncList - if (typeRef.IsValueType) - { - return false; - } - - foreach (var type in ResolveInheritanceHierarchy(typeRef)) - { - // only need to check for generic instances, as we're looking for SyncList - if (type.IsGenericInstance) - { - // resolves the instance type to it's generic type definition, for example SyncList to SyncList - var typeDef = type.Resolve(); - if (typeDef.HasGenericParameters && typeDef.FullName == Weaver.SyncListType.FullName) - { - return true; - } - } - } - } - catch - { - // sometimes this will fail if we reference a weird library that can't be resolved, so we just swallow that exception and return false - } - - return false; - } - - public static IEnumerable ResolveInheritanceHierarchy(TypeReference type) - { - // for value types the hierarchy is pre-defined as " : System.ValueType : System.Object" - if (type.IsValueType) - { - yield return type; - yield return Weaver.valueTypeType; - yield return Weaver.objectType; - yield break; - } - - // resolve entire hierarchy from to System.Object - while (type != null && type.FullName != Weaver.objectType.FullName) - { - yield return type; - - try - { - var typeDef = type.Resolve(); - if (typeDef == null) - { - break; - } - else - { - type = typeDef.BaseType; - } - } - catch - { - // when calling type.Resolve() we can sometimes get an exception if some dependant library - // could not be loaded (for whatever reason) so just swallow it and break out of the loop - break; - } - } - - - yield return Weaver.objectType; - } - - public static string DestinationFileFor(string outputDir, string assemblyPath) - { - var fileName = Path.GetFileName(assemblyPath); - Debug.Assert(fileName != null, "fileName != null"); - - return Path.Combine(outputDir, fileName); - } - - public static string PrettyPrintType(TypeReference type) - { - // generic instances, such as List - if (type.IsGenericInstance) - { - var giType = (GenericInstanceType)type; - return giType.Name.Substring(0, giType.Name.Length - 2) + "<" + String.Join(", ", giType.GenericArguments.Select(PrettyPrintType).ToArray()) + ">"; - } - - // generic types, such as List - if (type.HasGenericParameters) - { - return type.Name.Substring(0, type.Name.Length - 2) + "<" + String.Join(", ", type.GenericParameters.Select(x => x.Name).ToArray()) + ">"; - } - - // non-generic type such as Int - return type.Name; - } - - public static ReaderParameters ReaderParameters(string assemblyPath, IEnumerable extraPaths, IAssemblyResolver assemblyResolver, string unityEngineDLLPath, string unityUNetDLLPath) - { - var parameters = new ReaderParameters(); - if (assemblyResolver == null) - assemblyResolver = new DefaultAssemblyResolver(); - var helper = new AddSearchDirectoryHelper(assemblyResolver); - helper.AddSearchDirectory(Path.GetDirectoryName(assemblyPath)); - helper.AddSearchDirectory(Helpers.UnityEngineDLLDirectoryName()); - helper.AddSearchDirectory(Path.GetDirectoryName(unityEngineDLLPath)); - helper.AddSearchDirectory(Path.GetDirectoryName(unityUNetDLLPath)); - if (extraPaths != null) - { - foreach (var path in extraPaths) - helper.AddSearchDirectory(path); - } - parameters.AssemblyResolver = assemblyResolver; - parameters.SymbolReaderProvider = GetSymbolReaderProvider(assemblyPath); - return parameters; - } - - public static WriterParameters GetWriterParameters(ReaderParameters readParams) - { - var writeParams = new WriterParameters(); - if (readParams.SymbolReaderProvider is PdbReaderProvider) - { - //Log("Will export symbols of pdb format"); - writeParams.SymbolWriterProvider = new PdbWriterProvider(); - } - else if (readParams.SymbolReaderProvider is MdbReaderProvider) - { - //Log("Will export symbols of mdb format"); - writeParams.SymbolWriterProvider = new MdbWriterProvider(); - } - return writeParams; - } - - public static TypeReference MakeGenericType(TypeReference self, params TypeReference[] arguments) - { - if (self.GenericParameters.Count != arguments.Length) - throw new ArgumentException(); - - var instance = new GenericInstanceType(self); - foreach (var argument in arguments) - instance.GenericArguments.Add(argument); - - return instance; - } - - // used to get a specialized method on a generic class, such as SyncList::HandleMsg() - public static MethodReference MakeHostInstanceGeneric(MethodReference self, params TypeReference[] arguments) - { - var reference = new MethodReference(self.Name, self.ReturnType, MakeGenericType(self.DeclaringType, arguments)) - { - HasThis = self.HasThis, - ExplicitThis = self.ExplicitThis, - CallingConvention = self.CallingConvention - }; - - foreach (var parameter in self.Parameters) - reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType)); - - foreach (var genericParameter in self.GenericParameters) - reference.GenericParameters.Add(new GenericParameter(genericParameter.Name, reference)); - - return reference; - } - } -} diff --git a/Extensions/Networking/Weaver/MonoBehaviourProcessor.cs b/Extensions/Networking/Weaver/MonoBehaviourProcessor.cs deleted file mode 100644 index 1b72059ed6..0000000000 --- a/Extensions/Networking/Weaver/MonoBehaviourProcessor.cs +++ /dev/null @@ -1,99 +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 Mono.Cecil; - -namespace Unity.UNetWeaver -{ - class MonoBehaviourProcessor - { - TypeDefinition m_td; - - public MonoBehaviourProcessor(TypeDefinition td) - { - m_td = td; - } - - public void Process() - { - ProcessSyncVars(); - ProcessMethods(); - } - - void ProcessSyncVars() - { - // find syncvars - foreach (FieldDefinition fd in m_td.Fields) - { - foreach (var ca in fd.CustomAttributes) - { - if (ca.AttributeType.FullName == Weaver.SyncVarType.FullName) - { - Log.Error("Script " + m_td.FullName + " uses [SyncVar] " + fd.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - } - - if (Helpers.InheritsFromSyncList(fd.FieldType)) - { - Log.Error(string.Format("Script {0} defines field {1} with type {2}, but it's not a NetworkBehaviour", m_td.FullName, fd.Name, Helpers.PrettyPrintType(fd.FieldType))); - Weaver.fail = true; - } - } - } - - void ProcessMethods() - { - // find command and RPC functions - foreach (MethodDefinition md in m_td.Methods) - { - foreach (var ca in md.CustomAttributes) - { - if (ca.AttributeType.FullName == Weaver.CommandType.FullName) - { - Log.Error("Script " + m_td.FullName + " uses [Command] " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - - if (ca.AttributeType.FullName == Weaver.ClientRpcType.FullName) - { - Log.Error("Script " + m_td.FullName + " uses [ClientRpc] " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - - if (ca.AttributeType.FullName == Weaver.TargetRpcType.FullName) - { - Log.Error("Script " + m_td.FullName + " uses [TargetRpc] " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - - var attrName = ca.Constructor.DeclaringType.ToString(); - - if (attrName == "UnityEngine.Networking.ServerAttribute") - { - Log.Error("Script " + m_td.FullName + " uses the attribute [Server] on the method " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - else if (attrName == "UnityEngine.Networking.ServerCallbackAttribute") - { - Log.Error("Script " + m_td.FullName + " uses the attribute [ServerCallback] on the method " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - else if (attrName == "UnityEngine.Networking.ClientAttribute") - { - Log.Error("Script " + m_td.FullName + " uses the attribute [Client] on the method " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - else if (attrName == "UnityEngine.Networking.ClientCallbackAttribute") - { - Log.Error("Script " + m_td.FullName + " uses the attribute [ClientCallback] on the method " + md.Name + " but is not a NetworkBehaviour."); - Weaver.fail = true; - } - } - } - } - }; -} diff --git a/Extensions/Networking/Weaver/Program.cs b/Extensions/Networking/Weaver/Program.cs deleted file mode 100644 index 0cb8ef3639..0000000000 --- a/Extensions/Networking/Weaver/Program.cs +++ /dev/null @@ -1,65 +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 Mono.Cecil; - -namespace Unity.UNetWeaver -{ - public static class Log - { - public static Action WarningMethod; - public static Action ErrorMethod; - - public static void Warning(string msg) - { - WarningMethod("UNetWeaver warning: " + msg); - } - - public static void Error(string msg) - { - ErrorMethod("UNetWeaver error: " + msg); - } - } - - public class Program - { - public static bool Process(string unityEngine, string unetDLL, string outputDirectory, string[] assemblies, string[] extraAssemblyPaths, IAssemblyResolver assemblyResolver, Action printWarning, Action printError) - { - CheckDLLPath(unityEngine); - CheckDLLPath(unetDLL); - CheckOutputDirectory(outputDirectory); - CheckAssemblies(assemblies); - Log.WarningMethod = printWarning; - Log.ErrorMethod = printError; - return Weaver.WeaveAssemblies(assemblies, extraAssemblyPaths, assemblyResolver, outputDirectory, unityEngine, unetDLL); - } - - private static void CheckDLLPath(string path) - { - if (!File.Exists(path)) - throw new Exception("dll could not be located at " + path + "!"); - } - - private static void CheckAssemblies(IEnumerable assemblyPaths) - { - foreach (var assemblyPath in assemblyPaths) - CheckAssemblyPath(assemblyPath); - } - - private static void CheckAssemblyPath(string assemblyPath) - { - if (!File.Exists(assemblyPath)) - throw new Exception("Assembly " + assemblyPath + " does not exist!"); - } - - private static void CheckOutputDirectory(string outputDir) - { - if (!Directory.Exists(outputDir)) - Directory.CreateDirectory(outputDir); - } - } -} diff --git a/External/ExCSS/builds/builds/lib/net35/ExCSS.Unity.dll b/External/ExCSS/builds/builds/lib/net35/ExCSS.Unity.dll deleted file mode 100644 index 04fbb296f1..0000000000 Binary files a/External/ExCSS/builds/builds/lib/net35/ExCSS.Unity.dll and /dev/null differ diff --git a/External/NRefactory/builds/3.2.1/net35/Unity.Legacy.NRefactory.dll b/External/NRefactory/builds/3.2.1/net35/Unity.Legacy.NRefactory.dll deleted file mode 100644 index 497f69af28..0000000000 Binary files a/External/NRefactory/builds/3.2.1/net35/Unity.Legacy.NRefactory.dll and /dev/null differ diff --git a/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.Mdb.dll b/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.Mdb.dll deleted file mode 100644 index 6f856f7462..0000000000 Binary files a/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.Mdb.dll and /dev/null differ diff --git a/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.Pdb.dll b/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.Pdb.dll deleted file mode 100644 index eee6eb9196..0000000000 Binary files a/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.Pdb.dll and /dev/null differ diff --git a/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.dll b/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.dll deleted file mode 100644 index 4166cfc30f..0000000000 Binary files a/External/Unity.Cecil/builds/lib/net35/Unity.Cecil.dll and /dev/null differ diff --git a/Modules/AI/NavMesh/NavMesh.bindings.cs b/Modules/AI/NavMesh/NavMesh.bindings.cs index 0074c422aa..86023f6ec2 100644 --- a/Modules/AI/NavMesh/NavMesh.bindings.cs +++ b/Modules/AI/NavMesh/NavMesh.bindings.cs @@ -10,7 +10,7 @@ namespace UnityEngine.AI public static partial class NavMesh { [StaticAccessor("GetNavMeshManager()")] - [NativeName("Cleanup")] + [NativeName("CleanupAfterCarving")] public static extern void RemoveAllNavMeshData(); } } diff --git a/Modules/AI/NavMesh/NavMesh.cs b/Modules/AI/NavMesh/NavMesh.cs deleted file mode 100644 index b52ec2d420..0000000000 --- a/Modules/AI/NavMesh/NavMesh.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.Scripting; - -namespace UnityEngine.AI -{ - public static partial class NavMesh - { - public delegate void OnNavMeshPreUpdate(); - public static OnNavMeshPreUpdate onPreUpdate; - - [RequiredByNativeCode] - private static void Internal_CallOnNavMeshPreUpdate() - { - if (onPreUpdate != null) - onPreUpdate(); - } - } -} diff --git a/Modules/AssetBundle/Managed/AssemblyInfo.cs b/Modules/AssetBundle/Managed/AssemblyInfo.cs deleted file mode 100644 index c78d3390dd..0000000000 --- a/Modules/AssetBundle/Managed/AssemblyInfo.cs +++ /dev/null @@ -1,8 +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.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")] -[assembly: InternalsVisibleTo("Assembly-CSharp-testable")] diff --git a/Modules/AssetBundle/Managed/AssetBundle.deprecated.cs b/Modules/AssetBundle/Managed/AssetBundle.deprecated.cs deleted file mode 100644 index 96bff52e53..0000000000 --- a/Modules/AssetBundle/Managed/AssetBundle.deprecated.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; -namespace UnityEngine -{ - partial class AssetBundle - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Method CreateFromFile has been renamed to LoadFromFile (UnityUpgradable) -> LoadFromFile(*)", true)] - public static AssetBundle CreateFromFile(string path) { return null; } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Method CreateFromMemory has been renamed to LoadFromMemoryAsync (UnityUpgradable) -> LoadFromMemoryAsync(*)", true)] - public static AssetBundleCreateRequest CreateFromMemory(byte[] binary) { return null; } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Method CreateFromMemoryImmediate has been renamed to LoadFromMemory (UnityUpgradable) -> LoadFromMemory(*)", true)] - public static AssetBundle CreateFromMemoryImmediate(byte[] binary) { return null; } - } -} diff --git a/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs b/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs index e3ec3ddce3..129af826f3 100644 --- a/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs +++ b/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs @@ -88,6 +88,8 @@ public override void OnInspectorGUI() // the activeTab can get destroyed when opening particular sub-editors (such as the Avatar configuration editor on the Rig tab) if (activeTab != null) { + GUILayout.Space(EditorGUI.kSpacing); + activeTab.OnInspectorGUI(); } diff --git a/Modules/AssetPipelineEditor/ImportSettings/ModelImporterEditor.cs b/Modules/AssetPipelineEditor/ImportSettings/ModelImporterEditor.cs index f11f5c3c8d..af951453d3 100644 --- a/Modules/AssetPipelineEditor/ImportSettings/ModelImporterEditor.cs +++ b/Modules/AssetPipelineEditor/ImportSettings/ModelImporterEditor.cs @@ -11,6 +11,8 @@ namespace UnityEditor [CanEditMultipleObjects] internal class ModelImporterEditor : AssetImporterTabbedEditor { + static string s_LocalizedTitle = L10n.Tr("Model Import Settings"); + public override void OnEnable() { if (tabs == null) @@ -47,5 +49,16 @@ public override GUIContent GetPreviewTitle() // Only show the imported GameObject when the Model tab is active; not when the Animation tab is active public override bool showImportedObject { get { return activeTab is ModelImporterModelEditor; } } + + internal override string targetTitle + { + get + { + if (assetTargets == null || assetTargets.Length == 1 || !m_AllowMultiObjectAccess) + return base.targetTitle; + else + return assetTargets.Length + " " + s_LocalizedTitle; + } + } } } diff --git a/Modules/AssetPipelineEditor/Public/PluginImporter.bindings.cs b/Modules/AssetPipelineEditor/Public/PluginImporter.bindings.cs index 4ec47ccaa8..fd4083cfae 100644 --- a/Modules/AssetPipelineEditor/Public/PluginImporter.bindings.cs +++ b/Modules/AssetPipelineEditor/Public/PluginImporter.bindings.cs @@ -213,6 +213,9 @@ public bool GetExcludeFromAnyPlatform(BuildTarget platform) [NativeMethod("SetCompatibleWithEditor")] extern internal void SetCompatibleWithEditorWithBuildTargetsInternal(BuildTargetGroup buildTargetGroup, BuildTarget buildTarget, bool enable); + [NativeMethod("IsCompatibleWithDefines")] + extern internal bool IsCompatibleWithDefines(string[] defines); + internal void SetCompatibleWithEditor(BuildTargetGroup buildTargetGroup, BuildTarget buildTarget, bool enable) { SetCompatibleWithEditorWithBuildTargetsInternal(buildTargetGroup, buildTarget, enable); diff --git a/Modules/Audio/Public/Managed/Audio.deprecated.cs b/Modules/Audio/Public/Managed/Audio.deprecated.cs deleted file mode 100644 index 9dd86447f1..0000000000 --- a/Modules/Audio/Public/Managed/Audio.deprecated.cs +++ /dev/null @@ -1,46 +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 UnityEngine -{ - partial class AudioSettings - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("AudioSettings.driverCaps is obsolete. Use driverCapabilities instead (UnityUpgradable) -> driverCapabilities", true)] - public static AudioSpeakerMode driverCaps { get { return driverCapabilities; } } - } - - partial class AudioSource - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [System.Obsolete("AudioSource.panLevel has been deprecated. Use AudioSource.spatialBlend instead (UnityUpgradable) -> spatialBlend", true)] - public float panLevel { get { return spatialBlend; } set {} } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [System.Obsolete("AudioSource.pan has been deprecated. Use AudioSource.panStereo instead (UnityUpgradable) -> panStereo", true)] - public float pan { get { return panStereo; } set {} } - } - - partial class AudioLowPassFilter - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("AudioLowPassFilter.lowpassResonaceQ is obsolete. Use lowpassResonanceQ instead (UnityUpgradable) -> lowpassResonanceQ", true)] - public float lowpassResonaceQ { get { return lowpassResonanceQ; } set {} } - } - - partial class AudioHighPassFilter - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("AudioHighPassFilter.highpassResonaceQ is obsolete. Use highpassResonanceQ instead (UnityUpgradable) -> highpassResonanceQ", true)] - public float highpassResonaceQ { get { return highpassResonanceQ; } set {} } - } - - partial class AudioReverbFilter - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("AudioReverbFilter.lFReference is obsolete. Use lfReference instead (UnityUpgradable) -> lfReference", true)] - public float lFReference { get { return lfReference; } set {} } - } -} diff --git a/Modules/BuildPipeline/Editor/Managed/BuildDefines.cs b/Modules/BuildPipeline/Editor/Managed/BuildDefines.cs deleted file mode 100644 index 54e5508c39..0000000000 --- a/Modules/BuildPipeline/Editor/Managed/BuildDefines.cs +++ /dev/null @@ -1,30 +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 UnityEditor; -using UnityEngine; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEditor.Build -{ - internal delegate void GetScriptCompilationDefinesDelegate(BuildTarget target, HashSet defines); - - [RequiredByNativeCode] - internal class BuildDefines - { - public static event GetScriptCompilationDefinesDelegate getScriptCompilationDefinesDelegates; - - [RequiredByNativeCode] - public static string[] GetScriptCompilationDefines(BuildTarget target, string[] defines) - { - var hashSet = new HashSet(defines); - if (getScriptCompilationDefinesDelegates != null) - getScriptCompilationDefinesDelegates(target, hashSet); - var array = new string[hashSet.Count]; - hashSet.CopyTo(array); - return array; - } - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildFile.cs b/Modules/BuildReportingEditor/Managed/BuildFile.cs deleted file mode 100644 index 26b536c251..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildFile.cs +++ /dev/null @@ -1,25 +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.Bindings; - -namespace UnityEditor.Build.Reporting -{ - [NativeType(Header = "Modules/BuildReportingEditor/Public/BuildReport.h")] - public struct BuildFile - { - internal uint id { get; } - public string path { get; } - public string role { get; } - - [NativeName("totalSize")] - public ulong size { get; } - - public override string ToString() - { - return path; - } - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildReport.bindings.cs b/Modules/BuildReportingEditor/Managed/BuildReport.bindings.cs deleted file mode 100644 index 19be0e3f49..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildReport.bindings.cs +++ /dev/null @@ -1,72 +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 UnityEngine; -using Object = UnityEngine.Object; -using UnityEngine.Bindings; - -namespace UnityEditor.Build.Reporting -{ - [NativeHeader("Runtime/Utilities/DateTime.h")] - [NativeType(Header = "Modules/BuildReportingEditor/Public/BuildReport.h")] - [NativeClass("BuildReporting::BuildReport")] - public sealed class BuildReport : Object - { - private BuildReport() - { - } - - public extern BuildFile[] files { get; } - - [NativeName("BuildSteps")] - public extern BuildStep[] steps { get; } - - public extern BuildSummary summary { get; } - - public StrippingInfo strippingInfo - { - get { return GetAppendices().SingleOrDefault(); } - } - - [NativeMethod("RelocateFiles")] - internal extern void RecordFilesMoved(string originalPathPrefix, string newPathPrefix); - - [NativeMethod("AddFile")] - internal extern void RecordFileAdded(string path, string role); - - [NativeMethod("AddFilesRecursive")] - internal extern void RecordFilesAddedRecursive(string rootDir, string role); - - [NativeMethod("DeleteFile")] - internal extern void RecordFileDeleted(string path); - - [NativeMethod("DeleteFilesRecursive")] - internal extern void RecordFilesDeletedRecursive(string rootDir); - - [FreeFunction("BuildReporting::SummarizeErrors", HasExplicitThis = true)] - internal extern string SummarizeErrors(); - - internal extern void AddMessage(LogType messageType, string message); - - internal extern int BeginBuildStep(string stepName); - internal extern void ResumeBuildStep(int depth); - internal extern void EndBuildStep(int depth); - - internal extern void AddAppendix([NotNull] Object obj); - - internal TAppendix[] GetAppendices() where TAppendix : Object - { - return GetAppendices(typeof(TAppendix)).Cast().ToArray(); - } - - internal extern Object[] GetAppendices([NotNull] Type type); - - internal extern Object[] GetAllAppendices(); - - [FreeFunction("BuildReporting::GetLatestReport")] - internal static extern BuildReport GetLatestReport(); - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildReportHelper.cs b/Modules/BuildReportingEditor/Managed/BuildReportHelper.cs deleted file mode 100644 index 6da1c7d2eb..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildReportHelper.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 System.Diagnostics; -using System.Linq; -using UnityEditor.Utils; -using UnityEngine; -using System.Collections.Generic; -using System.IO; -using System.Xml.XPath; -using UnityEditorInternal; -using System; -using System.Text.RegularExpressions; -using Mono.Cecil; -using UnityEditor.Modules; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEditor.Build.Reporting -{ - internal static class BuildReportHelper - { - private static IBuildAnalyzer m_CachedAnalyzer; - private static BuildTarget m_CachedAnalyzerTarget; - - private static IBuildAnalyzer GetAnalyzerForTarget(BuildTarget target) - { - if (m_CachedAnalyzerTarget == target) - return m_CachedAnalyzer; - - m_CachedAnalyzer = ModuleManager.GetBuildAnalyzer(target); - m_CachedAnalyzerTarget = target; - return m_CachedAnalyzer; - } - - [RequiredByNativeCode] - public static void OnAddedExecutable(BuildReport report, int fileIndex) - { - var analyzer = GetAnalyzerForTarget(report.summary.platform); - if (analyzer == null) return; - - analyzer.OnAddedExecutable(report, fileIndex); - } - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildReportViewerWindow.cs b/Modules/BuildReportingEditor/Managed/BuildReportViewerWindow.cs deleted file mode 100644 index 064d28ce84..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildReportViewerWindow.cs +++ /dev/null @@ -1,15 +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 UnityEditor; -using System.Linq; -using UnityEditorInternal; -using System.Text; -using UnityEditor.Web; -using System.IO; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - diff --git a/Modules/BuildReportingEditor/Managed/BuildResult.cs b/Modules/BuildReportingEditor/Managed/BuildResult.cs deleted file mode 100644 index 0c2510c90c..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildResult.cs +++ /dev/null @@ -1,16 +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.Build.Reporting -{ - public enum BuildResult - { - Unknown = 0, - Succeeded = 1, - Failed = 2, - Cancelled = 3 - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildStep.cs b/Modules/BuildReportingEditor/Managed/BuildStep.cs deleted file mode 100644 index 3126456275..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildStep.cs +++ /dev/null @@ -1,28 +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.Bindings; - -namespace UnityEditor.Build.Reporting -{ - [NativeType(Header = "Modules/BuildReportingEditor/Public/BuildReport.h")] - public struct BuildStep - { - [NativeName("stepName")] - public string name { get; } - - internal ulong durationTicks; - public TimeSpan duration { get { return new TimeSpan((long)durationTicks); } } - - public BuildStepMessage[] messages { get; } - - public int depth { get; } - - public override string ToString() - { - return string.Format("{0} ({1}ms)", name, duration.TotalMilliseconds); - } - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildStepMessage.cs b/Modules/BuildReportingEditor/Managed/BuildStepMessage.cs deleted file mode 100644 index b4fb96bc18..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildStepMessage.cs +++ /dev/null @@ -1,18 +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.Bindings; -using Object = UnityEngine.Object; - -namespace UnityEditor.Build.Reporting -{ - [NativeType(Header = "Modules/BuildReportingEditor/Public/BuildReport.h")] - public struct BuildStepMessage - { - public LogType type { get; } - public string content { get; } - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildSummary.cs b/Modules/BuildReportingEditor/Managed/BuildSummary.cs deleted file mode 100644 index 8e3ada05d0..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildSummary.cs +++ /dev/null @@ -1,39 +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.Bindings; - -namespace UnityEditor.Build.Reporting -{ - [NativeType(Header = "Modules/BuildReportingEditor/Managed/BuildSummary.bindings.h", CodegenOptions = CodegenOptions.Custom)] - public struct BuildSummary - { - internal Int64 buildStartTimeTicks; - public DateTime buildStartedAt { get { return new DateTime(buildStartTimeTicks); } } - - [NativeName("buildGUID")] - public GUID guid { get; } - - public BuildTarget platform { get; } - public BuildTargetGroup platformGroup { get; } - public BuildOptions options { get; } - internal BuildAssetBundleOptions assetBundleOptions { get; } - public string outputPath { get; } - internal uint crc { get; } - public ulong totalSize { get; } - - internal UInt64 totalTimeTicks; - public TimeSpan totalTime { get { return new TimeSpan((long)totalTimeTicks); } } - public DateTime buildEndedAt { get { return buildStartedAt + totalTime; } } - - public int totalErrors { get; } - public int totalWarnings { get; } - - [NativeName("buildResult")] - public BuildResult result { get; } - - internal BuildType buildType { get; } - } -} diff --git a/Modules/BuildReportingEditor/Managed/BuildType.cs b/Modules/BuildReportingEditor/Managed/BuildType.cs deleted file mode 100644 index b820a47f5e..0000000000 --- a/Modules/BuildReportingEditor/Managed/BuildType.cs +++ /dev/null @@ -1,15 +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.Build.Reporting -{ - [Flags] - internal enum BuildType - { - Player = 1, - AssetBundle = 2 - } -} diff --git a/Modules/BuildReportingEditor/Managed/CommonRoles.bindings.cs b/Modules/BuildReportingEditor/Managed/CommonRoles.bindings.cs deleted file mode 100644 index 93584dcafc..0000000000 --- a/Modules/BuildReportingEditor/Managed/CommonRoles.bindings.cs +++ /dev/null @@ -1,81 +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.Bindings; - -namespace UnityEditor -{ - namespace Build.Reporting - { - [NativeType(Header = "Modules/BuildReportingEditor/Public/CommonRoles.h")] - public static class CommonRoles - { - [NativeProperty("BuildReporting::CommonRoles::scene", true, TargetType.Field)] - public static extern string scene { get; } - - [NativeProperty("BuildReporting::CommonRoles::sharedAssets", true, TargetType.Field)] - public static extern string sharedAssets { get; } - - [NativeProperty("BuildReporting::CommonRoles::resourcesFile", true, TargetType.Field)] - public static extern string resourcesFile { get; } - - [NativeProperty("BuildReporting::CommonRoles::assetBundle", true, TargetType.Field)] - public static extern string assetBundle { get; } - - [NativeProperty("BuildReporting::CommonRoles::manifestAssetBundle", true, TargetType.Field)] - public static extern string manifestAssetBundle { get; } - - [NativeProperty("BuildReporting::CommonRoles::assetBundleTextManifest", true, TargetType.Field)] - public static extern string assetBundleTextManifest { get; } - - [NativeProperty("BuildReporting::CommonRoles::managedLibrary", true, TargetType.Field)] - public static extern string managedLibrary { get; } - - [NativeProperty("BuildReporting::CommonRoles::dependentManagedLibrary", true, TargetType.Field)] - public static extern string dependentManagedLibrary { get; } - - [NativeProperty("BuildReporting::CommonRoles::executable", true, TargetType.Field)] - public static extern string executable { get; } - - [NativeProperty("BuildReporting::CommonRoles::streamingResourceFile", true, TargetType.Field)] - public static extern string streamingResourceFile { get; } - - [NativeProperty("BuildReporting::CommonRoles::streamingAsset", true, TargetType.Field)] - public static extern string streamingAsset { get; } - - [NativeProperty("BuildReporting::CommonRoles::bootConfig", true, TargetType.Field)] - public static extern string bootConfig { get; } - - [NativeProperty("BuildReporting::CommonRoles::builtInResources", true, TargetType.Field)] - public static extern string builtInResources { get; } - - [NativeProperty("BuildReporting::CommonRoles::builtInShaders", true, TargetType.Field)] - public static extern string builtInShaders { get; } - - [NativeProperty("BuildReporting::CommonRoles::appInfo", true, TargetType.Field)] - public static extern string appInfo { get; } - - [NativeProperty("BuildReporting::CommonRoles::managedEngineAPI", true, TargetType.Field)] - public static extern string managedEngineApi { get; } - - [NativeProperty("BuildReporting::CommonRoles::monoRuntime", true, TargetType.Field)] - public static extern string monoRuntime { get; } - - [NativeProperty("BuildReporting::CommonRoles::monoConfig", true, TargetType.Field)] - public static extern string monoConfig { get; } - - [NativeProperty("BuildReporting::CommonRoles::debugInfo", true, TargetType.Field)] - public static extern string debugInfo { get; } - - [NativeProperty("BuildReporting::CommonRoles::globalGameManagers", true, TargetType.Field)] - public static extern string globalGameManagers { get; } - - [NativeProperty("BuildReporting::CommonRoles::crashHandler", true, TargetType.Field)] - public static extern string crashHandler { get; } - - [NativeProperty("BuildReporting::CommonRoles::engineLibrary", true, TargetType.Field)] - public static extern string engineLibrary { get; } - } - } -} diff --git a/Modules/BuildReportingEditor/Managed/ScopedBuildStep.cs b/Modules/BuildReportingEditor/Managed/ScopedBuildStep.cs deleted file mode 100644 index 8fd9a03ae0..0000000000 --- a/Modules/BuildReportingEditor/Managed/ScopedBuildStep.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; - -namespace UnityEditor.Build.Reporting -{ - internal struct ScopedBuildStep : IDisposable - { - private readonly BuildReport m_Report; - private readonly int m_Step; - - public ScopedBuildStep(BuildReport report, string stepName) - { - if (report == null) - throw new ArgumentNullException("report"); - - m_Report = report; - m_Step = report.BeginBuildStep(stepName); - } - - public void Resume() - { - m_Report.ResumeBuildStep(m_Step); - } - - public void Dispose() - { - m_Report.EndBuildStep(m_Step); - } - } -} diff --git a/Modules/CloudServicesSettingsEditor/Ads/ScriptBindings/AdvertisementSettings.bindings.cs b/Modules/CloudServicesSettingsEditor/Ads/ScriptBindings/AdvertisementSettings.bindings.cs deleted file mode 100644 index 5e82363ec7..0000000000 --- a/Modules/CloudServicesSettingsEditor/Ads/ScriptBindings/AdvertisementSettings.bindings.cs +++ /dev/null @@ -1,49 +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.Bindings; - -namespace UnityEditor.Advertisements -{ - - [NativeHeader("Modules/UnityConnect/UnityAds/UnityAdsSettings.h")] - [StaticAccessor("GetUnityAdsSettings()", StaticAccessorType.Dot)] - public static partial class AdvertisementSettings - { - public static extern bool enabled { get; set; } - - public static extern bool testMode { get; set; } - - public static extern bool initializeOnStartup { get; set; } - - public static extern string GetGameId(RuntimePlatform platform); - - public static extern void SetGameId(RuntimePlatform platform, string gameId); - - [System.Obsolete("No longer supported and will always return true")] - public static bool IsPlatformEnabled(RuntimePlatform platform) - { - return true; - } - - [System.Obsolete("No longer supported and will do nothing")] - public static void SetPlatformEnabled(RuntimePlatform platform, bool value) - { - } - - [NativeMethod("GetGameId")] - public static extern string GetPlatformGameId(string platformName); - - [NativeMethod("SetGameId")] - public static extern void SetPlatformGameId(string platformName, string gameId); - - internal static extern void SetEnabledServiceWindow(bool enabled); - - internal static extern bool enabledForPlatform { get; } - - internal static extern void ApplyEnableSettings(BuildTarget target); - } - -} diff --git a/Modules/CloudServicesSettingsEditor/Analytics/ScriptBindings/AnalyticsSettings.bindings.cs b/Modules/CloudServicesSettingsEditor/Analytics/ScriptBindings/AnalyticsSettings.bindings.cs deleted file mode 100644 index ebd2b86384..0000000000 --- a/Modules/CloudServicesSettingsEditor/Analytics/ScriptBindings/AnalyticsSettings.bindings.cs +++ /dev/null @@ -1,25 +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.Bindings; - -namespace UnityEditor.Analytics -{ - - [NativeHeader("Modules/UnityConnect/UnityAnalytics/UnityAnalyticsSettings.h")] - [StaticAccessor("GetUnityAnalyticsSettings()", StaticAccessorType.Dot)] - public static partial class AnalyticsSettings - { - public static extern bool enabled { get; set; } - - public static extern bool testMode { get; set; } - - internal static extern void SetEnabledServiceWindow(bool enabled); - - internal static extern bool enabledForPlatform { get; } - - internal static extern void ApplyEnableSettings(BuildTarget target); - } - -} diff --git a/Modules/CloudServicesSettingsEditor/PerformanceReporting/ScriptBindings/PerformanceReportingSettings.bindings.cs b/Modules/CloudServicesSettingsEditor/PerformanceReporting/ScriptBindings/PerformanceReportingSettings.bindings.cs deleted file mode 100644 index 0ebada4659..0000000000 --- a/Modules/CloudServicesSettingsEditor/PerformanceReporting/ScriptBindings/PerformanceReportingSettings.bindings.cs +++ /dev/null @@ -1,19 +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.Bindings; - -namespace UnityEditor.Analytics -{ - - [NativeHeader("Modules/UnityConnect/PerformanceReporting/PerformanceReportingSettings.h")] - [StaticAccessor("GetPerformanceReportingSettings()", StaticAccessorType.Dot)] - public static partial class PerformanceReportingSettings - { - [ThreadAndSerializationSafe()] - public static extern bool enabled { get; set; } - } - -} diff --git a/Modules/CloudServicesSettingsEditor/Purchasing/ScriptBindings/PurchasingSettings.bindings.cs b/Modules/CloudServicesSettingsEditor/Purchasing/ScriptBindings/PurchasingSettings.bindings.cs deleted file mode 100644 index 97fdab902b..0000000000 --- a/Modules/CloudServicesSettingsEditor/Purchasing/ScriptBindings/PurchasingSettings.bindings.cs +++ /dev/null @@ -1,25 +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.Bindings; - -namespace UnityEditor.Purchasing -{ - - [NativeHeader("Modules/UnityConnect/UnityPurchasing/UnityPurchasingSettings.h")] - [StaticAccessor("GetUnityPurchasingSettings()", StaticAccessorType.Dot)] - public static partial class PurchasingSettings - { - [ThreadAndSerializationSafe()] - public static extern bool enabled { get; set; } - - internal static extern bool enabledForPlatform { get; } - - internal static extern void ApplyEnableSettings(BuildTarget target); - - internal static extern void SetEnabledServiceWindow(bool enabled); - } - -} diff --git a/Modules/GameCenter/Managed/GameCenterServices.cs b/Modules/GameCenter/Managed/GameCenterServices.cs deleted file mode 100644 index b8a1c97fa2..0000000000 --- a/Modules/GameCenter/Managed/GameCenterServices.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 - -using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; -using UnityEngine.Scripting; - -namespace UnityEngine.SocialPlatforms.GameCenter -{ -} diff --git a/Modules/GameCenter/Managed/NetworkServices.cs b/Modules/GameCenter/Managed/NetworkServices.cs deleted file mode 100644 index 92d9b7abdf..0000000000 --- a/Modules/GameCenter/Managed/NetworkServices.cs +++ /dev/null @@ -1,233 +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 UnityEngine -{ - using UnityEngine.SocialPlatforms; - - // A facade for the social API namespace, no state, only helper functions which delegate into others - public static class Social - { - public static ISocialPlatform Active - { - get { return ActivePlatform.Instance; } - set { ActivePlatform.Instance = value; } - } - - public static ILocalUser localUser { get { return Active.localUser; } } - - public static void LoadUsers(string[] userIDs, Action callback) - { - Active.LoadUsers(userIDs, callback); - } - - public static void ReportProgress(string achievementID, double progress, Action callback) - { - Active.ReportProgress(achievementID, progress, callback); - } - - public static void LoadAchievementDescriptions(Action callback) - { - Active.LoadAchievementDescriptions(callback); - } - - public static void LoadAchievements(Action callback) - { - Active.LoadAchievements(callback); - } - - public static void ReportScore(Int64 score, string board, Action callback) - { - Active.ReportScore(score, board, callback); - } - - public static void LoadScores(string leaderboardID, Action callback) - { - Active.LoadScores(leaderboardID, callback); - } - - public static ILeaderboard CreateLeaderboard() - { - return Active.CreateLeaderboard(); - } - - public static IAchievement CreateAchievement() - { - return Active.CreateAchievement(); - } - - public static void ShowAchievementsUI() - { - Active.ShowAchievementsUI(); - } - - public static void ShowLeaderboardUI() - { - Active.ShowLeaderboardUI(); - } - } -} - -namespace UnityEngine.SocialPlatforms -{ - // The state of the current active social implementation - internal static class ActivePlatform - { - private static ISocialPlatform _active; - - internal static ISocialPlatform Instance - { - get - { - if (_active == null) - _active = SelectSocialPlatform(); - return _active; - } - set - { - _active = value; - } - } - - private static ISocialPlatform SelectSocialPlatform() - { - // statically selecting community - return new UnityEngine.SocialPlatforms.Local(); - } - } - - public interface ISocialPlatform - { - ILocalUser localUser { get; } - - void LoadUsers(string[] userIDs, Action callback); - - void ReportProgress(string achievementID, double progress, Action callback); - void LoadAchievementDescriptions(Action callback); - void LoadAchievements(Action callback); - IAchievement CreateAchievement(); - - void ReportScore(Int64 score, string board, Action callback); - void LoadScores(string leaderboardID, Action callback); - ILeaderboard CreateLeaderboard(); - - void ShowAchievementsUI(); - void ShowLeaderboardUI(); - - // ===> These should be explicitly implemented <=== - void Authenticate(ILocalUser user, Action callback); - void Authenticate(ILocalUser user, Action callback); - void LoadFriends(ILocalUser user, Action callback); - void LoadScores(ILeaderboard board, Action callback); - bool GetLoading(ILeaderboard board); - } - - public interface ILocalUser : IUserProfile - { - void Authenticate(Action callback); - void Authenticate(Action callback); - - void LoadFriends(Action callback); - - IUserProfile[] friends { get; } - bool authenticated { get; } - bool underage { get; } - } - - public enum UserState - { - Online, - OnlineAndAway, - OnlineAndBusy, - Offline, - Playing - } - - public interface IUserProfile - { - string userName { get; } - string id { get; } - bool isFriend { get; } - UserState state { get; } - Texture2D image { get; } - } - - public interface IAchievement - { - void ReportProgress(Action callback); - - string id { get; set; } - double percentCompleted { get; set; } - bool completed { get; } - bool hidden { get; } - DateTime lastReportedDate { get; } - } - - public interface IAchievementDescription - { - string id { get; set; } - string title { get; } - Texture2D image { get; } - string achievedDescription { get; } - string unachievedDescription { get; } - bool hidden { get; } - int points { get; } - } - - public interface IScore - { - void ReportScore(Action callback); - - string leaderboardID { get; set; } - // TODO: This is just an int64 here, but should be able to represent all supported formats, except for float type scores ... - Int64 value { get; set; } - DateTime date { get; } - string formattedValue { get; } - string userID { get; } - int rank { get; } - } - - public enum UserScope - { - Global = 0, - FriendsOnly - } - - public enum TimeScope - { - Today = 0, - Week, - AllTime - } - - public struct Range - { - public int from; - public int count; - - public Range(int fromValue, int valueCount) - { - from = fromValue; - count = valueCount; - } - } - - public interface ILeaderboard - { - void SetUserFilter(string[] userIDs); - void LoadScores(Action callback); - bool loading { get; } - - string id { get; set; } - UserScope userScope { get; set; } - Range range { get; set; } - TimeScope timeScope { get; set; } - IScore localUserScore { get; } - uint maxRange { get; } - IScore[] scores { get; } - string title { get; } - } -} diff --git a/Modules/GameCenter/Public/GameCenterServices.bindings.cs b/Modules/GameCenter/Public/GameCenterServices.bindings.cs deleted file mode 100644 index c47627bde8..0000000000 --- a/Modules/GameCenter/Public/GameCenterServices.bindings.cs +++ /dev/null @@ -1,9 +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.Runtime.InteropServices; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - diff --git a/Modules/GraphViewEditor/Capabilities.cs b/Modules/GraphViewEditor/Capabilities.cs deleted file mode 100644 index 069cac8c77..0000000000 --- a/Modules/GraphViewEditor/Capabilities.cs +++ /dev/null @@ -1,20 +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 - } -} diff --git a/Modules/GraphViewEditor/Direction.cs b/Modules/GraphViewEditor/Direction.cs deleted file mode 100644 index 769ad99f28..0000000000 --- a/Modules/GraphViewEditor/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/ISelectable.cs b/Modules/GraphViewEditor/ISelectable.cs deleted file mode 100644 index c77e0fb4b4..0000000000 --- a/Modules/GraphViewEditor/ISelectable.cs +++ /dev/null @@ -1,19 +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.GraphView -{ - public interface ISelectable - { - bool IsSelectable(); - bool HitTest(Vector2 localPoint); - bool Overlaps(Rect rectangle); - void Select(VisualElement selectionContainer, bool additive); - void Unselect(VisualElement selectionContainer); - bool IsSelected(VisualElement selectionContainer); - } -} diff --git a/Modules/GraphViewEditor/ISelection.cs b/Modules/GraphViewEditor/ISelection.cs deleted file mode 100644 index a16872a9ab..0000000000 --- a/Modules/GraphViewEditor/ISelection.cs +++ /dev/null @@ -1,17 +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.Collections.Generic; - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - public interface ISelection - { - List selection { get; } - - void AddToSelection(ISelectable selectable); - void RemoveFromSelection(ISelectable selectable); - void ClearSelection(); - } -} diff --git a/Modules/GraphViewEditor/Manipulators/SelectionDragger.cs b/Modules/GraphViewEditor/Manipulators/SelectionDragger.cs index 790fb52601..56e112b8af 100644 --- a/Modules/GraphViewEditor/Manipulators/SelectionDragger.cs +++ b/Modules/GraphViewEditor/Manipulators/SelectionDragger.cs @@ -453,6 +453,8 @@ void MoveElement(GraphElement element, Rect originalPos) var graphView = target as GraphView; if (graphView != null && graphView.graphViewChanged != null) { + KeyValuePair firstPos = m_OriginalPos.First(); + m_GraphViewChange.moveDelta = firstPos.Key.GetPosition().position - firstPos.Value.pos.position; graphView.graphViewChanged(m_GraphViewChange); } } diff --git a/Modules/GraphViewEditor/NodeAdapter.cs b/Modules/GraphViewEditor/NodeAdapter.cs deleted file mode 100644 index 1e70e225eb..0000000000 --- a/Modules/GraphViewEditor/NodeAdapter.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 System.Linq; -using System.Reflection; -using System.Runtime.CompilerServices; -using UnityEngine; - -namespace UnityEditor.Experimental.UIElements.GraphView -{ - // types of port to adapt - public class PortSource - { - } - - // attribute to declare and adapter - public class TypeAdapter : Attribute - { - } - - // TODO: This is a straight port from Canvas2D. I don't think that having to check for types in the assembly using reflection is the way we want to go. - public class NodeAdapter - { - private static List s_TypeAdapters; - private static Dictionary s_NodeAdapterDictionary; - - public bool CanAdapt(object a, object b) - { - if (a == b) - return false; // self connections are not permitted - - if (a == null || b == null) - return false; - - MethodInfo mi = GetAdapter(a, b); - if (mi == null) - { - Debug.Log("adapter node not found for: " + a.GetType() + " -> " + b.GetType()); - } - return mi != null; - } - - public bool Connect(object a, object b) - { - MethodInfo mi = GetAdapter(a, b); - if (mi == null) - { - Debug.LogError("Attempt to connect 2 unadaptable types: " + a.GetType() + " -> " + b.GetType()); - return false; - } - object retVal = mi.Invoke(this, new[] { this, a, b }); - return (bool)retVal; - } - - IEnumerable GetExtensionMethods(Assembly assembly, Type extendedType) - { - return assembly.GetTypes() - .Where(t => t.IsSealed && !t.IsGenericType && !t.IsNested) - .SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) - .Where(m => m.IsDefined(typeof(ExtensionAttribute), false) && m.GetParameters()[0].ParameterType == extendedType); - } - - public MethodInfo GetAdapter(object a, object b) - { - if (a == null || b == null) - return null; - - if (s_NodeAdapterDictionary == null) - { - s_NodeAdapterDictionary = new Dictionary(); - - // add extension methods - AppDomain currentDomain = AppDomain.CurrentDomain; - foreach (Assembly assembly in currentDomain.GetAssemblies()) - { - foreach (MethodInfo method in GetExtensionMethods(assembly, typeof(NodeAdapter))) - { - ParameterInfo[] methodParams = method.GetParameters(); - if (methodParams.Length == 3) - { - string pa = methodParams[1].ParameterType + methodParams[2].ParameterType.ToString(); - int hash = pa.GetHashCode(); - if (s_NodeAdapterDictionary.ContainsKey(hash)) - { - Debug.Log("NodeAdapter: multiple extensions have the same signature:\n" + - "1: " + method + "\n" + - "2: " + s_NodeAdapterDictionary[hash]); - } - else - { - s_NodeAdapterDictionary.Add(hash, method); - } - } - } - } - } - - string s = a.GetType().ToString() + b.GetType(); - - MethodInfo methodInfo; - return s_NodeAdapterDictionary.TryGetValue(s.GetHashCode(), out methodInfo) ? methodInfo : null; - } - - public MethodInfo GetTypeAdapter(Type from, Type to) - { - if (s_TypeAdapters == null) - { - s_TypeAdapters = new List(); - AppDomain currentDomain = AppDomain.CurrentDomain; - foreach (Assembly assembly in currentDomain.GetAssemblies()) - { - try - { - foreach (Type temptype in assembly.GetTypes()) - { - MethodInfo[] methodInfos = temptype.GetMethods(BindingFlags.Public | BindingFlags.Static); - foreach (MethodInfo i in methodInfos) - { - object[] allAttrs = i.GetCustomAttributes(typeof(TypeAdapter), false); - if (allAttrs.Any()) - { - s_TypeAdapters.Add(i); - } - } - } - } - catch (Exception ex) - { - Debug.Log(ex); - } - } - } - - - foreach (MethodInfo i in s_TypeAdapters) - { - if (i.ReturnType == to) - { - ParameterInfo[] allParams = i.GetParameters(); - if (allParams.Length == 1) - { - if (allParams[0].ParameterType == from) - return i; - } - } - } - return null; - } - } -} diff --git a/Modules/GraphViewEditor/NodeSearch/SearchTree.cs b/Modules/GraphViewEditor/NodeSearch/SearchTree.cs deleted file mode 100644 index 006532a08e..0000000000 --- a/Modules/GraphViewEditor/NodeSearch/SearchTree.cs +++ /dev/null @@ -1,47 +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.Experimental.UIElements.GraphView -{ - [Serializable] - public class SearchTreeEntry : IComparable - { - public int level; - public GUIContent content; - - public object userData; - - public SearchTreeEntry(GUIContent content) - { - this.content = content; - } - - public string name - { - get { return content.text; } - } - - public int CompareTo(SearchTreeEntry o) - { - return name.CompareTo(o.name); - } - } - - [Serializable] - public class SearchTreeGroupEntry : SearchTreeEntry - { - internal int selectedIndex; - internal Vector2 scroll; - - public SearchTreeGroupEntry(GUIContent content, int level = 0) - : base(content) - { - this.content = content; - this.level = level; - } - } -} diff --git a/Modules/GraphViewEditor/Orientation.cs b/Modules/GraphViewEditor/Orientation.cs deleted file mode 100644 index 96c2377600..0000000000 --- a/Modules/GraphViewEditor/Orientation.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 Orientation - { - Horizontal, - Vertical - } -} diff --git a/Modules/GraphViewEditor/Utils/RectUtils.cs b/Modules/GraphViewEditor/Utils/RectUtils.cs deleted file mode 100644 index 77ba254c5e..0000000000 --- a/Modules/GraphViewEditor/Utils/RectUtils.cs +++ /dev/null @@ -1,92 +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.Experimental.UIElements.GraphView -{ - public class RectUtils - { - public static bool IntersectsSegment(Rect rect, Vector2 p1, Vector2 p2) - { - float minX = Mathf.Min(p1.x, p2.x); - float maxX = Mathf.Max(p1.x, p2.x); - - if (maxX > rect.xMax) - { - maxX = rect.xMax; - } - - if (minX < rect.xMin) - { - minX = rect.xMin; - } - - if (minX > maxX) - { - return false; - } - - float minY = Mathf.Min(p1.y, p2.y); - float maxY = Mathf.Max(p1.y, p2.y); - - float dx = p2.x - p1.x; - - if (Mathf.Abs(dx) > float.Epsilon) - { - float a = (p2.y - p1.y) / dx; - float b = p1.y - a * p1.x; - minY = a * minX + b; - maxY = a * maxX + b; - } - - if (minY > maxY) - { - float tmp = maxY; - maxY = minY; - minY = tmp; - } - - if (maxY > rect.yMax) - { - maxY = rect.yMax; - } - - if (minY < rect.yMin) - { - minY = rect.yMin; - } - - if (minY > maxY) - { - return false; - } - - return true; - } - - public static Rect Encompass(Rect a, Rect b) - { - return new Rect - { - xMin = Math.Min(a.xMin, b.xMin), - yMin = Math.Min(a.yMin, b.yMin), - xMax = Math.Max(a.xMax, b.xMax), - yMax = Math.Max(a.yMax, b.yMax) - }; - } - - public static Rect Inflate(Rect a, float left, float top, float right, float bottom) - { - return new Rect - { - xMin = a.xMin - left, - yMin = a.yMin - top, - xMax = a.xMax + right, - yMax = a.yMax + bottom - }; - } - } -} diff --git a/Modules/GraphViewEditor/Views/GraphView.cs b/Modules/GraphViewEditor/Views/GraphView.cs index e65244ab2c..a22ce0220b 100644 --- a/Modules/GraphViewEditor/Views/GraphView.cs +++ b/Modules/GraphViewEditor/Views/GraphView.cs @@ -44,6 +44,7 @@ public struct GraphViewChange // Operations Completed public List movedElements; + public Vector2 moveDelta; } public struct NodeCreationContext diff --git a/Modules/Grid/Managed/Grid.cs b/Modules/Grid/Managed/Grid.cs deleted file mode 100644 index a98aebb2e6..0000000000 --- a/Modules/Grid/Managed/Grid.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 UnityEngine -{ - public partial class Grid - { - public Vector3 GetCellCenterLocal(Vector3Int position) { return CellToLocalInterpolated(position + GetLayoutCellCenter()); } - public Vector3 GetCellCenterWorld(Vector3Int position) { return LocalToWorld(CellToLocalInterpolated(position + GetLayoutCellCenter())); } - } -} diff --git a/Modules/Grid/ScriptBindings/Grid.bindings.cs b/Modules/Grid/ScriptBindings/Grid.bindings.cs deleted file mode 100644 index 631150a4a7..0000000000 --- a/Modules/Grid/ScriptBindings/Grid.bindings.cs +++ /dev/null @@ -1,48 +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.Bindings; - -namespace UnityEngine -{ - [RequireComponent(typeof(Transform))] - [NativeHeader("Modules/Grid/Public/GridMarshalling.h")] - [NativeType(Header = "Modules/Grid/Public/Grid.h")] - public sealed partial class Grid : GridLayout - { - public new extern Vector3 cellSize - { - [FreeFunction("GridBindings::GetCellSize", HasExplicitThis = true)] - get; - [FreeFunction("GridBindings::SetCellSize", HasExplicitThis = true)] - set; - } - - public new extern Vector3 cellGap - { - [FreeFunction("GridBindings::GetCellGap", HasExplicitThis = true)] - get; - [FreeFunction("GridBindings::SetCellGap", HasExplicitThis = true)] - set; - } - - public new extern GridLayout.CellLayout cellLayout - { - get; - set; - } - - public new extern GridLayout.CellSwizzle cellSwizzle - { - get; - set; - } - - [FreeFunction("GridBindings::CellSwizzle")] - public extern static Vector3 Swizzle(GridLayout.CellSwizzle swizzle, Vector3 position); - - [FreeFunction("GridBindings::InverseCellSwizzle")] - public extern static Vector3 InverseSwizzle(GridLayout.CellSwizzle swizzle, Vector3 position); - } -} diff --git a/Modules/GridEditor/Managed/GridEditorUtility.cs b/Modules/GridEditor/Managed/GridEditorUtility.cs index 7516832bc6..59891615e0 100644 --- a/Modules/GridEditor/Managed/GridEditorUtility.cs +++ b/Modules/GridEditor/Managed/GridEditorUtility.cs @@ -216,10 +216,10 @@ public static void DrawGridMarquee(GridLayout gridLayout, BoundsInt area, Color Vector3[] cellLocals = { - gridLayout.CellToLocal(new Vector3Int(area.xMin, area.yMin, 0)), - gridLayout.CellToLocalInterpolated(new Vector3(area.xMax - 1 + cellGap.x, area.yMin, 0)), - gridLayout.CellToLocalInterpolated(new Vector3(area.xMax - 1 + cellGap.x, area.yMax - 1 + cellGap.y, 0)), - gridLayout.CellToLocalInterpolated(new Vector3(area.xMin, area.yMax - 1 + cellGap.y, 0)) + gridLayout.CellToLocal(new Vector3Int(area.xMin, area.yMin, area.zMin)), + gridLayout.CellToLocalInterpolated(new Vector3(area.xMax - 1 + cellGap.x, area.yMin, area.zMin)), + gridLayout.CellToLocalInterpolated(new Vector3(area.xMax - 1 + cellGap.x, area.yMax - 1 + cellGap.y, area.zMin)), + gridLayout.CellToLocalInterpolated(new Vector3(area.xMin, area.yMax - 1 + cellGap.y, area.zMin)) }; HandleUtility.ApplyWireMaterial(); @@ -252,34 +252,34 @@ public static void DrawSelectedHexGridArea(GridLayout gridLayout, BoundsInt area int right = horizontalCount; Vector3[] cellOffset = { - Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0, gridLayout.cellSize.y / 2, 0)), - Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(gridLayout.cellSize.x / 2, gridLayout.cellSize.y / 4, 0)), - Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(gridLayout.cellSize.x / 2, -gridLayout.cellSize.y / 4, 0)), - Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0, -gridLayout.cellSize.y / 2, 0)), - Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(-gridLayout.cellSize.x / 2, -gridLayout.cellSize.y / 4, 0)), - Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(-gridLayout.cellSize.x / 2, gridLayout.cellSize.y / 4, 0)) + Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0, gridLayout.cellSize.y / 2, area.zMin)), + Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(gridLayout.cellSize.x / 2, gridLayout.cellSize.y / 4, area.zMin)), + Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(gridLayout.cellSize.x / 2, -gridLayout.cellSize.y / 4, area.zMin)), + Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(0, -gridLayout.cellSize.y / 2, area.zMin)), + Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(-gridLayout.cellSize.x / 2, -gridLayout.cellSize.y / 4, area.zMin)), + Grid.Swizzle(gridLayout.cellSwizzle, new Vector3(-gridLayout.cellSize.x / 2, gridLayout.cellSize.y / 4, area.zMin)) }; // Fill Top and Bottom Vertices for (int x = area.min.x; x < area.max.x; x++) { - cellLocals[bottom++] = gridLayout.CellToLocal(new Vector3Int(x, area.min.y, 0)) + cellOffset[4]; - cellLocals[bottom++] = gridLayout.CellToLocal(new Vector3Int(x, area.min.y, 0)) + cellOffset[3]; - cellLocals[top--] = gridLayout.CellToLocal(new Vector3Int(x, area.max.y - 1, 0)) + cellOffset[0]; - cellLocals[top--] = gridLayout.CellToLocal(new Vector3Int(x, area.max.y - 1, 0)) + cellOffset[1]; + cellLocals[bottom++] = gridLayout.CellToLocal(new Vector3Int(x, area.min.y, area.zMin)) + cellOffset[4]; + cellLocals[bottom++] = gridLayout.CellToLocal(new Vector3Int(x, area.min.y, area.zMin)) + cellOffset[3]; + cellLocals[top--] = gridLayout.CellToLocal(new Vector3Int(x, area.max.y - 1, area.zMin)) + cellOffset[0]; + cellLocals[top--] = gridLayout.CellToLocal(new Vector3Int(x, area.max.y - 1, area.zMin)) + cellOffset[1]; } // Fill first Left and Right Vertices - cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, area.min.y, 0)) + cellOffset[5]; - cellLocals[top--] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, area.max.y - 1, 0)) + cellOffset[2]; + cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, area.min.y, area.zMin)) + cellOffset[5]; + cellLocals[top--] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, area.max.y - 1, area.zMin)) + cellOffset[2]; // Fill Left and Right Vertices for (int y = area.min.y + 1; y < area.max.y; y++) { - cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, y, 0)) + cellOffset[4]; - cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, y, 0)) + cellOffset[5]; + cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, y, area.zMin)) + cellOffset[4]; + cellLocals[left--] = gridLayout.CellToLocal(new Vector3Int(area.min.x, y, area.zMin)) + cellOffset[5]; } for (int y = area.min.y; y < (area.max.y - 1); y++) { - cellLocals[right++] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, y, 0)) + cellOffset[2]; - cellLocals[right++] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, y, 0)) + cellOffset[1]; + cellLocals[right++] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, y, area.zMin)) + cellOffset[2]; + cellLocals[right++] = gridLayout.CellToLocal(new Vector3Int(area.max.x - 1, y, area.zMin)) + cellOffset[1]; } HandleUtility.ApplyWireMaterial(); GL.PushMatrix(); diff --git a/Modules/IMGUI/EventCommandNames.cs b/Modules/IMGUI/EventCommandNames.cs deleted file mode 100644 index a45b3bb89d..0000000000 --- a/Modules/IMGUI/EventCommandNames.cs +++ /dev/null @@ -1,48 +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.Runtime.InteropServices; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - internal static class EventCommandNames - { - //Some of these strings are also hardcoded on the native side. Change them at your own risk! - public const string Cut = "Cut"; - public const string Copy = "Copy"; - public const string Paste = "Paste"; - public const string SelectAll = "SelectAll"; - public const string Duplicate = "Duplicate"; - public const string Delete = "Delete"; - public const string SoftDelete = "SoftDelete"; - public const string Find = "Find"; - - public const string UndoRedoPerformed = "UndoRedoPerformed"; - public const string OnLostFocus = "OnLostFocus"; - - //Used by IMGUIContainer to force editing textfield when focus is changed with tab - public const string NewKeyboardFocus = "NewKeyboardFocus"; - public const string ModifierKeysChanged = "ModifierKeysChanged"; - - //Used by ColorPicker - public const string EyeDropperUpdate = "EyeDropperUpdate"; - public const string EyeDropperClicked = "EyeDropperClicked"; - public const string EyeDropperCancelled = "EyeDropperCancelled"; - public const string ColorPickerChanged = "ColorPickerChanged"; - - - public const string FrameSelected = "FrameSelected"; - public const string FrameSelectedWithLock = "FrameSelectedWithLock"; - - - /* - public const string = ""; - public const string = ""; - public const string = ""; - public const string = ""; -*/ - } -} diff --git a/Modules/IMGUI/EventInterests.cs b/Modules/IMGUI/EventInterests.cs deleted file mode 100644 index d2717f7863..0000000000 --- a/Modules/IMGUI/EventInterests.cs +++ /dev/null @@ -1,29 +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.Bindings; - -namespace UnityEngine -{ - [VisibleToOtherModules("UnityEngine.UIElementsModule")] - internal struct EventInterests - { - public bool wantsMouseMove { get; set; } - public bool wantsMouseEnterLeaveWindow { get; set; } - - public bool WantsEvent(EventType type) - { - switch (type) - { - case EventType.MouseMove: - return wantsMouseMove; - case EventType.MouseEnterWindow: - case EventType.MouseLeaveWindow: - return wantsMouseEnterLeaveWindow; - default: - return true; - } - } - } -} diff --git a/Modules/IMGUI/FriendAttributes.cs b/Modules/IMGUI/FriendAttributes.cs deleted file mode 100644 index 373794d0f2..0000000000 --- a/Modules/IMGUI/FriendAttributes.cs +++ /dev/null @@ -1,8 +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.Runtime.CompilerServices; - -// needed for UnityEngine.IStylePainter -[assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")] diff --git a/Modules/IMGUI/GUIDebugger.bindings.cs b/Modules/IMGUI/GUIDebugger.bindings.cs deleted file mode 100644 index d2fc2a88ef..0000000000 --- a/Modules/IMGUI/GUIDebugger.bindings.cs +++ /dev/null @@ -1,37 +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.Bindings; -using System; - -namespace UnityEngine -{ - [NativeHeader("Modules/IMGUI/GUIDebugger.bindings.h")] - internal partial class GUIDebugger - { - //TODO: We could skip the trip to native if we check here if the current GUIVIew is being debugged. - [NativeConditional("UNITY_EDITOR")] - public static extern void LogLayoutEntry(Rect rect, RectOffset margins, GUIStyle style); - - [NativeConditional("UNITY_EDITOR")] - public static extern void LogLayoutGroupEntry(Rect rect, RectOffset margins, GUIStyle style, bool isVertical); - - [NativeConditional("UNITY_EDITOR")] - [StaticAccessor("GetGUIDebuggerManager()", StaticAccessorType.Dot)] - [NativeMethod("LogEndGroup")] - public static extern void LogLayoutEndGroup(); - - [NativeConditional("UNITY_EDITOR")] - [StaticAccessor("GetGUIDebuggerManager()", StaticAccessorType.Dot)] - public static extern void LogBeginProperty(string targetTypeAssemblyQualifiedName, string path, Rect position); - - [NativeConditional("UNITY_EDITOR")] - [StaticAccessor("GetGUIDebuggerManager()", StaticAccessorType.Dot)] - public static extern void LogEndProperty(); - - [NativeConditional("UNITY_EDITOR")] - public static extern bool active {get; } - } -} diff --git a/Modules/IMGUI/GUIEnums.cs b/Modules/IMGUI/GUIEnums.cs deleted file mode 100644 index b095d71278..0000000000 --- a/Modules/IMGUI/GUIEnums.cs +++ /dev/null @@ -1,30 +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 UnityEngine -{ - // Scaling mode to draw textures with - public enum ScaleMode - { - // Stretches the texture to fill the complete rectangle passed in to GUI.DrawTexture - StretchToFill = 0, - // Scales the texture, maintaining aspect ratio, so it completely covers the /position/ rectangle passed to GUI.DrawTexture. If the texture is being draw to a rectangle with a different aspect ratio than the original, the image is cropped. - ScaleAndCrop = 1, - // Scales the texture, maintaining aspect ratio, so it completely fits withing the /position/ rectangle passed to GUI.DrawTexture. - ScaleToFit = 2 - } - - // Used by GUIUtility.GetcontrolID to inform the UnityGUI system if a given control can get keyboard focus. - public enum FocusType - { - [Obsolete("FocusType.Native now behaves the same as FocusType.Passive in all OS cases. (UnityUpgradable) -> Passive", false)] - Native = 0, - // This is a proper keyboard control. It can have input focus on all platforms. Used for TextField and TextArea controls - Keyboard = 1, - // This control can never receive keyboard focus. - Passive = 2 - } -} diff --git a/Modules/IMGUI/GUILayout.cs b/Modules/IMGUI/GUILayout.cs index 193026aef4..f204f4e28a 100644 --- a/Modules/IMGUI/GUILayout.cs +++ b/Modules/IMGUI/GUILayout.cs @@ -242,6 +242,11 @@ static public void FlexibleSpace() op.value = 10000; GUILayoutUtility.GetRect(0, 0, GUILayoutUtility.spaceStyle, op); + + if (Event.current.type == EventType.Layout) + { + GUILayoutUtility.current.topLevel.entries[GUILayoutUtility.current.topLevel.entries.Count - 1].consideredForMargin = false; + } } public static void BeginHorizontal(params GUILayoutOption[] options) { BeginHorizontal(GUIContent.none, GUIStyle.none, options); } diff --git a/Modules/IMGUI/GUILayoutOption.cs b/Modules/IMGUI/GUILayoutOption.cs deleted file mode 100644 index 6d61e6a510..0000000000 --- a/Modules/IMGUI/GUILayoutOption.cs +++ /dev/null @@ -1,29 +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 UnityEngine -{ - // Class internally used to pass layout options into [[GUILayout]] functions. You don't use these directly, but construct them with the layouting functions in the [[GUILayout]] class. - public sealed class GUILayoutOption - { - internal enum Type - { - fixedWidth, fixedHeight, minWidth, maxWidth, minHeight, maxHeight, stretchWidth, stretchHeight, - // These are just for the spacing variables - alignStart, alignMiddle, alignEnd, alignJustify, equalSize, spacing - } - // *undocumented* - internal Type type; - // *undocumented* - internal object value; - // *undocumented* - internal GUILayoutOption(Type type, object value) - { - this.type = type; - this.value = value; - } - } -} diff --git a/Modules/IMGUI/GUIStateObjects.cs b/Modules/IMGUI/GUIStateObjects.cs deleted file mode 100644 index 319c1a486c..0000000000 --- a/Modules/IMGUI/GUIStateObjects.cs +++ /dev/null @@ -1,43 +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.Reflection; -using UnityEngineInternal; - -namespace UnityEngine -{ - internal class GUIStateObjects - { - static Dictionary s_StateCache = new Dictionary(); - - [System.Security.SecuritySafeCritical] - internal static object GetStateObject(System.Type t, int controlID) - { - object o; - if (!s_StateCache.TryGetValue(controlID, out o) || o.GetType() != t) - { - o = System.Activator.CreateInstance(t); - s_StateCache[controlID] = o; - } - return o; - } - - internal static object QueryStateObject(System.Type t, int controlID) - { - object o = s_StateCache[controlID]; - if (t.IsInstanceOfType(o)) - { - return o; - } - return null; - } - - static internal void Tests_ClearObjects() - { - s_StateCache.Clear(); - } - } -} diff --git a/Modules/IMGUI/GUIStyle.cs b/Modules/IMGUI/GUIStyle.cs index 074efdb66a..7e90f54d74 100644 --- a/Modules/IMGUI/GUIStyle.cs +++ b/Modules/IMGUI/GUIStyle.cs @@ -80,6 +80,11 @@ public GUIStyle() // Constructs GUIStyle identical to given other GUIStyle. public GUIStyle(GUIStyle other) { + if (other == null) + { + Debug.LogError("Copied style is null. Using StyleNotFound instead."); + other = GUISkin.error; + } m_Ptr = Internal_Copy(this, other); } diff --git a/Modules/IMGUI/GUITargetAttribute.cs b/Modules/IMGUI/GUITargetAttribute.cs deleted file mode 100644 index c8bdf2a2b5..0000000000 --- a/Modules/IMGUI/GUITargetAttribute.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 System; -using System.Runtime.CompilerServices; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - /// Controls for which screen the OnGUI is called - [AttributeUsage(AttributeTargets.Method)] - public class GUITargetAttribute : Attribute - { - internal int displayMask; - - public GUITargetAttribute() { displayMask = -1; } - - public GUITargetAttribute(int displayIndex) - { - displayMask = 1 << displayIndex; - } - - public GUITargetAttribute(int displayIndex, int displayIndex1) - { - displayMask = (1 << displayIndex) | (1 << displayIndex1); - } - - public GUITargetAttribute(int displayIndex, int displayIndex1, params int[] displayIndexList) - { - displayMask = (1 << displayIndex) | (1 << displayIndex1); - for (int i = 0; i < displayIndexList.Length; i++) - displayMask |= 1 << displayIndexList[i]; - } - - [RequiredByNativeCode] - static int GetGUITargetAttrValue(Type klass, string methodName) - { - var method = klass.GetMethod(methodName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); - if (method != null) - { - object[] attrs = method.GetCustomAttributes(true); - if (attrs != null) - { - for (int i = 0; i < attrs.Length; ++i) - { - if (attrs[i].GetType() != typeof(GUITargetAttribute)) - continue; - - GUITargetAttribute attr = attrs[i] as GUITargetAttribute; - return attr.displayMask; - } - } - } - - return -1; - } - } -} diff --git a/Modules/IMGUI/ObjectGUIState.bindings.cs b/Modules/IMGUI/ObjectGUIState.bindings.cs deleted file mode 100644 index 219ed949b5..0000000000 --- a/Modules/IMGUI/ObjectGUIState.bindings.cs +++ /dev/null @@ -1,46 +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.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Modules/IMGUI/GUIState.h")] - [VisibleToOtherModules("UnityEngine.UIElementsModule")] - internal class ObjectGUIState : IDisposable - { - internal IntPtr m_Ptr; - - public ObjectGUIState() - { - m_Ptr = Internal_Create(); - } - - public void Dispose() - { - Destroy(); - GC.SuppressFinalize(this); - } - - ~ObjectGUIState() - { - Destroy(); - } - - void Destroy() - { - if (m_Ptr != IntPtr.Zero) - { - Internal_Destroy(m_Ptr); - m_Ptr = IntPtr.Zero; - } - } - - private static extern IntPtr Internal_Create(); - - [NativeMethod(IsThreadSafe = true)] - private static extern void Internal_Destroy(IntPtr ptr); - } -} diff --git a/Modules/IMGUI/ScrollViewState.cs b/Modules/IMGUI/ScrollViewState.cs deleted file mode 100644 index 72ea999275..0000000000 --- a/Modules/IMGUI/ScrollViewState.cs +++ /dev/null @@ -1,94 +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.Scripting; - -namespace UnityEngine -{ - internal class ScrollViewState - { - public Rect position; - public Rect visibleRect; - public Rect viewRect; - public Vector2 scrollPosition; - public bool apply; - - [RequiredByNativeCode] // Created by reflection from GUI.BeginScrollView - public ScrollViewState() {} - - public void ScrollTo(Rect pos) - { - ScrollTowards(pos, Mathf.Infinity); - } - - public bool ScrollTowards(Rect pos, float maxDelta) - { - Vector2 scrollVector = ScrollNeeded(pos); - - // If we don't need scrolling, return false - if (scrollVector.sqrMagnitude < 0.0001f) - return false; - - // If we need scrolling but don't actually allow any, just return true to - // indicate scrolling is needed to be able to see pos - if (maxDelta == 0) - return true; - - // Clamp scrolling to max allowed delta - if (scrollVector.magnitude > maxDelta) - scrollVector = scrollVector.normalized * maxDelta; - - // Apply scrolling - scrollPosition += scrollVector; - apply = true; - - return true; - } - - private Vector2 ScrollNeeded(Rect pos) - { - Rect r = visibleRect; - r.x += scrollPosition.x; - r.y += scrollPosition.y; - - // If the rect we want to see is larger than the visible rect, then trim it, - // otherwise we can get oscillation or other unwanted behavior - float excess = pos.width - visibleRect.width; - if (excess > 0) - { - pos.width -= excess; - pos.x += excess * 0.5f; - } - excess = pos.height - visibleRect.height; - if (excess > 0) - { - pos.height -= excess; - pos.y += excess * 0.5f; - } - - Vector2 scrollVector = Vector2.zero; - - // Calculate needed x scrolling - if (pos.xMax > r.xMax) - scrollVector.x += pos.xMax - r.xMax; - else if (pos.xMin < r.xMin) - scrollVector.x -= r.xMin - pos.xMin; - - // Calculate needed y scrolling - if (pos.yMax > r.yMax) - scrollVector.y += pos.yMax - r.yMax; - else if (pos.yMin < r.yMin) - scrollVector.y -= r.yMin - pos.yMin; - - // Clamp scrolling to bounds so we don't request to scroll past the edge - Rect actualViewRect = viewRect; - actualViewRect.width = Mathf.Max(actualViewRect.width, visibleRect.width); - actualViewRect.height = Mathf.Max(actualViewRect.height, visibleRect.height); - scrollVector.x = Mathf.Clamp(scrollVector.x, actualViewRect.xMin - scrollPosition.x, actualViewRect.xMax - visibleRect.width - scrollPosition.x); - scrollVector.y = Mathf.Clamp(scrollVector.y, actualViewRect.yMin - scrollPosition.y, actualViewRect.yMax - visibleRect.height - scrollPosition.y); - - return scrollVector; - } - } -} diff --git a/Modules/IMGUI/TextEditor.cs b/Modules/IMGUI/TextEditor.cs deleted file mode 100644 index 3991e7cdfe..0000000000 --- a/Modules/IMGUI/TextEditor.cs +++ /dev/null @@ -1,1456 +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.Bindings; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine -{ - public class TextEditor - { - public TouchScreenKeyboard keyboardOnScreen = null; - public int controlID = 0; - public GUIStyle style = GUIStyle.none; - public bool multiline = false; - public bool hasHorizontalCursorPos = false; - public bool isPasswordField = false; - [VisibleToOtherModules("UnityEngine.UIElementsModule")] - internal bool m_HasFocus; - public Vector2 scrollOffset = Vector2.zero; // The text field can have a scroll offset in order to display its contents - - private GUIContent m_Content = new GUIContent(); - private Rect m_Position; - private int m_CursorIndex = 0; - private int m_SelectIndex = 0; - private bool m_RevealCursor = false; - - [Obsolete("Please use 'text' instead of 'content'", false)] - public GUIContent content - { - get { return m_Content; } - set { m_Content = value; } - } - - public string text - { - get { return m_Content.text; } - set - { - m_Content.text = value ?? string.Empty; - EnsureValidCodePointIndex(ref m_CursorIndex); - EnsureValidCodePointIndex(ref m_SelectIndex); - } - } - - public Rect position - { - get { return m_Position; } - set - { - if (m_Position == value) - return; - - m_Position = value; - - UpdateScrollOffset(); - } - } - - internal virtual Rect localPosition - { - [VisibleToOtherModules("UnityEngine.UIElementsModule")] - get { return position; } - } - - public int cursorIndex - { - get { return m_CursorIndex; } - set - { - int oldCursorIndex = m_CursorIndex; - m_CursorIndex = value; - EnsureValidCodePointIndex(ref m_CursorIndex); - - if (m_CursorIndex != oldCursorIndex) - { - m_RevealCursor = true; - OnCursorIndexChange(); - } - } - } - - public int selectIndex - { - get { return m_SelectIndex; } - set - { - int oldSelectIndex = m_SelectIndex; - m_SelectIndex = value; - EnsureValidCodePointIndex(ref m_SelectIndex); - - if (m_SelectIndex != oldSelectIndex) - OnSelectIndexChange(); - } - } - - // are we up/downing? - public Vector2 graphicalCursorPos; - public Vector2 graphicalSelectCursorPos; - - // Clear the cursor position for vertical movement... - void ClearCursorPos() {hasHorizontalCursorPos = false; m_iAltCursorPos = -1; } - - // selection - bool m_MouseDragSelectsWholeWords = false; - int m_DblClickInitPos = 0; - DblClickSnapping m_DblClickSnap = DblClickSnapping.WORDS; - public DblClickSnapping doubleClickSnapping { get { return m_DblClickSnap; } set { m_DblClickSnap = value; } } - bool m_bJustSelected = false; - - int m_iAltCursorPos = -1; - public int altCursorPosition { get { return m_iAltCursorPos; } set { m_iAltCursorPos = value; } } - - public enum DblClickSnapping : byte { WORDS, PARAGRAPHS }; - - [RequiredByNativeCode] - public TextEditor() - { - } - - public void OnFocus() - { - if (multiline) - cursorIndex = selectIndex = 0; - else - SelectAll(); - m_HasFocus = true; - } - - public void OnLostFocus() - { - m_HasFocus = false; - scrollOffset = Vector2.zero; - } - - void GrabGraphicalCursorPos() - { - if (!hasHorizontalCursorPos) - { - graphicalCursorPos = style.GetCursorPixelPosition(localPosition, m_Content, cursorIndex); - graphicalSelectCursorPos = style.GetCursorPixelPosition(localPosition, m_Content, selectIndex); - hasHorizontalCursorPos = false; - } - } - - // Handle a key event. - // Looks up the platform-dependent key-action table & performs the event - // return true if the event was recognized. - public bool HandleKeyEvent(Event e) - { - InitKeyActions(); - EventModifiers m = e.modifiers; - e.modifiers &= ~EventModifiers.CapsLock; - if (s_Keyactions.ContainsKey(e)) - { - TextEditOp op = (TextEditOp)s_Keyactions[e]; - PerformOperation(op); - e.modifiers = m; - return true; - } - e.modifiers = m; - return false; - } - - // Deletes previous text on the line - public bool DeleteLineBack() - { - if (hasSelection) - { - DeleteSelection(); - return true; - } - int p = cursorIndex; - int i = p; - while (i-- != 0) - if (text[i] == '\n') - { - p = i + 1; - break; - } - if (i == -1) - p = 0; - if (cursorIndex != p) - { - m_Content.text = text.Remove(p, cursorIndex - p); - selectIndex = cursorIndex = p; - return true; - } - return false; - } - - // Deletes the previous word - public bool DeleteWordBack() - { - if (hasSelection) - { - DeleteSelection(); - return true; - } - - int prevWordEnd = FindEndOfPreviousWord(cursorIndex); - if (cursorIndex != prevWordEnd) - { - m_Content.text = text.Remove(prevWordEnd, cursorIndex - prevWordEnd); - selectIndex = cursorIndex = prevWordEnd; - return true; - } - return false; - } - - // Deletes the following word - public bool DeleteWordForward() - { - if (hasSelection) - { - DeleteSelection(); - return true; - } - - int nextWordStart = FindStartOfNextWord(cursorIndex); - if (cursorIndex < text.Length) - { - m_Content.text = text.Remove(cursorIndex, nextWordStart - cursorIndex); - return true; - } - return false; - } - - // perform a right-delete - public bool Delete() - { - if (hasSelection) - { - DeleteSelection(); - return true; - } - else if (cursorIndex < text.Length) - { - m_Content.text = text.Remove(cursorIndex, NextCodePointIndex(cursorIndex) - cursorIndex); - return true; - } - return false; - } - - public bool CanPaste() - { - return GUIUtility.systemCopyBuffer.Length != 0; - } - - // Perform a left-delete - public bool Backspace() - { - if (hasSelection) - { - DeleteSelection(); - return true; - } - else if (cursorIndex > 0) - { - var startIndex = PreviousCodePointIndex(cursorIndex); - m_Content.text = text.Remove(startIndex, cursorIndex - startIndex); - selectIndex = cursorIndex = startIndex; - ClearCursorPos(); - return true; - } - return false; - } - - /// Select all the text - public void SelectAll() - { - cursorIndex = 0; selectIndex = text.Length; - ClearCursorPos(); - } - - /// Select none of the text - public void SelectNone() - { - selectIndex = cursorIndex; - ClearCursorPos(); - } - - /// Does this text field has a selection - public bool hasSelection { get { return cursorIndex != selectIndex; } } - - /// Returns the selected text - public string SelectedText - { - get - { - if (cursorIndex == selectIndex) - return ""; - if (cursorIndex < selectIndex) - return text.Substring(cursorIndex, selectIndex - cursorIndex); - else - return text.Substring(selectIndex, cursorIndex - selectIndex); - } - } - - /// Delete the current selection. If there is no selection, this function does not do anything... - public bool DeleteSelection() - { - if (cursorIndex == selectIndex) - return false; - if (cursorIndex < selectIndex) - { - m_Content.text = text.Substring(0, cursorIndex) + text.Substring(selectIndex, text.Length - selectIndex); - selectIndex = cursorIndex; - } - else - { - m_Content.text = text.Substring(0, selectIndex) + text.Substring(cursorIndex, text.Length - cursorIndex); - cursorIndex = selectIndex; - } - ClearCursorPos(); - - return true; - } - - /// Replace the selection with /replace/. If there is no selection, /replace/ is inserted at the current cursor point. - public void ReplaceSelection(string replace) - { - DeleteSelection(); - m_Content.text = text.Insert(cursorIndex, replace); - selectIndex = cursorIndex += replace.Length; - ClearCursorPos(); - } - - /// Replacted the selection with /c/ - public void Insert(char c) - { - ReplaceSelection(c.ToString()); - } - - /// Move selection to alt cursor /position/ - public void MoveSelectionToAltCursor() - { - if (m_iAltCursorPos == -1) - return; - int p = m_iAltCursorPos; - string tmp = SelectedText; - m_Content.text = text.Insert(p, tmp); - - if (p < cursorIndex) - { - cursorIndex += tmp.Length; - selectIndex += tmp.Length; - } - - DeleteSelection(); - - selectIndex = cursorIndex = p; - ClearCursorPos(); - } - - /// Move the cursor one character to the right and deselect. - public void MoveRight() - { - ClearCursorPos(); - if (selectIndex == cursorIndex) - { - cursorIndex = NextCodePointIndex(cursorIndex); - DetectFocusChange(); // TODO: Is this necessary? - selectIndex = cursorIndex; - } - else - { - if (selectIndex > cursorIndex) - cursorIndex = selectIndex; - else - selectIndex = cursorIndex; - } - } - - /// Move the cursor one character to the left and deselect. - public void MoveLeft() - { - if (selectIndex == cursorIndex) - { - cursorIndex = PreviousCodePointIndex(cursorIndex); - selectIndex = cursorIndex; - } - else - { - if (selectIndex > cursorIndex) - selectIndex = cursorIndex; - else - cursorIndex = selectIndex; - } - ClearCursorPos(); - } - - /// Move the cursor up and deselects. - public void MoveUp() - { - if (selectIndex < cursorIndex) - selectIndex = cursorIndex; - else - cursorIndex = selectIndex; - GrabGraphicalCursorPos(); - graphicalCursorPos.y -= 1; - cursorIndex = selectIndex = style.GetCursorStringIndex(localPosition, m_Content, graphicalCursorPos); - if (cursorIndex <= 0) - ClearCursorPos(); - } - - /// Move the cursor down and deselects. - public void MoveDown() - { - if (selectIndex > cursorIndex) - selectIndex = cursorIndex; - else - cursorIndex = selectIndex; - GrabGraphicalCursorPos(); - graphicalCursorPos.y += style.lineHeight + 5; - cursorIndex = selectIndex = style.GetCursorStringIndex(localPosition, m_Content, graphicalCursorPos); - if (cursorIndex == text.Length) - ClearCursorPos(); - } - - /// Moves the cursor to the start of the current line. - public void MoveLineStart() - { - // we start from the left-most selected character - int p = selectIndex < cursorIndex ? selectIndex : cursorIndex; - // then we scan back to find the first newline - int i = p; - while (i-- != 0) - if (text[i] == '\n') - { - selectIndex = cursorIndex = i + 1; - return; - } - selectIndex = cursorIndex = 0; - } - - /// Moves the selection to the end of the current line - public void MoveLineEnd() - { - // we start from the right-most selected character - int p = selectIndex > cursorIndex ? selectIndex : cursorIndex; - // then we scan forward to find the first newline - int i = p; - int strlen = text.Length; - while (i < strlen) - { - if (text[i] == '\n') - { - selectIndex = cursorIndex = i; - return; - } - i++; - } - selectIndex = cursorIndex = strlen; - } - - /// Move to the start of the current graphical line. This takes word-wrapping into consideration. - public void MoveGraphicalLineStart() - { - cursorIndex = selectIndex = GetGraphicalLineStart(cursorIndex < selectIndex ? cursorIndex : selectIndex); - } - - /// Move to the end of the current graphical line. This takes word-wrapping into consideration. - public void MoveGraphicalLineEnd() - { - cursorIndex = selectIndex = GetGraphicalLineEnd(cursorIndex > selectIndex ? cursorIndex : selectIndex); - } - - /// Moves the cursor to the beginning of the text - public void MoveTextStart() - { - selectIndex = cursorIndex = 0; - } - - /// Moves the cursor to the end of the text - public void MoveTextEnd() - { - selectIndex = cursorIndex = text.Length; - } - - private int IndexOfEndOfLine(int startIndex) - { - int index = text.IndexOf('\n', startIndex); - return (index != -1 ? index : text.Length); - } - - /// Move to the next paragraph - public void MoveParagraphForward() - { - cursorIndex = cursorIndex > selectIndex ? cursorIndex : selectIndex; - if (cursorIndex < text.Length) - { - selectIndex = cursorIndex = IndexOfEndOfLine(cursorIndex + 1); - } - } - - /// Move to the previous paragraph - public void MoveParagraphBackward() - { - cursorIndex = cursorIndex < selectIndex ? cursorIndex : selectIndex; - if (cursorIndex > 1) - { - selectIndex = cursorIndex = text.LastIndexOf('\n', cursorIndex - 2) + 1; - } - else - selectIndex = cursorIndex = 0; - } - - // - - // Move the cursor to a graphical position. Used for moving the cursor on MouseDown events. - public void MoveCursorToPosition(Vector2 cursorPosition) - { - MoveCursorToPosition_Internal(cursorPosition, Event.current.shift); - } - - // Move the cursor to a graphical position. Used for moving the cursor on MouseDown events. - protected internal void MoveCursorToPosition_Internal(Vector2 cursorPosition, bool shift) - { - selectIndex = style.GetCursorStringIndex(localPosition, m_Content, cursorPosition + scrollOffset); - - if (!shift) - { - cursorIndex = selectIndex; - } - - DetectFocusChange(); // TODO: Is this necessary? - } - - public void MoveAltCursorToPosition(Vector2 cursorPosition) - { - int index = style.GetCursorStringIndex(localPosition, m_Content, cursorPosition + scrollOffset); - m_iAltCursorPos = Mathf.Min(text.Length, index); - DetectFocusChange(); // TODO: Is this necessary? - } - - public bool IsOverSelection(Vector2 cursorPosition) - { - int p = style.GetCursorStringIndex(localPosition, m_Content, cursorPosition + scrollOffset); - return ((p < Mathf.Max(cursorIndex, selectIndex)) && (p > Mathf.Min(cursorIndex, selectIndex))); - } - - // Do a drag selection. Used to expand the selection in MouseDrag events. - public void SelectToPosition(Vector2 cursorPosition) - { - if (!m_MouseDragSelectsWholeWords) - cursorIndex = style.GetCursorStringIndex(localPosition, m_Content, cursorPosition + scrollOffset); - else // snap to words/paragraphs - { - int p = style.GetCursorStringIndex(localPosition, m_Content, cursorPosition + scrollOffset); - - EnsureValidCodePointIndex(ref p); - EnsureValidCodePointIndex(ref m_DblClickInitPos); - - if (m_DblClickSnap == DblClickSnapping.WORDS) - { - if (p < m_DblClickInitPos) - { - cursorIndex = FindEndOfClassification(p, Direction.Backward); - selectIndex = FindEndOfClassification(m_DblClickInitPos, Direction.Forward); - } - else - { - cursorIndex = FindEndOfClassification(p, Direction.Forward); - selectIndex = FindEndOfClassification(m_DblClickInitPos, Direction.Backward); - } - } // paragraph - else - { - if (p < m_DblClickInitPos) - { - if (p > 0) - cursorIndex = text.LastIndexOf('\n', Mathf.Max(0, p - 2)) + 1; - else - cursorIndex = 0; - - selectIndex = text.LastIndexOf('\n', m_DblClickInitPos); - } - else - { - if (p < text.Length) - { - cursorIndex = IndexOfEndOfLine(p); - } - else - cursorIndex = text.Length; - - selectIndex = text.LastIndexOf('\n', Mathf.Max(0, m_DblClickInitPos - 2)) + 1; - } - } - } - } - - /// Expand the selection to the left - public void SelectLeft() - { - if (m_bJustSelected) - if (cursorIndex > selectIndex) - { // swap - int tmp = cursorIndex; - cursorIndex = selectIndex; - selectIndex = tmp; - } - m_bJustSelected = false; - - cursorIndex = PreviousCodePointIndex(cursorIndex); - } - - public void SelectRight() - { - if (m_bJustSelected) - if (cursorIndex < selectIndex) - { // swap - int tmp = cursorIndex; - cursorIndex = selectIndex; - selectIndex = tmp; - } - m_bJustSelected = false; - - cursorIndex = NextCodePointIndex(cursorIndex); - } - - public void SelectUp() - { - GrabGraphicalCursorPos(); - graphicalCursorPos.y -= 1; - cursorIndex = style.GetCursorStringIndex(localPosition, m_Content, graphicalCursorPos); - } - - public void SelectDown() - { - GrabGraphicalCursorPos(); - graphicalCursorPos.y += style.lineHeight + 5; - cursorIndex = style.GetCursorStringIndex(localPosition, m_Content, graphicalCursorPos); - } - - /// Select to the end of the text - public void SelectTextEnd() - { - // This is not quite like the mac - there, when you select to end of text, the position of the cursor becomes somewhat i'll defined - // Hard to explain. In textedit, try: CMD-SHIFT-down, SHIFT-LEFT for case 1. then do CMD-SHIFT-down, SHIFT-RIGHT, SHIFT-LEFT for case 2. - // Anyways, it's wrong so we won't do that - cursorIndex = text.Length; - } - - /// Select to the start of the text - public void SelectTextStart() - { - // Same thing as SelectTextEnd... - cursorIndex = 0; - } - - /// sets whether the text selection is done by dbl click or not - public void MouseDragSelectsWholeWords(bool on) - { - m_MouseDragSelectsWholeWords = on; - m_DblClickInitPos = cursorIndex; - } - - public void DblClickSnap(DblClickSnapping snapping) - { - m_DblClickSnap = snapping; - } - - int GetGraphicalLineStart(int p) - { - Vector2 point = style.GetCursorPixelPosition(localPosition, m_Content, p); - point.x = 0; - return style.GetCursorStringIndex(localPosition, m_Content, point); - } - - int GetGraphicalLineEnd(int p) - { - Vector2 point = style.GetCursorPixelPosition(localPosition, m_Content, p); - point.x += 5000; - return style.GetCursorStringIndex(localPosition, m_Content, point); - } - - int FindNextSeperator(int startPos) - { - int textLen = text.Length; - while (startPos < textLen && ClassifyChar(startPos) != CharacterType.LetterLike) - startPos = NextCodePointIndex(startPos); - while (startPos < textLen && ClassifyChar(startPos) == CharacterType.LetterLike) - startPos = NextCodePointIndex(startPos); - return startPos; - } - - int FindPrevSeperator(int startPos) - { - startPos = PreviousCodePointIndex(startPos); - while (startPos > 0 && ClassifyChar(startPos) != CharacterType.LetterLike) - startPos = PreviousCodePointIndex(startPos); - - if (startPos == 0) - return 0; - - while (startPos > 0 && ClassifyChar(startPos) == CharacterType.LetterLike) - startPos = PreviousCodePointIndex(startPos); - - if (ClassifyChar(startPos) == CharacterType.LetterLike) - return startPos; - return NextCodePointIndex(startPos); - } - - /// Move to the end of the word. - /// If the cursor is over some space characters, these are skipped - /// Then, the cursor moves to the end of the following word. - /// This corresponds to Alt-RightArrow on a Mac - public void MoveWordRight() - { - cursorIndex = cursorIndex > selectIndex ? cursorIndex : selectIndex; - cursorIndex = selectIndex = FindNextSeperator(cursorIndex); - ClearCursorPos(); - } - - public void MoveToStartOfNextWord() - { - ClearCursorPos(); - if (cursorIndex != selectIndex) - { - MoveRight(); - return; - } - cursorIndex = selectIndex = FindStartOfNextWord(cursorIndex); - } - - public void MoveToEndOfPreviousWord() - { - ClearCursorPos(); - if (cursorIndex != selectIndex) - { - MoveLeft(); - return; - } - cursorIndex = selectIndex = FindEndOfPreviousWord(cursorIndex); - } - - public void SelectToStartOfNextWord() - { - ClearCursorPos(); - cursorIndex = FindStartOfNextWord(cursorIndex); - } - - public void SelectToEndOfPreviousWord() - { - ClearCursorPos(); - cursorIndex = FindEndOfPreviousWord(cursorIndex); - } - - enum CharacterType - { - LetterLike, - Symbol, Symbol2, - WhiteSpace - } - - CharacterType ClassifyChar(int index) - { - if (char.IsWhiteSpace(text, index)) - return CharacterType.WhiteSpace; - if (char.IsLetterOrDigit(text, index) || text[index] == '\'') - return CharacterType.LetterLike; - return CharacterType.Symbol; - } - - /// Move to start of next word. - /// This corresponds to Ctrl-RightArrow on Windows - /// If the cursor is over a whitespace, it's moved forwards ''till the first non-whitespace character - /// If the cursor is over an alphanumeric character, it''s moved forward 'till it encounters space or a punctuation mark. - /// If the stopping character is a space, this is skipped as well. - /// If the cursor is over an punctuation mark, it's moved forward ''till it a letter or a space of a punctuation mark. If the stopping character is a space, this is skipped as well - public int FindStartOfNextWord(int p) - { - int textLen = text.Length; - if (p == textLen) - return p; - - // Find out which char type we're at... - CharacterType t = ClassifyChar(p); - if (t != CharacterType.WhiteSpace) - { - p = NextCodePointIndex(p); - while (p < textLen && ClassifyChar(p) == t) - p = NextCodePointIndex(p); - } - else - { - if (text[p] == '\t' || text[p] == '\n') - return NextCodePointIndex(p); - } - - if (p == textLen) - return p; - - // Skip spaces - if (text[p] == ' ') // If we're at a space, skip over any number of spaces - { - while (p < textLen && ClassifyChar(p) == CharacterType.WhiteSpace) - p = NextCodePointIndex(p); - } - else if (text[p] == '\t' || text[p] == '\n') // If we're at a tab or a newline, just step one char ahead - { - return p; - } - return p; - } - - int FindEndOfPreviousWord(int p) - { - if (p == 0) - return p; - p = PreviousCodePointIndex(p); - - // Skip spaces - while (p > 0 && text[p] == ' ') - p = PreviousCodePointIndex(p); - - CharacterType t = ClassifyChar(p); - if (t != CharacterType.WhiteSpace) - { - while (p > 0 && ClassifyChar(PreviousCodePointIndex(p)) == t) - p = PreviousCodePointIndex(p); - } - return p; - } - - public void MoveWordLeft() - { - cursorIndex = cursorIndex < selectIndex ? cursorIndex : selectIndex; - cursorIndex = FindPrevSeperator(cursorIndex); - selectIndex = cursorIndex; - } - - public void SelectWordRight() - { - ClearCursorPos(); - int cachedPos = selectIndex; - if (cursorIndex < selectIndex) - { - selectIndex = cursorIndex; - MoveWordRight(); - selectIndex = cachedPos; - cursorIndex = cursorIndex < selectIndex ? cursorIndex : selectIndex; - return; - } - selectIndex = cursorIndex; - MoveWordRight(); - selectIndex = cachedPos; - } - - public void SelectWordLeft() - { - ClearCursorPos(); - int cachedPos = selectIndex; - if (cursorIndex > selectIndex) - { - selectIndex = cursorIndex; - MoveWordLeft(); - selectIndex = cachedPos; - cursorIndex = cursorIndex > selectIndex ? cursorIndex : selectIndex; - return; - } - selectIndex = cursorIndex; - MoveWordLeft(); - selectIndex = cachedPos; - } - - /// Expand the selection to the start of the line - /// Used on a mac for CMD-SHIFT-LEFT - public void ExpandSelectGraphicalLineStart() - { - ClearCursorPos(); - if (cursorIndex < selectIndex) - cursorIndex = GetGraphicalLineStart(cursorIndex); - else - { - int temp = cursorIndex; - cursorIndex = GetGraphicalLineStart(selectIndex); - selectIndex = temp; - } - } - - /// Expand the selection to the end of the line - /// Used on a mac for CMD-SHIFT-RIGHT - public void ExpandSelectGraphicalLineEnd() - { - ClearCursorPos(); - if (cursorIndex > selectIndex) - cursorIndex = GetGraphicalLineEnd(cursorIndex); - else - { - int temp = cursorIndex; - cursorIndex = GetGraphicalLineEnd(selectIndex); - selectIndex = temp; - } - } - - /// Move the selection point to the start of the line - /// Used on a Windows for SHIFT-Home - public void SelectGraphicalLineStart() - { - ClearCursorPos(); - cursorIndex = GetGraphicalLineStart(cursorIndex); - } - - /// Expand the selection to the end of the line - /// Used on a mac for SHIFT-End - public void SelectGraphicalLineEnd() - { - ClearCursorPos(); - cursorIndex = GetGraphicalLineEnd(cursorIndex); - } - - public void SelectParagraphForward() - { - ClearCursorPos(); - bool wasBehind = cursorIndex < selectIndex; - if (cursorIndex < text.Length) - { - cursorIndex = IndexOfEndOfLine(cursorIndex + 1); - if (wasBehind && cursorIndex > selectIndex) - cursorIndex = selectIndex; - } - } - - public void SelectParagraphBackward() - { - ClearCursorPos(); - bool wasInFront = cursorIndex > selectIndex; - if (cursorIndex > 1) - { - cursorIndex = text.LastIndexOf('\n', cursorIndex - 2) + 1; - if (wasInFront && cursorIndex < selectIndex) - cursorIndex = selectIndex; - } - else - selectIndex = cursorIndex = 0; - } - - /// Select the word under the cursor - public void SelectCurrentWord() - { - var index = cursorIndex; - if (cursorIndex < selectIndex) - { - cursorIndex = FindEndOfClassification(index, Direction.Backward); - selectIndex = FindEndOfClassification(index, Direction.Forward); - } - else - { - cursorIndex = FindEndOfClassification(index, Direction.Forward); - selectIndex = FindEndOfClassification(index, Direction.Backward); - } - - ClearCursorPos(); - m_bJustSelected = true; - } - - enum Direction - { - Forward, - Backward, - } - - int FindEndOfClassification(int p, Direction dir) - { - if (text.Length == 0) - return 0; - - if (p == text.Length) - p = PreviousCodePointIndex(p); - - var t = ClassifyChar(p); - do - { - switch (dir) - { - case Direction.Backward: - p = PreviousCodePointIndex(p); - if (p == 0) - return ClassifyChar(0) == t ? 0 : NextCodePointIndex(0); - break; - - case Direction.Forward: - p = NextCodePointIndex(p); - if (p == text.Length) - return text.Length; - break; - } - } - while (ClassifyChar(p) == t); - if (dir == Direction.Forward) - return p; - return NextCodePointIndex(p); - } - - // Select the entire paragraph the cursor is on (separated by \n) - public void SelectCurrentParagraph() - { - ClearCursorPos(); - int textLen = text.Length; - - if (cursorIndex < textLen) - { - cursorIndex = IndexOfEndOfLine(cursorIndex) + 1; - } - if (selectIndex != 0) - selectIndex = text.LastIndexOf('\n', selectIndex - 1) + 1; - } - - public void UpdateScrollOffsetIfNeeded(Event evt) - { - if (evt.type != EventType.Repaint && evt.type != EventType.Layout) - { - UpdateScrollOffset(); - } - } - - [VisibleToOtherModules] - internal void UpdateScrollOffset() - { - int cursorPos = cursorIndex; - graphicalCursorPos = style.GetCursorPixelPosition(new Rect(0, 0, position.width, position.height), m_Content, cursorPos); - - Rect r = style.padding.Remove(position); - - Vector2 contentSize = new Vector2(style.CalcSize(m_Content).x, style.CalcHeight(m_Content, position.width)); - - // If there is plenty of room, simply show entire string - if (contentSize.x < position.width) - { - scrollOffset.x = 0; - } - else if (m_RevealCursor) - { - //go right - if (graphicalCursorPos.x + 1 > scrollOffset.x + r.width) - // do we want html or apple behavior? this is html behavior - scrollOffset.x = graphicalCursorPos.x - r.width; - //go left - if (graphicalCursorPos.x < scrollOffset.x + style.padding.left) - scrollOffset.x = graphicalCursorPos.x - style.padding.left; - } - // ... and height/y as well - // If there is plenty of room, simply show entire string - if (contentSize.y < r.height) - { - scrollOffset.y = 0; - } - else if (m_RevealCursor) - { - //go down - if (graphicalCursorPos.y + style.lineHeight > scrollOffset.y + r.height + style.padding.top) - scrollOffset.y = graphicalCursorPos.y - r.height - style.padding.top + style.lineHeight; - //go up - if (graphicalCursorPos.y < scrollOffset.y + style.padding.top) - scrollOffset.y = graphicalCursorPos.y - style.padding.top; - } - - // This case takes many words to explain: - // 1. Text field has more text than it can fit vertically, and the cursor is at the very bottom (text field is scrolled down) - // 2. user e.g. deletes some lines of text at the bottom (backspace or select+delete) - // 3. now suddenly we have space at the bottom of text field, that is now not filled with any content - // 4. scroll text field up to fill in that space (this is what other text editors do) - if (scrollOffset.y > 0 && contentSize.y - scrollOffset.y < r.height + style.padding.top + style.padding.bottom) - scrollOffset.y = contentSize.y - r.height - style.padding.top - style.padding.bottom; - - scrollOffset.y = scrollOffset.y < 0 ? 0 : scrollOffset.y; - - m_RevealCursor = false; - } - - // TODO: get the height from the font - - public void DrawCursor(string newText) - { - string realText = text; - int cursorPos = cursorIndex; - if (Input.compositionString.Length > 0) - { - m_Content.text = newText.Substring(0, cursorIndex) + Input.compositionString + newText.Substring(selectIndex); - cursorPos += Input.compositionString.Length; - } - else - m_Content.text = newText; - - graphicalCursorPos = style.GetCursorPixelPosition(new Rect(0, 0, position.width, position.height), m_Content, cursorPos); - - //Debug.Log("Cursor pos: " + graphicalCursorPos); - - Vector2 originalContentOffset = style.contentOffset; - style.contentOffset -= scrollOffset; - style.Internal_clipOffset = scrollOffset; - - // Debug.Log ("ScrollOffset : " + scrollOffset); - - Input.compositionCursorPos = graphicalCursorPos + new Vector2(position.x, position.y + style.lineHeight) - scrollOffset; - - if (Input.compositionString.Length > 0) - style.DrawWithTextSelection(position, m_Content, controlID, cursorIndex, cursorIndex + Input.compositionString.Length, true); - else - style.DrawWithTextSelection(position, m_Content, controlID, cursorIndex, selectIndex); - - if (m_iAltCursorPos != -1) - style.DrawCursor(position, m_Content, controlID, m_iAltCursorPos); - - // reset - style.contentOffset = originalContentOffset; - style.Internal_clipOffset = Vector2.zero; - - m_Content.text = realText; - } - - bool PerformOperation(TextEditOp operation) - { - m_RevealCursor = true; - - switch (operation) - { - // NOTE the TODOs below: - case TextEditOp.MoveLeft: MoveLeft(); break; - case TextEditOp.MoveRight: MoveRight(); break; - case TextEditOp.MoveUp: MoveUp(); break; - case TextEditOp.MoveDown: MoveDown(); break; - case TextEditOp.MoveLineStart: MoveLineStart(); break; - case TextEditOp.MoveLineEnd: MoveLineEnd(); break; - case TextEditOp.MoveWordRight: MoveWordRight(); break; - case TextEditOp.MoveToStartOfNextWord: MoveToStartOfNextWord(); break; - case TextEditOp.MoveToEndOfPreviousWord: MoveToEndOfPreviousWord(); break; - case TextEditOp.MoveWordLeft: MoveWordLeft(); break; - case TextEditOp.MoveTextStart: MoveTextStart(); break; - case TextEditOp.MoveTextEnd: MoveTextEnd(); break; - case TextEditOp.MoveParagraphForward: MoveParagraphForward(); break; - case TextEditOp.MoveParagraphBackward: MoveParagraphBackward(); break; - // case TextEditOp.MovePageUp: return MovePageUp (); break; - // case TextEditOp.MovePageDown: return MovePageDown (); break; - case TextEditOp.MoveGraphicalLineStart: MoveGraphicalLineStart(); break; - case TextEditOp.MoveGraphicalLineEnd: MoveGraphicalLineEnd(); break; - case TextEditOp.SelectLeft: SelectLeft(); break; - case TextEditOp.SelectRight: SelectRight(); break; - case TextEditOp.SelectUp: SelectUp(); break; - case TextEditOp.SelectDown: SelectDown(); break; - case TextEditOp.SelectWordRight: SelectWordRight(); break; - case TextEditOp.SelectWordLeft: SelectWordLeft(); break; - case TextEditOp.SelectToEndOfPreviousWord: SelectToEndOfPreviousWord(); break; - case TextEditOp.SelectToStartOfNextWord: SelectToStartOfNextWord(); break; - - case TextEditOp.SelectTextStart: SelectTextStart(); break; - case TextEditOp.SelectTextEnd: SelectTextEnd(); break; - case TextEditOp.ExpandSelectGraphicalLineStart: ExpandSelectGraphicalLineStart(); break; - case TextEditOp.ExpandSelectGraphicalLineEnd: ExpandSelectGraphicalLineEnd(); break; - case TextEditOp.SelectParagraphForward: SelectParagraphForward(); break; - case TextEditOp.SelectParagraphBackward: SelectParagraphBackward(); break; - case TextEditOp.SelectGraphicalLineStart: SelectGraphicalLineStart(); break; - case TextEditOp.SelectGraphicalLineEnd: SelectGraphicalLineEnd(); break; - // case TextEditOp.SelectPageUp: return SelectPageUp (); break; - // case TextEditOp.SelectPageDown: return SelectPageDown (); break; - case TextEditOp.Delete: return Delete(); - case TextEditOp.Backspace: return Backspace(); - case TextEditOp.Cut: return Cut(); - case TextEditOp.Copy: Copy(); break; - case TextEditOp.Paste: return Paste(); - case TextEditOp.SelectAll: SelectAll(); break; - case TextEditOp.SelectNone: SelectNone(); break; - // case TextEditOp.ScrollStart: return ScrollStart (); break; - // case TextEditOp.ScrollEnd: return ScrollEnd (); break; - // case TextEditOp.ScrollPageUp: return ScrollPageUp (); break; - // case TextEditOp.ScrollPageDown: return ScrollPageDown (); break; - case TextEditOp.DeleteWordBack: return DeleteWordBack(); // break; // The uncoditional return makes the "break;" issue a warning about unreachable code - case TextEditOp.DeleteLineBack: return DeleteLineBack(); - case TextEditOp.DeleteWordForward: return DeleteWordForward(); // break; // The uncoditional return makes the "break;" issue a warning about unreachable code - default: - Debug.Log("Unimplemented: " + operation); - break; - } - - return false; - } - - enum TextEditOp - { - MoveLeft, MoveRight, MoveUp, MoveDown, MoveLineStart, MoveLineEnd, MoveTextStart, MoveTextEnd, MovePageUp, MovePageDown, - MoveGraphicalLineStart, MoveGraphicalLineEnd, MoveWordLeft, MoveWordRight, - MoveParagraphForward, MoveParagraphBackward, MoveToStartOfNextWord, MoveToEndOfPreviousWord, - SelectLeft, SelectRight, SelectUp, SelectDown, SelectTextStart, SelectTextEnd, SelectPageUp, SelectPageDown, - ExpandSelectGraphicalLineStart, ExpandSelectGraphicalLineEnd, SelectGraphicalLineStart, SelectGraphicalLineEnd, - SelectWordLeft, SelectWordRight, SelectToEndOfPreviousWord, SelectToStartOfNextWord, - SelectParagraphBackward, SelectParagraphForward, - Delete, Backspace, DeleteWordBack, DeleteWordForward, DeleteLineBack, - Cut, Copy, Paste, SelectAll, SelectNone, - ScrollStart, ScrollEnd, ScrollPageUp, ScrollPageDown - }; - - string oldText; - int oldPos, oldSelectPos; - - public void SaveBackup() - { - oldText = text; - oldPos = cursorIndex; - oldSelectPos = selectIndex; - } - - public void Undo() - { - m_Content.text = oldText; - cursorIndex = oldPos; - selectIndex = oldSelectPos; - } - - public bool Cut() - { - //Debug.Log ("Cut"); - if (isPasswordField) - return false; - Copy(); - return DeleteSelection(); - } - - public void Copy() - { - //Debug.Log ("Copy"); - if (selectIndex == cursorIndex) - return; - - if (isPasswordField) - return; - - string copyStr; - if (cursorIndex < selectIndex) - copyStr = text.Substring(cursorIndex, selectIndex - cursorIndex); - else - copyStr = text.Substring(selectIndex, cursorIndex - selectIndex); - - GUIUtility.systemCopyBuffer = copyStr; - } - - static string ReplaceNewlinesWithSpaces(string value) - { - // First get rid of Windows style new lines and then *nix so we don't leave '\r' around. - value = value.Replace("\r\n", " "); - value = value.Replace('\n', ' '); - // This probably won't happen, but just in case... - value = value.Replace('\r', ' '); - return value; - } - - public bool Paste() - { - //Debug.Log ("Paste"); - string pasteval = GUIUtility.systemCopyBuffer; - if (pasteval != "") - { - if (!multiline) - pasteval = ReplaceNewlinesWithSpaces(pasteval); - ReplaceSelection(pasteval); - return true; - } - return false; - } - - static void MapKey(string key, TextEditOp action) - { - s_Keyactions[Event.KeyboardEvent(key)] = action; - } - - static Dictionary s_Keyactions; - /// Set up a platform independant keyboard->Edit action map. This varies depending on whether we are on mac or windows. - void InitKeyActions() - { - if (s_Keyactions != null) - return; - s_Keyactions = new Dictionary(); - - // key mappings shared by the platforms - MapKey("left", TextEditOp.MoveLeft); - MapKey("right", TextEditOp.MoveRight); - MapKey("up", TextEditOp.MoveUp); - MapKey("down", TextEditOp.MoveDown); - - MapKey("#left", TextEditOp.SelectLeft); - MapKey("#right", TextEditOp.SelectRight); - MapKey("#up", TextEditOp.SelectUp); - MapKey("#down", TextEditOp.SelectDown); - - MapKey("delete", TextEditOp.Delete); - MapKey("backspace", TextEditOp.Backspace); - MapKey("#backspace", TextEditOp.Backspace); - - // OSX is the special case for input shortcuts - if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX) - { - // Keyboard mappings for mac - // TODO MapKey ("home", TextEditOp.ScrollStart); - // TODO MapKey ("end", TextEditOp.ScrollEnd); - // TODO MapKey ("page up", TextEditOp.ScrollPageUp); - // TODO MapKey ("page down", TextEditOp.ScrollPageDown); - - MapKey("^left", TextEditOp.MoveGraphicalLineStart); - MapKey("^right", TextEditOp.MoveGraphicalLineEnd); - // TODO MapKey ("^up", TextEditOp.ScrollPageUp); - // TODO MapKey ("^down", TextEditOp.ScrollPageDown); - - MapKey("&left", TextEditOp.MoveWordLeft); - MapKey("&right", TextEditOp.MoveWordRight); - MapKey("&up", TextEditOp.MoveParagraphBackward); - MapKey("&down", TextEditOp.MoveParagraphForward); - - MapKey("%left", TextEditOp.MoveGraphicalLineStart); - MapKey("%right", TextEditOp.MoveGraphicalLineEnd); - MapKey("%up", TextEditOp.MoveTextStart); - MapKey("%down", TextEditOp.MoveTextEnd); - - MapKey("#home", TextEditOp.SelectTextStart); - MapKey("#end", TextEditOp.SelectTextEnd); - // TODO MapKey ("#page up", TextEditOp.SelectPageUp); - // TODO MapKey ("#page down", TextEditOp.SelectPageDown); - - MapKey("#^left", TextEditOp.ExpandSelectGraphicalLineStart); - MapKey("#^right", TextEditOp.ExpandSelectGraphicalLineEnd); - MapKey("#^up", TextEditOp.SelectParagraphBackward); - MapKey("#^down", TextEditOp.SelectParagraphForward); - - MapKey("#&left", TextEditOp.SelectWordLeft); - MapKey("#&right", TextEditOp.SelectWordRight); - MapKey("#&up", TextEditOp.SelectParagraphBackward); - MapKey("#&down", TextEditOp.SelectParagraphForward); - - MapKey("#%left", TextEditOp.ExpandSelectGraphicalLineStart); - MapKey("#%right", TextEditOp.ExpandSelectGraphicalLineEnd); - MapKey("#%up", TextEditOp.SelectTextStart); - MapKey("#%down", TextEditOp.SelectTextEnd); - - MapKey("%a", TextEditOp.SelectAll); - MapKey("%x", TextEditOp.Cut); - MapKey("%c", TextEditOp.Copy); - MapKey("%v", TextEditOp.Paste); - - // emacs-like keybindings - MapKey("^d", TextEditOp.Delete); - MapKey("^h", TextEditOp.Backspace); - MapKey("^b", TextEditOp.MoveLeft); - MapKey("^f", TextEditOp.MoveRight); - MapKey("^a", TextEditOp.MoveLineStart); - MapKey("^e", TextEditOp.MoveLineEnd); - - MapKey("&delete", TextEditOp.DeleteWordForward); - MapKey("&backspace", TextEditOp.DeleteWordBack); - MapKey("%backspace", TextEditOp.DeleteLineBack); - } - else - { - // Windows/Linux keymappings - MapKey("home", TextEditOp.MoveGraphicalLineStart); - MapKey("end", TextEditOp.MoveGraphicalLineEnd); - // TODO MapKey ("page up", TextEditOp.MovePageUp); - // TODO MapKey ("page down", TextEditOp.MovePageDown); - - MapKey("%left", TextEditOp.MoveWordLeft); - MapKey("%right", TextEditOp.MoveWordRight); - MapKey("%up", TextEditOp.MoveParagraphBackward); - MapKey("%down", TextEditOp.MoveParagraphForward); - - MapKey("^left", TextEditOp.MoveToEndOfPreviousWord); - MapKey("^right", TextEditOp.MoveToStartOfNextWord); - MapKey("^up", TextEditOp.MoveParagraphBackward); - MapKey("^down", TextEditOp.MoveParagraphForward); - - MapKey("#^left", TextEditOp.SelectToEndOfPreviousWord); - MapKey("#^right", TextEditOp.SelectToStartOfNextWord); - MapKey("#^up", TextEditOp.SelectParagraphBackward); - MapKey("#^down", TextEditOp.SelectParagraphForward); - - MapKey("#home", TextEditOp.SelectGraphicalLineStart); - MapKey("#end", TextEditOp.SelectGraphicalLineEnd); - // TODO MapKey ("#page up", TextEditOp.SelectPageUp); - // TODO MapKey ("#page down", TextEditOp.SelectPageDown); - - MapKey("^delete", TextEditOp.DeleteWordForward); - MapKey("^backspace", TextEditOp.DeleteWordBack); - MapKey("%backspace", TextEditOp.DeleteLineBack); - - MapKey("^a", TextEditOp.SelectAll); - MapKey("^x", TextEditOp.Cut); - MapKey("^c", TextEditOp.Copy); - MapKey("^v", TextEditOp.Paste); - MapKey("#delete", TextEditOp.Cut); - MapKey("^insert", TextEditOp.Copy); - MapKey("#insert", TextEditOp.Paste); - } - } - - public void DetectFocusChange() - { - OnDetectFocusChange(); - } - - internal virtual void OnDetectFocusChange() - { - if (m_HasFocus == true && controlID != GUIUtility.keyboardControl) - OnLostFocus(); - if (m_HasFocus == false && controlID == GUIUtility.keyboardControl) - OnFocus(); - } - - internal virtual void OnCursorIndexChange() - { - } - - internal virtual void OnSelectIndexChange() - { - } - - private void ClampTextIndex(ref int index) - { - index = Mathf.Clamp(index, 0, text.Length); - } - - void EnsureValidCodePointIndex(ref int index) - { - ClampTextIndex(ref index); - if (!IsValidCodePointIndex(index)) - index = NextCodePointIndex(index); - } - - bool IsValidCodePointIndex(int index) - { - if (index < 0 || index > text.Length) - return false; - if (index == 0 || index == text.Length) - return true; - return !char.IsLowSurrogate(text[index]); - } - - int PreviousCodePointIndex(int index) - { - if (index > 0) - index--; - while (index > 0 && char.IsLowSurrogate(text[index])) - index--; - return index; - } - - int NextCodePointIndex(int index) - { - if (index < text.Length) - index++; - while (index < text.Length && char.IsLowSurrogate(text[index])) - index++; - return index; - } - } -} // namespace diff --git a/Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.cs b/Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.cs index 86ce9a075e..d5ea21ea9c 100644 --- a/Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.cs +++ b/Modules/ImageConversion/ScriptBindings/ImageConversion.bindings.cs @@ -32,7 +32,7 @@ public static byte[] EncodeToEXR(this Texture2D tex) } [NativeMethod(Name = "ImageConversionBindings::LoadImage", IsFreeFunction = true)] - extern public static bool LoadImage(this Texture2D tex, byte[] data, bool markNonReadable); + extern public static bool LoadImage([NotNull] this Texture2D tex, byte[] data, bool markNonReadable); public static bool LoadImage(this Texture2D tex, byte[] data) { return LoadImage(tex, data, false); diff --git a/Modules/PackageManager/Editor/Managed/IShouldIncludeInBuildCallback.cs b/Modules/PackageManager/Editor/Managed/IShouldIncludeInBuildCallback.cs deleted file mode 100644 index 7859da6665..0000000000 --- a/Modules/PackageManager/Editor/Managed/IShouldIncludeInBuildCallback.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.PackageManager -{ - public interface IShouldIncludeInBuildCallback - { - string PackageName { get; } - bool ShouldIncludeInBuild(string path); - } -} diff --git a/Modules/PresetsEditor/PresetManagerEditor.cs b/Modules/PresetsEditor/PresetManagerEditor.cs index 7a91f1785f..31d983ae32 100644 --- a/Modules/PresetsEditor/PresetManagerEditor.cs +++ b/Modules/PresetsEditor/PresetManagerEditor.cs @@ -147,6 +147,7 @@ void DrawElementCallback(Rect rect, int index, bool isActive, bool isFocused) case EventType.MouseDown: if (buttonRect.Contains(Event.current.mousePosition)) { + RefreshAddList(); var menu = new GenericMenu(); if (m_DiscoveredPresets.ContainsKey(keyType)) { diff --git a/Modules/ProfilerEditor/MemoryProfiler/MemorySnapshot.cs b/Modules/ProfilerEditor/MemoryProfiler/MemorySnapshot.cs index c61d4a7ef8..0ad5078c77 100644 --- a/Modules/ProfilerEditor/MemoryProfiler/MemorySnapshot.cs +++ b/Modules/ProfilerEditor/MemoryProfiler/MemorySnapshot.cs @@ -10,12 +10,10 @@ namespace UnityEditor.Profiling.Memory.Experimental { - // Note: this snapshot is completely serializable by unity's serializer. // !!!!! NOTE: Keep in sync with Runtime\Profiler\MemorySnapshots.cpp - public class PackedMemorySnapshot : ISerializationCallbackReceiver + public class PackedMemorySnapshot : IDisposable { - private static readonly UInt64 kMinSupportedVersion = 7; - + static readonly UInt64 kMinSupportedVersion = 7; public static PackedMemorySnapshot Load(string path) { MemorySnapshotFileReader reader = new MemorySnapshotFileReader(path); @@ -42,7 +40,6 @@ public static void Save(PackedMemorySnapshot snapshot, string writePath) FileUtil.CopyFileIfExists(path, writePath, true); } - [SerializeField] MemorySnapshotFileReader m_Reader = null; public ConnectionEntries connections { get; internal set; } @@ -84,15 +81,6 @@ internal void BuildEntries() typeDescriptions = new TypeDescriptionEntries(m_Reader); } - public void OnBeforeSerialize() - { - } - - public void OnAfterDeserialize() - { - BuildEntries(); - } - internal MemorySnapshotFileReader GetReader() { return m_Reader; @@ -106,11 +94,11 @@ public UInt32 version } } - public UnityEngine.Profiling.Memory.Experimental.MetaData metadata + public MetaData metadata { get { - byte[] array = m_Reader.GetDataSingle(EntryType.Metadata_UserMetadata, ConversionFunctions.ToByteArray); + byte[] array = m_Reader.GetDataSingle(EntryType.Metadata_UserMetadata, ConversionFunctions.ToByteArray); // decoded as // content_data_length // content_data @@ -121,15 +109,21 @@ public UnityEngine.Profiling.Memory.Experimental.MetaData metadata // [opt: screenshot_width ] // [opt: screenshot_height ] // [opt: screenshot_format ] + var data = new UnityEngine.Profiling.Memory.Experimental.MetaData(); - var metaData = new UnityEngine.Profiling.Memory.Experimental.MetaData(); + if (array.Length == 0) + { + data.content = ""; + data.platform = ""; + return data; + } int offset = 0; int dataLength = 0; offset = ReadIntFromByteArray(array, offset, out dataLength); - offset = ReadStringFromByteArray(array, offset, dataLength, out metaData.content); + offset = ReadStringFromByteArray(array, offset, dataLength, out data.content); offset = ReadIntFromByteArray(array, offset, out dataLength); - offset = ReadStringFromByteArray(array, offset, dataLength, out metaData.platform); + offset = ReadStringFromByteArray(array, offset, dataLength, out data.platform); offset = ReadIntFromByteArray(array, offset, out dataLength); if (dataLength > 0) @@ -146,14 +140,14 @@ public UnityEngine.Profiling.Memory.Experimental.MetaData metadata offset = ReadIntFromByteArray(array, offset, out height); offset = ReadIntFromByteArray(array, offset, out format); - metaData.screenshot = new Texture2D(width, height, (TextureFormat)format, false); - metaData.screenshot.LoadRawTextureData(screenshot); - metaData.screenshot.Apply(); + data.screenshot = new Texture2D(width, height, (TextureFormat)format, false); + data.screenshot.LoadRawTextureData(screenshot); + data.screenshot.Apply(); } UnityEngine.Assertions.Assert.AreEqual(array.Length, offset); - return metaData; + return data; } } @@ -222,7 +216,7 @@ public DateTime recordDate } } - public UnityEngine.Profiling.Memory.Experimental.CaptureFlags captureFlags + public CaptureFlags captureFlags { get { @@ -237,6 +231,31 @@ public VirtualMachineInformation virtualMachineInformation return m_Reader.GetDataSingle(EntryType.Metadata_VirtualMachineInformation, ConversionFunctions.ToVirtualMachineInformation); } } + + ~PackedMemorySnapshot() + { + Dispose(false); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (m_Reader == null) + { + return; + } + + m_Reader.Dispose(); + m_Reader = null; + } + } } [Flags] diff --git a/Modules/ProfilerEditor/ProfilerWindow/MemorySnapshot.cs b/Modules/ProfilerEditor/ProfilerWindow/MemorySnapshot.cs index 5ff7053662..5a6c077a9e 100644 --- a/Modules/ProfilerEditor/ProfilerWindow/MemorySnapshot.cs +++ b/Modules/ProfilerEditor/ProfilerWindow/MemorySnapshot.cs @@ -3,6 +3,7 @@ // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; +using System.IO; using UnityEngine; namespace UnityEditor.MemoryProfiler @@ -15,23 +16,33 @@ private static void SnapshotFinished(string path, bool result) { if (result) { - UnityEditor.Profiling.Memory.Experimental.PackedMemorySnapshot snapshot = UnityEditor.Profiling.Memory.Experimental.PackedMemorySnapshot.Load(path); + Profiling.Memory.Experimental.PackedMemorySnapshot snapshot = Profiling.Memory.Experimental.PackedMemorySnapshot.Load(path); - OnSnapshotReceived(new PackedMemorySnapshot(snapshot)); + var oldSnapshot = new PackedMemorySnapshot(snapshot); + snapshot.Dispose(); + File.Delete(path); + + OnSnapshotReceived(oldSnapshot); } else { + if (File.Exists(path)) + File.Delete(path); + OnSnapshotReceived(null); } } - public static void RequestNewSnapshot() + internal static string GetTemporarySnapshotPath() { string[] s = Application.dataPath.Split('/'); string projectName = s[s.Length - 2]; - string path = Application.temporaryCachePath + "/" + projectName + ".snap"; + return Path.Combine(Application.temporaryCachePath, projectName + ".snap"); + } - UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.TakeSnapshot(path, SnapshotFinished, UnityEngine.Profiling.Memory.Experimental.CaptureFlags.NativeObjects | UnityEngine.Profiling.Memory.Experimental.CaptureFlags.ManagedObjects); + public static void RequestNewSnapshot() + { + UnityEngine.Profiling.Memory.Experimental.MemoryProfiler.TakeSnapshot(GetTemporarySnapshotPath(), SnapshotFinished, UnityEngine.Profiling.Memory.Experimental.CaptureFlags.NativeObjects | UnityEngine.Profiling.Memory.Experimental.CaptureFlags.ManagedObjects); } } diff --git a/Modules/ProfilerEditor/ProfilerWindow/NetworkDetailStats.cs b/Modules/ProfilerEditor/ProfilerWindow/NetworkDetailStats.cs index 16ccf7806d..e8ba9d056b 100644 --- a/Modules/ProfilerEditor/ProfilerWindow/NetworkDetailStats.cs +++ b/Modules/ProfilerEditor/ProfilerWindow/NetworkDetailStats.cs @@ -119,8 +119,10 @@ public void NewProfilerTick(int tickId) { entry.NewProfilerTick(tickId); } +#pragma warning disable 618 NetworkTransport.SetPacketStat(0, MsgId, (int)totalIn, 1); NetworkTransport.SetPacketStat(1, MsgId, (int)totalOut, 1); +#pragma warning restore 618 totalIn = 0; totalOut = 0; } @@ -253,8 +255,10 @@ static public void ResetAll() { foreach (var detail in m_NetworkOperations.Values) { +#pragma warning disable 618 NetworkTransport.SetPacketStat(0, detail.MsgId, 0, 1); NetworkTransport.SetPacketStat(1, detail.MsgId, 0, 1); +#pragma warning restore 618 } m_NetworkOperations.Clear(); } diff --git a/Modules/ProfilerEditor/ProfilerWindow/ProfilerFrameHierarchyView.cs b/Modules/ProfilerEditor/ProfilerWindow/ProfilerFrameHierarchyView.cs index 4850a99fb8..f7f1f41a83 100644 --- a/Modules/ProfilerEditor/ProfilerWindow/ProfilerFrameHierarchyView.cs +++ b/Modules/ProfilerEditor/ProfilerWindow/ProfilerFrameHierarchyView.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using UnityEditor; using UnityEditor.IMGUI.Controls; +using Unity.Profiling; namespace UnityEditorInternal.Profiling { @@ -111,6 +112,8 @@ public bool sortedProfilerColumnAscending public delegate void SearchChangedCallback(string newSearch); public event SearchChangedCallback searchChanged; + static readonly ProfilerMarker m_DoGUIMarker = new ProfilerMarker(nameof(ProfilerFrameDataHierarchyView) + ".DoGUI"); + public ProfilerFrameDataHierarchyView() { m_Initialized = false; @@ -275,70 +278,73 @@ static string GetProfilerColumnName(ProfilerColumn column) public void DoGUI(FrameDataView frameDataView) { - InitIfNeeded(); + using (m_DoGUIMarker.Auto()) + { + InitIfNeeded(); - var collectingSamples = ProfilerDriver.enabled && (ProfilerDriver.profileEditor || EditorApplication.isPlaying); - var isSearchAllowed = string.IsNullOrEmpty(treeView.searchString) || !(collectingSamples && ProfilerDriver.deepProfiling); + var collectingSamples = ProfilerDriver.enabled && (ProfilerDriver.profileEditor || EditorApplication.isPlaying); + var isSearchAllowed = string.IsNullOrEmpty(treeView.searchString) || !(collectingSamples && ProfilerDriver.deepProfiling); - var isDataAvailable = frameDataView != null && frameDataView.IsValid(); - if (isDataAvailable && isSearchAllowed) - if (isDataAvailable) - m_TreeView.SetFrameDataView(frameDataView); + var isDataAvailable = frameDataView != null && frameDataView.IsValid(); + if (isDataAvailable && isSearchAllowed) + if (isDataAvailable) + m_TreeView.SetFrameDataView(frameDataView); - var showDetailedView = isDataAvailable && m_DetailedViewType != DetailedViewType.None; - if (showDetailedView) - SplitterGUILayout.BeginHorizontalSplit(m_DetailedViewSpliterState); + var showDetailedView = isDataAvailable && m_DetailedViewType != DetailedViewType.None; + if (showDetailedView) + SplitterGUILayout.BeginHorizontalSplit(m_DetailedViewSpliterState); - // Hierarchy view area - GUILayout.BeginVertical(); + // Hierarchy view area + GUILayout.BeginVertical(); - DrawToolbar(frameDataView, showDetailedView); + DrawToolbar(frameDataView, showDetailedView); - if (!isDataAvailable) - { - GUILayout.Label(BaseStyles.noData, BaseStyles.label); - } - else if (!isSearchAllowed) - { - GUILayout.Label(BaseStyles.disabledSearchText, BaseStyles.label); - } - else - { - var rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandHeight(true), GUILayout.ExpandHeight(true)); - m_TreeView.OnGUI(rect); - } + if (!isDataAvailable) + { + GUILayout.Label(BaseStyles.noData, BaseStyles.label); + } + else if (!isSearchAllowed) + { + GUILayout.Label(BaseStyles.disabledSearchText, BaseStyles.label); + } + else + { + var rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandHeight(true), GUILayout.ExpandHeight(true)); + m_TreeView.OnGUI(rect); + } - GUILayout.EndVertical(); + GUILayout.EndVertical(); - if (showDetailedView) - { - GUILayout.BeginVertical(); + if (showDetailedView) + { + GUILayout.BeginVertical(); - // Detailed view area - EditorGUILayout.BeginHorizontal(BaseStyles.toolbar); + // Detailed view area + EditorGUILayout.BeginHorizontal(BaseStyles.toolbar); - DrawDetailedViewPopup(); - GUILayout.FlexibleSpace(); + DrawDetailedViewPopup(); + GUILayout.FlexibleSpace(); - DrawOptionsMenuPopup(); - EditorGUILayout.EndHorizontal(); + DrawOptionsMenuPopup(); + EditorGUILayout.EndHorizontal(); - switch (m_DetailedViewType) - { - case DetailedViewType.Objects: - detailedObjectsView.DoGUI(BaseStyles.header, frameDataView, m_TreeView.GetSelection()); - break; - case DetailedViewType.CallersAndCallees: - detailedCallsView.DoGUI(BaseStyles.header, frameDataView, m_TreeView.GetSelection()); - break; - } + switch (m_DetailedViewType) + { + case DetailedViewType.Objects: + detailedObjectsView.DoGUI(BaseStyles.header, frameDataView, m_TreeView.GetSelection()); + break; + case DetailedViewType.CallersAndCallees: + detailedCallsView.DoGUI(BaseStyles.header, frameDataView, m_TreeView.GetSelection()); + break; + } - GUILayout.EndVertical(); + GUILayout.EndVertical(); - SplitterGUILayout.EndHorizontalSplit(); - } + SplitterGUILayout.EndHorizontalSplit(); + } - HandleKeyboardEvents(); + HandleKeyboardEvents(); + } } void DrawSearchBar() diff --git a/Modules/ProfilerEditor/ProfilerWindow/ProfilerTimelineGUI.cs b/Modules/ProfilerEditor/ProfilerWindow/ProfilerTimelineGUI.cs index 9d60438ccd..ee29b6a242 100644 --- a/Modules/ProfilerEditor/ProfilerWindow/ProfilerTimelineGUI.cs +++ b/Modules/ProfilerEditor/ProfilerWindow/ProfilerTimelineGUI.cs @@ -9,6 +9,7 @@ using UnityEditorInternal.Profiling; using Object = UnityEngine.Object; using UnityEditor.AnimatedValues; +using Unity.Profiling; namespace UnityEditorInternal { @@ -36,12 +37,13 @@ internal class ThreadInfo public int threadIndex; public string name; public bool alive; - public int maxDepth = 1; - public ThreadInfo(string name, int threadIndex, int linesToDisplay) + public int maxDepth; + public ThreadInfo(string name, int threadIndex, int maxDepth, int linesToDisplay) { this.name = name; this.threadIndex = threadIndex; this.linesToDisplay = linesToDisplay; + this.maxDepth = Mathf.Max(1, maxDepth); } } @@ -227,6 +229,8 @@ struct RangeSelectionInfo RangeSelectionInfo m_RangeSelection = new RangeSelectionInfo(); + static readonly ProfilerMarker m_DoGUIMarker = new ProfilerMarker(nameof(ProfilerTimelineGUI) + ".DoGUI"); + public ProfilerTimelineGUI(IProfilerWindowController window) { m_Window = window; @@ -265,43 +269,21 @@ private void UpdateGroupAndThreadInfo(ref ProfilerFrameDataIterator iter, int fr ThreadInfo thread = threads.Find(t => t.threadIndex == i); if (thread == null) { - thread = new ThreadInfo(iter.GetThreadName(), i, group.defaultLineCountPerThread); + // ProfilerFrameDataIterator.maxDepth includes the thread sample which is not getting displayed, so we store it at -1 for all intents and purposes + thread = new ThreadInfo(iter.GetThreadName(), i, iter.maxDepth - 1, group.defaultLineCountPerThread); // the main thread gets double the size if (i == 0) thread.linesToDisplay *= 2; group.threads.Add(thread); } - thread.alive = true; - } - - if (m_LastSelectedFrameID != frameIndex) - { - foreach (var group in m_Groups) + else if (m_LastSelectedFrameID != frameIndex) { - foreach (var thread in group.threads) - { - thread.maxDepth = GetThreadMaxDepth(thread, frameIndex); - } - } - m_LastSelectedFrameID = frameIndex; - } - } - - int GetThreadMaxDepth(ThreadInfo thread, int frame) - { - int maxDepth = 1; - using (var iter = new ProfilerFrameDataIterator()) - { - iter.SetRoot(frame, thread.threadIndex); - - while (iter.Next(true)) - { - if (iter.depth > maxDepth) - maxDepth = iter.depth; + thread.maxDepth = iter.maxDepth; } + thread.alive = true; } - return maxDepth; + m_LastSelectedFrameID = frameIndex; } private float CalculateHeightForAllBars(Rect fullRect, out float combinedHeaderHeight, out float combinedThreadHeight) @@ -1190,200 +1172,203 @@ void HandleThreadSplitterFoldoutButtons(GroupInfo group, ThreadInfo thread, Rect public void DoGUI(FrameDataView frameDataView, float width, float ypos, float height) { - if (frameDataView == null || !frameDataView.IsValid()) + using (m_DoGUIMarker.Auto()) { - GUILayout.Label(BaseStyles.noData, BaseStyles.label); - return; - } - - Rect fullRect = new Rect(0, ypos - 1, width, height + 1); - float sideWidth = Chart.kSideWidth - 1; + if (frameDataView == null || !frameDataView.IsValid()) + { + GUILayout.Label(BaseStyles.noData, BaseStyles.label); + return; + } - Rect timeRulerRect = new Rect(fullRect.x + sideWidth, fullRect.y, fullRect.width - sideWidth, k_LineHeight); + Rect fullRect = new Rect(0, ypos - 1, width, height + 1); + float sideWidth = Chart.kSideWidth - 1; - Rect timeAreaRect = new Rect(fullRect.x + sideWidth, fullRect.y + timeRulerRect.height, fullRect.width - sideWidth, fullRect.height - timeRulerRect.height); + Rect timeRulerRect = new Rect(fullRect.x + sideWidth, fullRect.y, fullRect.width - sideWidth, k_LineHeight); - bool initializing = false; - if (m_TimeArea == null) - { - initializing = true; - m_TimeArea = new ZoomableArea(); - m_TimeArea.hRangeLocked = false; - m_TimeArea.vRangeLocked = false; - m_TimeArea.hSlider = true; - m_TimeArea.vSlider = true; - m_TimeArea.vAllowExceedBaseRangeMax = false; - m_TimeArea.vAllowExceedBaseRangeMin = false; - m_TimeArea.hBaseRangeMin = 0; - m_TimeArea.vBaseRangeMin = 0; - m_TimeArea.vScaleMax = 1f; - m_TimeArea.vScaleMin = 1f; - m_TimeArea.scaleWithWindow = true; - m_TimeArea.margin = 10; - m_TimeArea.topmargin = 0; - m_TimeArea.bottommargin = 0; - m_TimeArea.upDirection = ZoomableArea.YDirection.Negative; - m_TimeArea.vZoomLockedByDefault = true; - } + Rect timeAreaRect = new Rect(fullRect.x + sideWidth, fullRect.y + timeRulerRect.height, fullRect.width - sideWidth, fullRect.height - timeRulerRect.height); - m_TimeArea.rect = timeAreaRect; + bool initializing = false; + if (m_TimeArea == null) + { + initializing = true; + m_TimeArea = new ZoomableArea(); + m_TimeArea.hRangeLocked = false; + m_TimeArea.vRangeLocked = false; + m_TimeArea.hSlider = true; + m_TimeArea.vSlider = true; + m_TimeArea.vAllowExceedBaseRangeMax = false; + m_TimeArea.vAllowExceedBaseRangeMin = false; + m_TimeArea.hBaseRangeMin = 0; + m_TimeArea.vBaseRangeMin = 0; + m_TimeArea.vScaleMax = 1f; + m_TimeArea.vScaleMin = 1f; + m_TimeArea.scaleWithWindow = true; + m_TimeArea.margin = 10; + m_TimeArea.topmargin = 0; + m_TimeArea.bottommargin = 0; + m_TimeArea.upDirection = ZoomableArea.YDirection.Negative; + m_TimeArea.vZoomLockedByDefault = true; + } - Rect bottomLeftFillRect = new Rect(0, ypos + height - m_TimeArea.vSliderWidth, sideWidth, m_TimeArea.vSliderWidth); + m_TimeArea.rect = timeAreaRect; - if (Event.current.type == EventType.Repaint) - { - styles.profilerGraphBackground.Draw(fullRect, false, false, false, false); - // The bar in the lower left side that fills the space next to the horizontal scrollbar. - EditorStyles.toolbar.Draw(bottomLeftFillRect, false, false, false, false); - } + Rect bottomLeftFillRect = new Rect(0, ypos + height - m_TimeArea.vSliderWidth, sideWidth, m_TimeArea.vSliderWidth); - if (initializing) - { - NativeProfilerTimeline_InitializeArgs args = new NativeProfilerTimeline_InitializeArgs(); - args.Reset(); - args.ghostAlpha = 0.3f; - args.nonSelectedAlpha = 0.75f; - args.guiStyle = styles.bar.m_Ptr; - args.lineHeight = k_LineHeight; - args.textFadeOutWidth = k_TextFadeOutWidth; - args.textFadeStartWidth = k_TextFadeStartWidth; - - NativeProfilerTimeline.Initialize(ref args); - } - // Prepare group and Thread Info - var iter = new ProfilerFrameDataIterator(); - int threadCount = iter.GetThreadCount(frameDataView.frameIndex); - iter.SetRoot(frameDataView.frameIndex, 0); - UpdateGroupAndThreadInfo(ref iter, frameDataView.frameIndex); - MarkDeadOrClearThread(); + if (Event.current.type == EventType.Repaint) + { + styles.profilerGraphBackground.Draw(fullRect, false, false, false, false); + // The bar in the lower left side that fills the space next to the horizontal scrollbar. + EditorStyles.toolbar.Draw(bottomLeftFillRect, false, false, false, false); + } - HandleFrameSelected(iter.frameTimeMS); + if (initializing) + { + NativeProfilerTimeline_InitializeArgs args = new NativeProfilerTimeline_InitializeArgs(); + args.Reset(); + args.ghostAlpha = 0.3f; + args.nonSelectedAlpha = 0.75f; + args.guiStyle = styles.bar.m_Ptr; + args.lineHeight = k_LineHeight; + args.textFadeOutWidth = k_TextFadeOutWidth; + args.textFadeStartWidth = k_TextFadeStartWidth; + + NativeProfilerTimeline.Initialize(ref args); + } + // Prepare group and Thread Info + var iter = new ProfilerFrameDataIterator(); + int threadCount = iter.GetThreadCount(frameDataView.frameIndex); + iter.SetRoot(frameDataView.frameIndex, 0); + UpdateGroupAndThreadInfo(ref iter, frameDataView.frameIndex); + MarkDeadOrClearThread(); - // update time area to new bounds - float combinedHeaderHeight, combinedThreadHeight; - float heightForAllBars = CalculateHeightForAllBars(fullRect, out combinedHeaderHeight, out combinedThreadHeight); - float emptySpaceBelowBars = k_LineHeight * 3f; + HandleFrameSelected(iter.frameTimeMS); - // if needed, take up more empty space below, to fill up the ZoomableArea - emptySpaceBelowBars = Mathf.Max(emptySpaceBelowBars, timeAreaRect.height - heightForAllBars); + // update time area to new bounds + float combinedHeaderHeight, combinedThreadHeight; + float heightForAllBars = CalculateHeightForAllBars(fullRect, out combinedHeaderHeight, out combinedThreadHeight); + float emptySpaceBelowBars = k_LineHeight * 3f; - heightForAllBars += emptySpaceBelowBars; + // if needed, take up more empty space below, to fill up the ZoomableArea + emptySpaceBelowBars = Mathf.Max(emptySpaceBelowBars, timeAreaRect.height - heightForAllBars); - m_TimeArea.hBaseRangeMax = iter.frameTimeMS; - m_TimeArea.vBaseRangeMax = heightForAllBars; + heightForAllBars += emptySpaceBelowBars; - if (Mathf.Abs(heightForAllBars - m_LastHeightForAllBars) >= 0.5f || Mathf.Abs(fullRect.height - m_LastFullRectHeight) >= 0.5f) - { - m_LastHeightForAllBars = heightForAllBars; - m_LastFullRectHeight = fullRect.height; + m_TimeArea.hBaseRangeMax = iter.frameTimeMS; + m_TimeArea.vBaseRangeMax = heightForAllBars; - // set V range to enforce scale of 1 and to shift the shown area up in case the drawn area shrunk down - m_TimeArea.SetShownVRange(m_TimeArea.shownArea.y, m_TimeArea.shownArea.y + m_TimeArea.drawRect.height); - } + if (Mathf.Abs(heightForAllBars - m_LastHeightForAllBars) >= 0.5f || Mathf.Abs(fullRect.height - m_LastFullRectHeight) >= 0.5f) + { + m_LastHeightForAllBars = heightForAllBars; + m_LastFullRectHeight = fullRect.height; - // frame the selection if needed and before drawing the time area - if (initializing) - PerformFrameSelected(iter.frameTimeMS); + // set V range to enforce scale of 1 and to shift the shown area up in case the drawn area shrunk down + m_TimeArea.SetShownVRange(m_TimeArea.shownArea.y, m_TimeArea.shownArea.y + m_TimeArea.drawRect.height); + } - DoTimeRulerGUI(timeRulerRect, sideWidth, iter.frameTimeMS); - DoTimeArea(); + // frame the selection if needed and before drawing the time area + if (initializing) + PerformFrameSelected(iter.frameTimeMS); - Rect fullThreadsRect = new Rect(fullRect.x, fullRect.y + timeRulerRect.height, fullRect.width - m_TimeArea.vSliderWidth, fullRect.height - timeRulerRect.height - m_TimeArea.hSliderHeight); + DoTimeRulerGUI(timeRulerRect, sideWidth, iter.frameTimeMS); + DoTimeArea(); - Rect fullThreadsRectWithoutSidebar = fullThreadsRect; - fullThreadsRectWithoutSidebar.x += sideWidth; - fullThreadsRectWithoutSidebar.width -= sideWidth; + Rect fullThreadsRect = new Rect(fullRect.x, fullRect.y + timeRulerRect.height, fullRect.width - m_TimeArea.vSliderWidth, fullRect.height - timeRulerRect.height - m_TimeArea.hSliderHeight); - // The splitters need to be handled after the time area so that they don't interfere with the input for panning/scrolling the ZoomableArea - DoThreadSplitters(fullThreadsRect, fullThreadsRectWithoutSidebar, frameDataView.frameIndex, ThreadSplitterCommand.HandleThreadSplitter); + Rect fullThreadsRectWithoutSidebar = fullThreadsRect; + fullThreadsRectWithoutSidebar.x += sideWidth; + fullThreadsRectWithoutSidebar.width -= sideWidth; - Rect barsUIRect = m_TimeArea.drawRect; + // The splitters need to be handled after the time area so that they don't interfere with the input for panning/scrolling the ZoomableArea + DoThreadSplitters(fullThreadsRect, fullThreadsRectWithoutSidebar, frameDataView.frameIndex, ThreadSplitterCommand.HandleThreadSplitter); - DrawGrid(barsUIRect, iter.frameTimeMS); + Rect barsUIRect = m_TimeArea.drawRect; - Rect barsAndSidebarUIRect = new Rect(barsUIRect.x - sideWidth, barsUIRect.y, barsUIRect.width + sideWidth, barsUIRect.height); + DrawGrid(barsUIRect, iter.frameTimeMS); - GUI.BeginClip(barsAndSidebarUIRect); + Rect barsAndSidebarUIRect = new Rect(barsUIRect.x - sideWidth, barsUIRect.y, barsUIRect.width + sideWidth, barsUIRect.height); - Rect shownBarsUIRect = barsUIRect; - shownBarsUIRect.y = scrollOffsetY; + GUI.BeginClip(barsAndSidebarUIRect); - // since the scale is not applied to the group headers, there would be some height unaccounted for - // this calculation applies that height to the threads via scaleForThreadHeight - float heightUnaccountedForDueToNotScalingHeaders = m_TimeArea.scale.y * combinedHeaderHeight - combinedHeaderHeight; - float scaleForThreadHeight = (combinedThreadHeight * m_TimeArea.scale.y + heightUnaccountedForDueToNotScalingHeaders) / combinedThreadHeight; + Rect shownBarsUIRect = barsUIRect; + shownBarsUIRect.y = scrollOffsetY; - DrawBars(shownBarsUIRect, scaleForThreadHeight); - GUI.EndClip(); + // since the scale is not applied to the group headers, there would be some height unaccounted for + // this calculation applies that height to the threads via scaleForThreadHeight + float heightUnaccountedForDueToNotScalingHeaders = m_TimeArea.scale.y * combinedHeaderHeight - combinedHeaderHeight; + float scaleForThreadHeight = (combinedThreadHeight * m_TimeArea.scale.y + heightUnaccountedForDueToNotScalingHeaders) / combinedThreadHeight; - DoRangeSelection(barsUIRect); + DrawBars(shownBarsUIRect, scaleForThreadHeight); + GUI.EndClip(); - GUI.BeginClip(barsUIRect); - shownBarsUIRect.x = 0; + DoRangeSelection(barsUIRect); - bool oldEnabled = GUI.enabled; - GUI.enabled = false; - // Walk backwards to find how many previous frames we need to show. - int maxContextFramesToShow = m_Window.IsRecording() ? 1 : 3; - int numContextFramesToShow = maxContextFramesToShow; - int currentFrame = frameDataView.frameIndex; - float currentTime = 0; - do - { - int prevFrame = ProfilerDriver.GetPreviousFrameIndex(currentFrame); - if (prevFrame == -1) - break; - iter.SetRoot(prevFrame, 0); - currentTime -= iter.frameTimeMS; - currentFrame = prevFrame; - --numContextFramesToShow; - } - while (currentTime > m_TimeArea.shownArea.x && numContextFramesToShow > 0); + GUI.BeginClip(barsUIRect); + shownBarsUIRect.x = 0; - // Draw previous frames - while (currentFrame != -1 && currentFrame != frameDataView.frameIndex) - { - iter.SetRoot(currentFrame, 0); - DoProfilerFrame(currentFrame, shownBarsUIRect, true, threadCount, currentTime, scaleForThreadHeight); - currentTime += iter.frameTimeMS; - currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame); - } + bool oldEnabled = GUI.enabled; + GUI.enabled = false; + // Walk backwards to find how many previous frames we need to show. + int maxContextFramesToShow = m_Window.IsRecording() ? 1 : 3; + int numContextFramesToShow = maxContextFramesToShow; + int currentFrame = frameDataView.frameIndex; + float currentTime = 0; + do + { + int prevFrame = ProfilerDriver.GetPreviousFrameIndex(currentFrame); + if (prevFrame == -1) + break; + iter.SetRoot(prevFrame, 0); + currentTime -= iter.frameTimeMS; + currentFrame = prevFrame; + --numContextFramesToShow; + } + while (currentTime > m_TimeArea.shownArea.x && numContextFramesToShow > 0); - // Draw next frames - numContextFramesToShow = maxContextFramesToShow; - currentFrame = frameDataView.frameIndex; - currentTime = 0; - while (currentTime < m_TimeArea.shownArea.x + m_TimeArea.shownArea.width && numContextFramesToShow >= 0) - { - if (frameDataView.frameIndex != currentFrame) + // Draw previous frames + while (currentFrame != -1 && currentFrame != frameDataView.frameIndex) + { + iter.SetRoot(currentFrame, 0); DoProfilerFrame(currentFrame, shownBarsUIRect, true, threadCount, currentTime, scaleForThreadHeight); - iter.SetRoot(currentFrame, 0); - currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame); - if (currentFrame == -1) - break; - currentTime += iter.frameTimeMS; - --numContextFramesToShow; - } + currentTime += iter.frameTimeMS; + currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame); + } + + // Draw next frames + numContextFramesToShow = maxContextFramesToShow; + currentFrame = frameDataView.frameIndex; + currentTime = 0; + while (currentTime < m_TimeArea.shownArea.x + m_TimeArea.shownArea.width && numContextFramesToShow >= 0) + { + if (frameDataView.frameIndex != currentFrame) + DoProfilerFrame(currentFrame, shownBarsUIRect, true, threadCount, currentTime, scaleForThreadHeight); + iter.SetRoot(currentFrame, 0); + currentFrame = ProfilerDriver.GetNextFrameIndex(currentFrame); + if (currentFrame == -1) + break; + currentTime += iter.frameTimeMS; + --numContextFramesToShow; + } - GUI.enabled = oldEnabled; + GUI.enabled = oldEnabled; - // Draw center frame last to get on top - threadCount = 0; - DoProfilerFrame(frameDataView.frameIndex, shownBarsUIRect, false, threadCount, 0, scaleForThreadHeight); + // Draw center frame last to get on top + threadCount = 0; + DoProfilerFrame(frameDataView.frameIndex, shownBarsUIRect, false, threadCount, 0, scaleForThreadHeight); - GUI.EndClip(); + GUI.EndClip(); - // Draw Foldout Buttons on top of natively drawn bars - DoThreadSplitters(fullThreadsRect, fullThreadsRectWithoutSidebar, frameDataView.frameIndex, ThreadSplitterCommand.HandleThreadSplitterFoldoutButtons); + // Draw Foldout Buttons on top of natively drawn bars + DoThreadSplitters(fullThreadsRect, fullThreadsRectWithoutSidebar, frameDataView.frameIndex, ThreadSplitterCommand.HandleThreadSplitterFoldoutButtons); - // Draw tooltips on top of clip to be able to extend outside of timeline area - DoSelectionTooltip(frameDataView.frameIndex, m_TimeArea.drawRect); + // Draw tooltips on top of clip to be able to extend outside of timeline area + DoSelectionTooltip(frameDataView.frameIndex, m_TimeArea.drawRect); - if (Event.current.type == EventType.Repaint) - { - // Reset all flags once Repaint finished on this view - m_LastRepaintProcessedInputs = m_CurrentlyProcessedInputs; - m_CurrentlyProcessedInputs = 0; + if (Event.current.type == EventType.Repaint) + { + // Reset all flags once Repaint finished on this view + m_LastRepaintProcessedInputs = m_CurrentlyProcessedInputs; + m_CurrentlyProcessedInputs = 0; + } } } diff --git a/Modules/ProfilerEditor/ProfilerWindow/ProfilerWindow.cs b/Modules/ProfilerEditor/ProfilerWindow/ProfilerWindow.cs index 1228f2fe70..127ff30dbb 100644 --- a/Modules/ProfilerEditor/ProfilerWindow/ProfilerWindow.cs +++ b/Modules/ProfilerEditor/ProfilerWindow/ProfilerWindow.cs @@ -107,7 +107,8 @@ static Styles() private Vector2 m_GraphPos = Vector2.zero; private Vector2[] m_PaneScroll = new Vector2[Profiler.areaCount]; private Vector2 m_PaneScroll_AudioChannels = Vector2.zero; - private Vector2 m_PaneScroll_AudioDSP = Vector2.zero; + private Vector2 m_PaneScroll_AudioDSPLeft = Vector2.zero; + private Vector2 m_PaneScroll_AudioDSPRight = Vector2.zero; private Vector2 m_PaneScroll_AudioClips = Vector2.zero; [SerializeField] @@ -122,7 +123,7 @@ static Styles() ProfilerArea? m_CurrentArea = ProfilerArea.CPU; ProfilerMemoryView m_ShowDetailedMemoryPane = ProfilerMemoryView.Simple; - ProfilerAudioView m_ShowDetailedAudioPane = ProfilerAudioView.Stats; + ProfilerAudioView m_ShowDetailedAudioPane = ProfilerAudioView.Channels; [SerializeField] bool m_ShowInactiveDSPChains = false; @@ -837,194 +838,192 @@ void DrawNetworkOperationsPane() } - private void AudioProfilerToggle(ProfilerCaptureFlags toggleFlag) + private enum ProfilerAudioPopupItems { - bool oldState = (AudioSettings.profilerCaptureFlags & (int)toggleFlag) != 0; - bool newState = GUILayout.Toggle(oldState, "Record", EditorStyles.toolbarButton); - if (oldState != newState) - ProfilerDriver.SetAudioCaptureFlags((AudioSettings.profilerCaptureFlags & ~(int)toggleFlag) | (newState - ? (int)toggleFlag - : 0)); + Simple = 0, + Detailed = 1 + } + + private bool AudioDeepProfileToggle() + { + int toggleFlags = (int)ProfilerCaptureFlags.Channels; + if (Unsupported.IsDeveloperMode()) + toggleFlags |= (int)ProfilerCaptureFlags.Clips | (int)ProfilerCaptureFlags.DSPNodes; + ProfilerAudioPopupItems oldShowDetailedAudioPane = (AudioSettings.profilerCaptureFlags & toggleFlags) != 0 ? ProfilerAudioPopupItems.Detailed : ProfilerAudioPopupItems.Simple; + ProfilerAudioPopupItems newShowDetailedAudioPane = (ProfilerAudioPopupItems)EditorGUILayout.EnumPopup(oldShowDetailedAudioPane, EditorStyles.toolbarDropDown, GUILayout.Width(70f)); + if (oldShowDetailedAudioPane != newShowDetailedAudioPane) + ProfilerDriver.SetAudioCaptureFlags((AudioSettings.profilerCaptureFlags & ~toggleFlags) | (newShowDetailedAudioPane == ProfilerAudioPopupItems.Detailed ? toggleFlags : 0)); + return (AudioSettings.profilerCaptureFlags & toggleFlags) != 0; + } + + private Rect DrawAudioStatsPane(ref Vector2 scrollPos) + { + var totalRect = GUILayoutUtility.GetRect(20f, 20000f, 10, 10000f); + var statsRect = new Rect(totalRect.x, totalRect.y, 230f, totalRect.height); + var rightRect = new Rect(statsRect.xMax, totalRect.y, totalRect.width - statsRect.width, totalRect.height); + + // STATS + var content = ProfilerDriver.GetOverviewText(m_CurrentArea.Value, GetActiveVisibleFrameIndex()); + var textSize = EditorStyles.wordWrappedLabel.CalcSize(GUIContent.Temp(content)); + scrollPos = GUI.BeginScrollView(statsRect, scrollPos, new Rect(0, 0, textSize.x, textSize.y)); + GUI.Label(new Rect(3, 3, textSize.x, textSize.y), content, EditorStyles.wordWrappedLabel); + GUI.EndScrollView(); + EditorGUI.DrawRect(new Rect(statsRect.xMax - 1, statsRect.y, 1, statsRect.height), Color.black); + + return rightRect; } private void DrawAudioPane() { EditorGUILayout.BeginHorizontal(EditorStyles.toolbar); ProfilerAudioView newShowDetailedAudioPane = m_ShowDetailedAudioPane; - if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Stats, "Stats", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Stats; - if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Channels, "Channels", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Channels; - if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Groups, "Groups", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Groups; - if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.ChannelsAndGroups, "Channels and groups", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.ChannelsAndGroups; - if (Unsupported.IsDeveloperMode() && GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.DSPGraph, "DSP Graph", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.DSPGraph; - if (Unsupported.IsDeveloperMode() && GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Clips, "Clips", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Clips; - if (newShowDetailedAudioPane != m_ShowDetailedAudioPane) - { - m_ShowDetailedAudioPane = newShowDetailedAudioPane; - m_LastAudioProfilerFrame = -1; // force update - } - if (m_ShowDetailedAudioPane == ProfilerAudioView.Stats) - { - GUILayout.Space(5); - GUILayout.FlexibleSpace(); - EditorGUILayout.EndHorizontal(); - DrawOverviewText(m_CurrentArea); - } - else if (m_ShowDetailedAudioPane == ProfilerAudioView.DSPGraph) + if (AudioDeepProfileToggle()) { - GUILayout.Space(5); - AudioProfilerToggle(ProfilerCaptureFlags.DSPNodes); - GUILayout.Space(5); - m_ShowInactiveDSPChains = GUILayout.Toggle(m_ShowInactiveDSPChains, "Show inactive", EditorStyles.toolbarButton); - if (m_ShowInactiveDSPChains) - m_HighlightAudibleDSPChains = GUILayout.Toggle(m_HighlightAudibleDSPChains, "Highlight audible", EditorStyles.toolbarButton); - GUILayout.FlexibleSpace(); - EditorGUILayout.EndHorizontal(); + if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Channels, "Channels", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Channels; + if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Groups, "Groups", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Groups; + if (GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.ChannelsAndGroups, "Channels and groups", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.ChannelsAndGroups; + if (Unsupported.IsDeveloperMode() && GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.DSPGraph, "DSP Graph", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.DSPGraph; + if (Unsupported.IsDeveloperMode() && GUILayout.Toggle(newShowDetailedAudioPane == ProfilerAudioView.Clips, "Clips", EditorStyles.toolbarButton)) newShowDetailedAudioPane = ProfilerAudioView.Clips; + if (newShowDetailedAudioPane != m_ShowDetailedAudioPane) + { + m_ShowDetailedAudioPane = newShowDetailedAudioPane; + m_LastAudioProfilerFrame = -1; // force update + } + if (m_ShowDetailedAudioPane == ProfilerAudioView.DSPGraph) + { + m_ShowInactiveDSPChains = GUILayout.Toggle(m_ShowInactiveDSPChains, "Show inactive", EditorStyles.toolbarButton); + if (m_ShowInactiveDSPChains) + m_HighlightAudibleDSPChains = GUILayout.Toggle(m_HighlightAudibleDSPChains, "Highlight audible", EditorStyles.toolbarButton); + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); - var totalRect = GUILayoutUtility.GetRect(20f, 10000f, 10, 20000f); + var graphRect = DrawAudioStatsPane(ref m_PaneScroll_AudioDSPLeft); - m_PaneScroll_AudioDSP = GUI.BeginScrollView(totalRect, m_PaneScroll_AudioDSP, new Rect(0, 0, 10000, 20000)); + m_PaneScroll_AudioDSPRight = GUI.BeginScrollView(graphRect, m_PaneScroll_AudioDSPRight, new Rect(0, 0, 10000, 20000)); - var clippingRect = new Rect(m_PaneScroll_AudioDSP.x, m_PaneScroll_AudioDSP.y, totalRect.width, totalRect.height); + var clippingRect = new Rect(m_PaneScroll_AudioDSPRight.x, m_PaneScroll_AudioDSPRight.y, graphRect.width, graphRect.height); - if (m_AudioProfilerDSPView == null) - m_AudioProfilerDSPView = new AudioProfilerDSPView(); + if (m_AudioProfilerDSPView == null) + m_AudioProfilerDSPView = new AudioProfilerDSPView(); - ProfilerProperty property = CreateProperty(); - if (CheckFrameData(property)) - { - m_AudioProfilerDSPView.OnGUI(clippingRect, property, m_ShowInactiveDSPChains, m_HighlightAudibleDSPChains, ref m_DSPGraphZoomFactor, ref m_PaneScroll_AudioDSP); - } - if (property != null) - property.Dispose(); + ProfilerProperty property = CreateProperty(); + if (CheckFrameData(property)) + { + m_AudioProfilerDSPView.OnGUI(clippingRect, property, m_ShowInactiveDSPChains, m_HighlightAudibleDSPChains, ref m_DSPGraphZoomFactor, ref m_PaneScroll_AudioDSPRight); + } + if (property != null) + property.Dispose(); - GUI.EndScrollView(); + GUI.EndScrollView(); - Repaint(); - } - else if (m_ShowDetailedAudioPane == ProfilerAudioView.Clips) - { - GUILayout.Space(5); - AudioProfilerToggle(ProfilerCaptureFlags.Clips); - GUILayout.FlexibleSpace(); - EditorGUILayout.EndHorizontal(); - - var totalRect = GUILayoutUtility.GetRect(20f, 20000f, 10, 10000f); - var statsRect = new Rect(totalRect.x, totalRect.y, 230f, totalRect.height); - var treeRect = new Rect(statsRect.xMax, totalRect.y, totalRect.width - statsRect.width, totalRect.height); + Repaint(); + } + else if (m_ShowDetailedAudioPane == ProfilerAudioView.Clips) + { + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); - // STATS - var content = ProfilerDriver.GetOverviewText(m_CurrentArea.Value, GetActiveVisibleFrameIndex()); - var textSize = EditorStyles.wordWrappedLabel.CalcSize(GUIContent.Temp(content)); - m_PaneScroll_AudioClips = GUI.BeginScrollView(statsRect, m_PaneScroll_AudioClips, new Rect(0, 0, textSize.x, textSize.y)); - GUI.Label(new Rect(3, 3, textSize.x, textSize.y), content, EditorStyles.wordWrappedLabel); - GUI.EndScrollView(); - EditorGUI.DrawRect(new Rect(statsRect.xMax - 1, statsRect.y, 1, statsRect.height), Color.black); + var treeRect = DrawAudioStatsPane(ref m_PaneScroll_AudioClips); - // TREE - if (m_AudioProfilerClipTreeViewState == null) - m_AudioProfilerClipTreeViewState = new AudioProfilerClipTreeViewState(); + // TREE + if (m_AudioProfilerClipTreeViewState == null) + m_AudioProfilerClipTreeViewState = new AudioProfilerClipTreeViewState(); - if (m_AudioProfilerClipViewBackend == null) - m_AudioProfilerClipViewBackend = new AudioProfilerClipViewBackend(m_AudioProfilerClipTreeViewState); + if (m_AudioProfilerClipViewBackend == null) + m_AudioProfilerClipViewBackend = new AudioProfilerClipViewBackend(m_AudioProfilerClipTreeViewState); - ProfilerProperty property = CreateProperty(); - if (CheckFrameData(property)) - { - if (m_CurrentFrame == -1 || m_LastAudioProfilerFrame != m_CurrentFrame) + ProfilerProperty property = CreateProperty(); + if (CheckFrameData(property)) { - m_LastAudioProfilerFrame = m_CurrentFrame; - var sourceItems = property.GetAudioProfilerClipInfo(); - if (sourceItems != null && sourceItems.Length > 0) + if (m_CurrentFrame == -1 || m_LastAudioProfilerFrame != m_CurrentFrame) { - var items = new List(); - foreach (var s in sourceItems) - { - items.Add(new AudioProfilerClipInfoWrapper(s, property.GetAudioProfilerNameByOffset(s.assetNameOffset))); - } - m_AudioProfilerClipViewBackend.SetData(items); - if (m_AudioProfilerClipView == null) + m_LastAudioProfilerFrame = m_CurrentFrame; + var sourceItems = property.GetAudioProfilerClipInfo(); + if (sourceItems != null && sourceItems.Length > 0) { - m_AudioProfilerClipView = new AudioProfilerClipView(this, m_AudioProfilerClipTreeViewState); - m_AudioProfilerClipView.Init(treeRect, m_AudioProfilerClipViewBackend); + var items = new List(); + foreach (var s in sourceItems) + { + items.Add(new AudioProfilerClipInfoWrapper(s, property.GetAudioProfilerNameByOffset(s.assetNameOffset))); + } + m_AudioProfilerClipViewBackend.SetData(items); + if (m_AudioProfilerClipView == null) + { + m_AudioProfilerClipView = new AudioProfilerClipView(this, m_AudioProfilerClipTreeViewState); + m_AudioProfilerClipView.Init(treeRect, m_AudioProfilerClipViewBackend); + } } } + if (m_AudioProfilerClipView != null) + m_AudioProfilerClipView.OnGUI(treeRect); } - if (m_AudioProfilerClipView != null) - m_AudioProfilerClipView.OnGUI(treeRect); + if (property != null) + property.Dispose(); } - if (property != null) - property.Dispose(); - } - else - { - GUILayout.Space(5); - AudioProfilerToggle(ProfilerCaptureFlags.Channels); - GUILayout.Space(5); - bool resetAllAudioClipPlayCountsOnPlay = GUILayout.Toggle(AudioUtil.resetAllAudioClipPlayCountsOnPlay, "Reset play count on play", EditorStyles.toolbarButton); - if (resetAllAudioClipPlayCountsOnPlay != AudioUtil.resetAllAudioClipPlayCountsOnPlay) - AudioUtil.resetAllAudioClipPlayCountsOnPlay = resetAllAudioClipPlayCountsOnPlay; - if (Unsupported.IsDeveloperMode()) + else { - GUILayout.Space(5); - bool showAllGroups = EditorPrefs.GetBool("AudioProfilerShowAllGroups"); - bool newShowAllGroups = GUILayout.Toggle(showAllGroups, "Show all groups (dev mode only)", EditorStyles.toolbarButton); - if (showAllGroups != newShowAllGroups) - EditorPrefs.SetBool("AudioProfilerShowAllGroups", newShowAllGroups); - } - GUILayout.FlexibleSpace(); - EditorGUILayout.EndHorizontal(); - - var totalRect = GUILayoutUtility.GetRect(20f, 20000f, 10, 10000f); - var statsRect = new Rect(totalRect.x, totalRect.y, 230f, totalRect.height); - var treeRect = new Rect(statsRect.xMax, totalRect.y, totalRect.width - statsRect.width, totalRect.height); + bool resetAllAudioClipPlayCountsOnPlay = GUILayout.Toggle(AudioUtil.resetAllAudioClipPlayCountsOnPlay, "Reset play count on play", EditorStyles.toolbarButton); + if (resetAllAudioClipPlayCountsOnPlay != AudioUtil.resetAllAudioClipPlayCountsOnPlay) + AudioUtil.resetAllAudioClipPlayCountsOnPlay = resetAllAudioClipPlayCountsOnPlay; + if (Unsupported.IsDeveloperMode()) + { + GUILayout.Space(5); + bool showAllGroups = EditorPrefs.GetBool("AudioProfilerShowAllGroups"); + bool newShowAllGroups = GUILayout.Toggle(showAllGroups, "Show all groups (dev mode only)", EditorStyles.toolbarButton); + if (showAllGroups != newShowAllGroups) + EditorPrefs.SetBool("AudioProfilerShowAllGroups", newShowAllGroups); + } + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); - // STATS - var content = ProfilerDriver.GetOverviewText(m_CurrentArea.Value, GetActiveVisibleFrameIndex()); - var textSize = EditorStyles.wordWrappedLabel.CalcSize(GUIContent.Temp(content)); - m_PaneScroll_AudioChannels = GUI.BeginScrollView(statsRect, m_PaneScroll_AudioChannels, new Rect(0, 0, textSize.x, textSize.y)); - GUI.Label(new Rect(3, 3, textSize.x, textSize.y), content, EditorStyles.wordWrappedLabel); - GUI.EndScrollView(); - EditorGUI.DrawRect(new Rect(statsRect.xMax - 1, statsRect.y, 1, statsRect.height), Color.black); + var treeRect = DrawAudioStatsPane(ref m_PaneScroll_AudioChannels); - // TREE - if (m_AudioProfilerGroupTreeViewState == null) - m_AudioProfilerGroupTreeViewState = new AudioProfilerGroupTreeViewState(); + // TREE + if (m_AudioProfilerGroupTreeViewState == null) + m_AudioProfilerGroupTreeViewState = new AudioProfilerGroupTreeViewState(); - if (m_AudioProfilerGroupViewBackend == null) - m_AudioProfilerGroupViewBackend = new AudioProfilerGroupViewBackend(m_AudioProfilerGroupTreeViewState); + if (m_AudioProfilerGroupViewBackend == null) + m_AudioProfilerGroupViewBackend = new AudioProfilerGroupViewBackend(m_AudioProfilerGroupTreeViewState); - ProfilerProperty property = CreateProperty(); - if (CheckFrameData(property)) - { - if (m_CurrentFrame == -1 || m_LastAudioProfilerFrame != m_CurrentFrame) + ProfilerProperty property = CreateProperty(); + if (CheckFrameData(property)) { - m_LastAudioProfilerFrame = m_CurrentFrame; - var sourceItems = property.GetAudioProfilerGroupInfo(); - if (sourceItems != null && sourceItems.Length > 0) + if (m_CurrentFrame == -1 || m_LastAudioProfilerFrame != m_CurrentFrame) { - var items = new List(); - foreach (var s in sourceItems) - { - bool isGroup = (s.flags & AudioProfilerGroupInfoHelper.AUDIOPROFILER_FLAGS_GROUP) != 0; - if (m_ShowDetailedAudioPane == ProfilerAudioView.Channels && isGroup) - continue; - if (m_ShowDetailedAudioPane == ProfilerAudioView.Groups && !isGroup) - continue; - items.Add(new AudioProfilerGroupInfoWrapper(s, property.GetAudioProfilerNameByOffset(s.assetNameOffset), property.GetAudioProfilerNameByOffset(s.objectNameOffset), m_ShowDetailedAudioPane == ProfilerAudioView.Channels)); - } - m_AudioProfilerGroupViewBackend.SetData(items); - if (m_AudioProfilerGroupView == null) + m_LastAudioProfilerFrame = m_CurrentFrame; + var sourceItems = property.GetAudioProfilerGroupInfo(); + if (sourceItems != null && sourceItems.Length > 0) { - m_AudioProfilerGroupView = new AudioProfilerGroupView(this, m_AudioProfilerGroupTreeViewState); - m_AudioProfilerGroupView.Init(treeRect, m_AudioProfilerGroupViewBackend); + var items = new List(); + foreach (var s in sourceItems) + { + bool isGroup = (s.flags & AudioProfilerGroupInfoHelper.AUDIOPROFILER_FLAGS_GROUP) != 0; + if (m_ShowDetailedAudioPane == ProfilerAudioView.Channels && isGroup) + continue; + if (m_ShowDetailedAudioPane == ProfilerAudioView.Groups && !isGroup) + continue; + items.Add(new AudioProfilerGroupInfoWrapper(s, property.GetAudioProfilerNameByOffset(s.assetNameOffset), property.GetAudioProfilerNameByOffset(s.objectNameOffset), m_ShowDetailedAudioPane == ProfilerAudioView.Channels)); + } + m_AudioProfilerGroupViewBackend.SetData(items); + if (m_AudioProfilerGroupView == null) + { + m_AudioProfilerGroupView = new AudioProfilerGroupView(this, m_AudioProfilerGroupTreeViewState); + m_AudioProfilerGroupView.Init(treeRect, m_AudioProfilerGroupViewBackend); + } } } + if (m_AudioProfilerGroupView != null) + m_AudioProfilerGroupView.OnGUI(treeRect, m_ShowDetailedAudioPane == ProfilerAudioView.Channels); } - if (m_AudioProfilerGroupView != null) - m_AudioProfilerGroupView.OnGUI(treeRect, m_ShowDetailedAudioPane == ProfilerAudioView.Channels); + if (property != null) + property.Dispose(); } - if (property != null) - property.Dispose(); + } + else + { + GUILayout.FlexibleSpace(); + EditorGUILayout.EndHorizontal(); + DrawOverviewText(m_CurrentArea); } } diff --git a/Modules/ProfilerEditor/Public/ProfilerAPI.bindings.cs b/Modules/ProfilerEditor/Public/ProfilerAPI.bindings.cs index b2b687f222..75bb8169db 100644 --- a/Modules/ProfilerEditor/Public/ProfilerAPI.bindings.cs +++ b/Modules/ProfilerEditor/Public/ProfilerAPI.bindings.cs @@ -54,7 +54,7 @@ public enum ProfilerMemoryView public enum ProfilerAudioView { - Stats = 0, + [Obsolete("This has been made obsolete. Audio stats are now shown on every subpane.", true)] Stats = 0, Channels = 1, Groups = 2, ChannelsAndGroups = 3, diff --git a/Modules/ProfilerEditor/Public/ProfilerFrameDataIterator.bindings.cs b/Modules/ProfilerEditor/Public/ProfilerFrameDataIterator.bindings.cs index 19037e8a21..c2ddb37866 100644 --- a/Modules/ProfilerEditor/Public/ProfilerFrameDataIterator.bindings.cs +++ b/Modules/ProfilerEditor/Public/ProfilerFrameDataIterator.bindings.cs @@ -63,6 +63,14 @@ public extern int depth get; } + /// + /// The maximal depth of the stacked samples. This count includes the thread root as well as counters. + /// + public extern int maxDepth + { + get; + } + public extern string path { [NativeMethod("GetFunctionPath")] diff --git a/Modules/RestService/Handler.cs b/Modules/RestService/Handler.cs deleted file mode 100644 index 537635e9ba..0000000000 --- a/Modules/RestService/Handler.cs +++ /dev/null @@ -1,115 +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 System.Text; -using UnityEditorInternal; - -namespace UnityEditor.RestService -{ - [UnityEngine.Scripting.RequiredByNativeCode] - internal abstract class Handler - { - // The following methods are invoked from native code. - protected abstract void InvokeGet(Request request, string payload, Response writeResponse); - protected abstract void InvokePost(Request request, string payload, Response writeResponse); - protected abstract void InvokeDelete(Request request, string payload, Response writeResponse); - } - - internal abstract class JSONHandler : Handler - { - protected override void InvokeGet(Request request, string payload, Response writeResponse) - { - CallSafely(request, payload, writeResponse, HandleGet); - } - - protected override void InvokePost(Request request, string payload, Response writeResponse) - { - CallSafely(request, payload, writeResponse, HandlePost); - } - - protected override void InvokeDelete(Request request, string payload, Response writeResponse) - { - CallSafely(request, payload, writeResponse, HandleDelete); - } - - private static void CallSafely(Request request, string payload, Response writeResponse, Func method) - { - try - { - JSONValue json = null; - - if (payload.Trim().Length == 0) - json = new JSONValue(); - else - { - try - { - json = new JSONParser(request.Payload).Parse(); - } - catch (JSONParseException) - { - ThrowInvalidJSONException(); - } - } - - writeResponse.SimpleResponse(HttpStatusCode.Ok, "application/json", method(request, json).ToString()); - } - catch (JSONTypeException) - { - ThrowInvalidJSONException(); - } - catch (KeyNotFoundException) - { - RespondWithException(writeResponse, new RestRequestException { HttpStatusCode = HttpStatusCode.BadRequest }); - } - catch (RestRequestException rre) - { - RespondWithException(writeResponse, rre); - } - catch (Exception e) - { - RespondWithException(writeResponse, new RestRequestException {HttpStatusCode = HttpStatusCode.InternalServerError, RestErrorString = "InternalServerError", RestErrorDescription = "Caught exception while fulfilling request: " + e}); - } - } - - private static void ThrowInvalidJSONException() - { - throw new RestRequestException {HttpStatusCode = HttpStatusCode.BadRequest, RestErrorString = "Invalid JSON"}; - } - - private static void RespondWithException(Response writeResponse, RestRequestException rre) - { - var body = new StringBuilder("{"); - if (rre.RestErrorString != null) - body.AppendFormat("\"error\":\"{0}\",", rre.RestErrorString); - if (rre.RestErrorDescription != null) - body.AppendFormat("\"errordescription\":\"{0}\"", rre.RestErrorDescription); - body.Append("}"); - writeResponse.SimpleResponse(rre.HttpStatusCode, "application/json", body.ToString()); - } - - virtual protected JSONValue HandleGet(Request request, JSONValue payload) - { - throw new RestRequestException {HttpStatusCode = HttpStatusCode.MethodNotAllowed, RestErrorString = "MethodNotAllowed", RestErrorDescription = "This endpoint does not support the GET verb."}; - } - - virtual protected JSONValue HandlePost(Request request, JSONValue payload) - { - throw new RestRequestException { HttpStatusCode = HttpStatusCode.MethodNotAllowed, RestErrorString = "MethodNotAllowed", RestErrorDescription = "This endpoint does not support the POST verb."}; - } - - virtual protected JSONValue HandleDelete(Request request, JSONValue payload) - { - throw new RestRequestException { HttpStatusCode = HttpStatusCode.MethodNotAllowed, RestErrorString = "MethodNotAllowed", RestErrorDescription = "This endpoint does not support the DELETE verb."}; - } - - protected static JSONValue ToJSON(IEnumerable strings) - { - return new JSONValue(strings.Select(s => new JSONValue(s)).ToList()); - } - } -} diff --git a/Modules/RestService/Logger.cs b/Modules/RestService/Logger.cs deleted file mode 100644 index 037a3f83a1..0000000000 --- a/Modules/RestService/Logger.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; - -namespace UnityEditor.RestService -{ - internal class Logger - { - static public void Log(Exception an_exception) - { - Debug.Log(an_exception.ToString()); - } - - static public void Log(string a_message) - { - Debug.Log(a_message); - } - } -} diff --git a/Modules/RestService/OpenDocumentsRestHandler.cs b/Modules/RestService/OpenDocumentsRestHandler.cs deleted file mode 100644 index 36b92630f5..0000000000 --- a/Modules/RestService/OpenDocumentsRestHandler.cs +++ /dev/null @@ -1,36 +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 System.Text; -using UnityEditorInternal; - -namespace UnityEditor.RestService -{ - internal class OpenDocumentsRestHandler : JSONHandler - { - protected override JSONValue HandlePost(Request request, JSONValue payload) - { - ScriptEditorSettings.OpenDocuments = payload.ContainsKey("documents") ? - payload["documents"].AsList().Select(d => d.AsString()).ToList() : - new List(); - ScriptEditorSettings.Save(); - return new JSONValue(); - } - - protected override JSONValue HandleGet(Request request, JSONValue payload) - { - var result = new JSONValue(); - result["documents"] = ToJSON(ScriptEditorSettings.OpenDocuments); - return result; - } - - internal static void Register() - { - Router.RegisterHandler("/unity/opendocuments", new OpenDocumentsRestHandler()); - } - } -} diff --git a/Modules/RestService/PairingRestHandler.cs b/Modules/RestService/PairingRestHandler.cs deleted file mode 100644 index f9f23498cd..0000000000 --- a/Modules/RestService/PairingRestHandler.cs +++ /dev/null @@ -1,78 +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.Diagnostics; -using System.IO; -using UnityEditor.Callbacks; -using UnityEditorInternal; -using UnityEngine; - -namespace UnityEditor.RestService -{ - internal class PairingRestHandler : JSONHandler - { - protected override JSONValue HandlePost(Request request, JSONValue payload) - { - ScriptEditorSettings.ServerURL = payload["url"].AsString(); - ScriptEditorSettings.Name = payload.ContainsKey("name") ? payload["name"].AsString() : null; - ScriptEditorSettings.ProcessId = payload.ContainsKey("processid") ? (int)payload["processid"].AsFloat() : -1; - - Logger.Log("[Pair] Name: " + (ScriptEditorSettings.Name ?? "") + - " ServerURL " + ScriptEditorSettings.ServerURL + - " Process id: " + ScriptEditorSettings.ProcessId); - - var result = new JSONValue(); - result["unityprocessid"] = Process.GetCurrentProcess().Id; - result["unityproject"] = Application.dataPath; - return result; - } - - internal static void Register() - { - Router.RegisterHandler("/unity/pair", new PairingRestHandler()); - } - - [OnOpenAsset] - static bool OnOpenAsset(int instanceID, int line) - { - if (ScriptEditorSettings.ServerURL == null) - return false; - - var assetpath = Path.GetFullPath(Application.dataPath + "/../" + AssetDatabase.GetAssetPath(instanceID)).Replace('\\', '/'); - var lowerAssetPath = assetpath.ToLower(); - - if (!lowerAssetPath.EndsWith(".cs") && !lowerAssetPath.EndsWith(".js") && !lowerAssetPath.EndsWith(".boo")) - return false; - - if (!IsScriptEditorRunning() || !RestRequest.Send("/openfile", "{ \"file\" : \"" + assetpath + "\", \"line\" : " + line + " }", 5000)) - { - ScriptEditorSettings.ServerURL = null; - ScriptEditorSettings.Name = null; - ScriptEditorSettings.ProcessId = -1; - - return false; - } - - return true; - } - - static bool IsScriptEditorRunning() - { - if (ScriptEditorSettings.ProcessId < 0) - return false; - - try - { - var process = Process.GetProcessById(ScriptEditorSettings.ProcessId); - return !process.HasExited; - } - catch (Exception e) - { - Logger.Log(e); - return false; - } - } - } -} diff --git a/Modules/RestService/PlayModeRestHandler.cs b/Modules/RestService/PlayModeRestHandler.cs deleted file mode 100644 index 74a3191e89..0000000000 --- a/Modules/RestService/PlayModeRestHandler.cs +++ /dev/null @@ -1,57 +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 UnityEditorInternal; - -namespace UnityEditor.RestService -{ - internal class PlayModeRestHandler : JSONHandler - { - protected override JSONValue HandlePost(Request request, JSONValue payload) - { - var action = payload.Get("action").AsString(); - string oldState = CurrentState(); - switch (action) - { - case "play": - EditorApplication.isPlaying = true; - EditorApplication.isPaused = false; - break; - case "pause": - EditorApplication.isPaused = true; - break; - case "stop": - EditorApplication.isPlaying = false; - break; - default: - throw new RestRequestException {HttpStatusCode = HttpStatusCode.BadRequest, RestErrorString = "Invalid action: " + action}; - } - - var result = new JSONValue(); - result["oldstate"] = oldState; - result["newstate"] = CurrentState(); - return result; - } - - protected override JSONValue HandleGet(Request request, JSONValue payload) - { - var result = new JSONValue(); - result["state"] = CurrentState(); - return result; - } - - internal static void Register() - { - Router.RegisterHandler("/unity/playmode", new PlayModeRestHandler()); - } - - internal string CurrentState() - { - if (!EditorApplication.isPlayingOrWillChangePlaymode) - return "stopped"; - - return EditorApplication.isPaused ? "paused" : "playing"; - } - } -} diff --git a/Modules/RestService/RestRequest.cs b/Modules/RestService/RestRequest.cs deleted file mode 100644 index 5c0fc4df03..0000000000 --- a/Modules/RestService/RestRequest.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 System.IO; -using System.Net; -using System.Text; - -namespace UnityEditor.RestService -{ - internal class RestRequest - { - static public bool Send(string endpoint, string payload, int timeout) - { - if (ScriptEditorSettings.ServerURL == null) - return false; - - // Send POST request - byte[] content = Encoding.UTF8.GetBytes(payload); - - var request = WebRequest.Create(ScriptEditorSettings.ServerURL + endpoint); - request.Timeout = timeout; - request.Method = "POST"; - request.ContentType = "application/json"; - request.ContentLength = content.Length; - - try - { - var stream = request.GetRequestStream(); - stream.Write(content, 0, content.Length); - stream.Close(); - } - catch (Exception e) - { - Logger.Log(e); - return false; - } - - try - { - request.BeginGetResponse(GetResponseCallback, request); - } - catch (Exception e) - { - Logger.Log(e); - return false; - } - - return true; - } - - private static void GetResponseCallback(IAsyncResult asynchronousResult) - { - var request = (WebRequest)asynchronousResult.AsyncState; - var response = request.EndGetResponse(asynchronousResult); - - try - { - var stream = response.GetResponseStream(); - var reader = new StreamReader(stream); - - reader.ReadToEnd(); - - reader.Close(); - stream.Close(); - } - finally - { - response.Close(); - } - } - } -} diff --git a/Modules/RestService/RestRequestException.cs b/Modules/RestService/RestRequestException.cs deleted file mode 100644 index b517303b91..0000000000 --- a/Modules/RestService/RestRequestException.cs +++ /dev/null @@ -1,30 +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.RestService -{ - internal class RestRequestException : Exception - { - public RestRequestException() - { - } - - public RestRequestException(HttpStatusCode httpStatusCode, string restErrorString) : this(httpStatusCode, restErrorString, null) - { - } - - public RestRequestException(HttpStatusCode httpStatusCode, string restErrorString, string restErrorDescription) - { - HttpStatusCode = httpStatusCode; - RestErrorString = restErrorString; - RestErrorDescription = restErrorDescription; - } - - public string RestErrorString { get; set; } - public HttpStatusCode HttpStatusCode { get; set; } - public string RestErrorDescription { get; set; } - } -} diff --git a/Modules/RestService/RestServiceExtension.cs b/Modules/RestService/RestServiceExtension.cs deleted file mode 100644 index 86e2c7f1d4..0000000000 --- a/Modules/RestService/RestServiceExtension.cs +++ /dev/null @@ -1,19 +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.RestService -{ - [InitializeOnLoad] - internal class RestServiceRegistration - { - static RestServiceRegistration() - { - OpenDocumentsRestHandler.Register(); - ProjectStateRestHandler.Register(); - AssetRestHandler.Register(); - PairingRestHandler.Register(); - PlayModeRestHandler.Register(); - } - } -} diff --git a/Modules/RestService/ScriptEditorSettings.cs b/Modules/RestService/ScriptEditorSettings.cs deleted file mode 100644 index 01d3f12383..0000000000 --- a/Modules/RestService/ScriptEditorSettings.cs +++ /dev/null @@ -1,80 +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.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using UnityEditorInternal; -using UnityEngine; - -namespace UnityEditor.RestService -{ - internal class ScriptEditorSettings - { - public static string Name { get; set; } - public static string ServerURL { get; set; } - public static int ProcessId { get; set; } - public static List OpenDocuments { get; set; } - - static ScriptEditorSettings() - { - OpenDocuments = new List(); - Clear(); - } - - private static string FilePath - { - get { return Application.dataPath + "/../Library/" + "UnityScriptEditorSettings.json"; } - } - - private static void Clear() - { - Name = null; - ServerURL = null; - ProcessId = -1; - } - - public static void Save() - { - var sb = new StringBuilder(); - - sb.AppendFormat("{{\n\t\"name\" : \"{0}\",\n\t\"serverurl\" : \"{1}\",\n\t\"processid\" : {2},\n\t", Name, ServerURL, ProcessId); - sb.AppendFormat("\"opendocuments\" : [{0}]\n}}", string.Join(",", OpenDocuments.Select(d => "\"" + d + "\"").ToArray())); - File.WriteAllText(FilePath, sb.ToString()); - } - - public static void Load() - { - try - { - var contents = File.ReadAllText(FilePath); - var json = new JSONParser(contents).Parse(); - - Name = json.ContainsKey("name") ? json["name"].AsString() : null; - ServerURL = json.ContainsKey("serverurl") ? json["serverurl"].AsString() : null; - ProcessId = json.ContainsKey("processid") ? (int)json["processid"].AsFloat() : -1; - OpenDocuments = json.ContainsKey("opendocuments") ? json["opendocuments"].AsList().Select(d => d.AsString()).ToList() : new List(); - - if (ProcessId >= 0) - { - Process.GetProcessById(ProcessId); - } - } - catch (FileNotFoundException) - { - Clear(); - Save(); - } - catch (Exception e) - { - Logger.Log(e); - Clear(); - Save(); - } - } - } -} diff --git a/Modules/SharedInternals/UnityString.cs b/Modules/SharedInternals/UnityString.cs deleted file mode 100644 index 3a2d2c8138..0000000000 --- a/Modules/SharedInternals/UnityString.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 System; -using System.Runtime.InteropServices; -using UnityEngine.Scripting; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - // This function exists because UnityEngine.dll is compiled against .NET 3.5, but .NET Core removes all the overloads - // except this one. So to prevent our code compiling against the (string, object, object) version and use the params - // version instead, we reroute through this. - // TODO: remove this when the dependency goes away. - [VisibleToOtherModules] - internal sealed partial class UnityString - { - public static string Format(string fmt, params object[] args) - { - return String.Format(fmt, args); - } - } -} diff --git a/Modules/ShortcutManagerEditor/ConflictResolver.cs b/Modules/ShortcutManagerEditor/ConflictResolver.cs index e54fc6df84..0a6cde0f5a 100644 --- a/Modules/ShortcutManagerEditor/ConflictResolver.cs +++ b/Modules/ShortcutManagerEditor/ConflictResolver.cs @@ -12,7 +12,7 @@ namespace UnityEditor.ShortcutManagement { class ConflictResolver : IConflictResolver { - public void ResolveConflict(List keyCombinationSequence, List entries) + public void ResolveConflict(IEnumerable keyCombinationSequence, IEnumerable entries) { var builder = new StringBuilder(); diff --git a/Modules/ShortcutManagerEditor/ContextManager.cs b/Modules/ShortcutManagerEditor/ContextManager.cs index 9a0de4c520..c6709cd1f7 100644 --- a/Modules/ShortcutManagerEditor/ContextManager.cs +++ b/Modules/ShortcutManagerEditor/ContextManager.cs @@ -16,6 +16,7 @@ interface IContextManager bool HasAnyPriorityContext(); bool HasPriorityContextOfType(Type type); bool HasActiveContextOfType(Type type); + bool playModeContextIsActive { get; } object GetContextInstanceOfType(Type type); } @@ -32,7 +33,19 @@ internal class GlobalContext {} List m_ToolContexts = new List(); - public int activeContextCount => 1 + ((m_FocusedWindow != null && m_FocusedWindow.IsAlive && m_FocusedWindow.Target != null) ? 1 : 0) + m_PriorityContexts.Count(c => c.active) + m_ToolContexts.Count(c => c.active); + public int activeContextCount => 1 + ((focusedWindow != null) ? 1 : 0) + m_PriorityContexts.Count(c => c.active) + m_ToolContexts.Count(c => c.active); + + public bool playModeContextIsActive => focusedWindow is GameView && EditorApplication.isPlaying; + + private EditorWindow focusedWindow + { + get + { + if (m_FocusedWindow != null && m_FocusedWindow.IsAlive && m_FocusedWindow.Target != null) + return m_FocusedWindow.Target as EditorWindow; + return null; + } + } public void SetFocusedWindow(EditorWindow window) { diff --git a/Modules/ShortcutManagerEditor/Directory.cs b/Modules/ShortcutManagerEditor/Directory.cs index e718465fd2..05f04b2292 100644 --- a/Modules/ShortcutManagerEditor/Directory.cs +++ b/Modules/ShortcutManagerEditor/Directory.cs @@ -56,6 +56,12 @@ public void FindShortcutEntries(List combinationSequence, IConte { if (!contextManager.HasActiveContextOfType(shortcutEntry.context)) continue; + if (shortcutEntry.type != ShortcutType.Menu && contextManager.playModeContextIsActive) + // Emulate old play mode shortcut behavior + // * Menu shortcuts are always active + // * Non-menu shortcuts only apply when the game view does not have focus + continue; + outputShortcuts.Add(shortcutEntry); } } diff --git a/Modules/ShortcutManagerEditor/IConflictResolver.cs b/Modules/ShortcutManagerEditor/IConflictResolver.cs index 06f79d4fdf..845e86f5e0 100644 --- a/Modules/ShortcutManagerEditor/IConflictResolver.cs +++ b/Modules/ShortcutManagerEditor/IConflictResolver.cs @@ -8,5 +8,5 @@ interface IConflictResolver { - void ResolveConflict(List keyCombinationSequence, List entries); + void ResolveConflict(IEnumerable keyCombinationSequence, IEnumerable entries); } diff --git a/Modules/ShortcutManagerEditor/ShortcutAttributeDiscoveryProvider.cs b/Modules/ShortcutManagerEditor/ShortcutAttributeDiscoveryProvider.cs index 196892e6dd..ed6c0ee843 100644 --- a/Modules/ShortcutManagerEditor/ShortcutAttributeDiscoveryProvider.cs +++ b/Modules/ShortcutManagerEditor/ShortcutAttributeDiscoveryProvider.cs @@ -2,6 +2,7 @@ // 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 System.Reflection; @@ -39,15 +40,15 @@ public IEnumerable GetDefinedShortcuts() { var entries = new List(); var names = new List(); - var shortcuts = new List(); - Menu.GetMenuItemShortcuts(names, shortcuts); + var defaultShortcuts = new List(); + Menu.GetMenuItemDefaultShortcuts(names, defaultShortcuts); entries.Capacity += names.Count; for (int index = 0; index < names.Count; ++index) { var keys = new List(); - if (!string.IsNullOrEmpty(shortcuts[index])) - keys.Add(new KeyCombination(Event.KeyboardEvent(shortcuts[index]))); + if (!string.IsNullOrEmpty(defaultShortcuts[index])) + keys.Add(new KeyCombination(Event.KeyboardEvent(defaultShortcuts[index]))); entries.Add(new MenuItemEntryDiscoveryInfo(names[index], keys)); } @@ -139,7 +140,8 @@ public MenuItemEntryDiscoveryInfo(string menuItemPath, List keys m_KeyCombinations = keys; m_MenuItemPath = menuItemPath; - m_ShortcutEntry = new ShortcutEntry(new Identifier(m_MenuItemPath), m_KeyCombinations, null, null, ShortcutType.Menu); + Action menuAction = (args) => { EditorApplication.ExecuteMenuItem(m_MenuItemPath); }; + m_ShortcutEntry = new ShortcutEntry(new Identifier(m_MenuItemPath), m_KeyCombinations, menuAction, null, ShortcutType.Menu); } public ShortcutEntry GetShortcutEntry() diff --git a/Modules/ShortcutManagerEditor/ShortcutController.cs b/Modules/ShortcutManagerEditor/ShortcutController.cs index 068fe5f33c..34f3303ddc 100644 --- a/Modules/ShortcutManagerEditor/ShortcutController.cs +++ b/Modules/ShortcutManagerEditor/ShortcutController.cs @@ -16,9 +16,17 @@ static ShortcutIntegration() { InitializeController(); EditorApplication.globalEventHandler += EventHandler; + EditorApplication.doPressedKeysTriggerAnyShortcut += HasAnyEntriesHandler; // Need to reinitialize after project load if we want menu items EditorApplication.projectWasLoaded += InitializeController; + + EditorApplication.focusChanged += OnFocusChanged; + } + + static bool HasAnyEntriesHandler() + { + return instance.HasAnyEntries(Event.current); } static void EventHandler() @@ -27,6 +35,17 @@ static void EventHandler() instance.HandleKeyEvent(Event.current); } + static void OnInvokingAction(ShortcutEntry shortcutEntry, ShortcutArguments shortcutArguments) + { + // Separate shortcut actions into different undo groups + Undo.IncrementCurrentGroup(); + } + + static void OnFocusChanged(bool isFocused) + { + instance.trigger.ResetActiveClutches(); + } + static void InitializeController() { var shortcutProviders = new IDiscoveryShortcutProvider[] @@ -39,6 +58,7 @@ static void InitializeController() var discovery = new Discovery(shortcutProviders, identifierConflictHandler, invalidContextReporter); instance = new ShortcutController(discovery); instance.Initialize(instance.profileManager); + instance.trigger.invokingAction += OnInvokingAction; } } @@ -49,6 +69,7 @@ class ShortcutController public IShortcutProfileManager profileManager { get; } public IDirectory directory => m_Directory; + public Trigger trigger => m_Trigger; ContextManager m_ContextManager = new ContextManager(); @@ -67,6 +88,11 @@ internal void Initialize(IShortcutProfileManager sender) m_Trigger = new Trigger(directory, new ConflictResolver()); } + internal bool HasAnyEntries(Event evt) + { + return m_Trigger.HasAnyEntries(); + } + internal void HandleKeyEvent(Event evt) { m_Trigger.HandleKeyEvent(evt, contextManager); diff --git a/Modules/ShortcutManagerEditor/ShortcutEntry.cs b/Modules/ShortcutManagerEditor/ShortcutEntry.cs index 298751209b..06f605f018 100644 --- a/Modules/ShortcutManagerEditor/ShortcutEntry.cs +++ b/Modules/ShortcutManagerEditor/ShortcutEntry.cs @@ -74,10 +74,10 @@ class ShortcutEntry public Type context => m_Context; public ShortcutType type => m_Type; - internal ShortcutEntry(Identifier id, List defaultCombination, Action action, Type context, ShortcutType type) + internal ShortcutEntry(Identifier id, IEnumerable defaultCombination, Action action, Type context, ShortcutType type) { m_Identifier = id; - m_DefaultCombinations = new List(defaultCombination); + m_DefaultCombinations = defaultCombination.ToList(); m_Context = context ?? ContextManager.globalContextType; m_Action = action; m_Type = type; diff --git a/Modules/ShortcutManagerEditor/Trigger.cs b/Modules/ShortcutManagerEditor/Trigger.cs index 3aaf584b68..87358087be 100644 --- a/Modules/ShortcutManagerEditor/Trigger.cs +++ b/Modules/ShortcutManagerEditor/Trigger.cs @@ -17,7 +17,8 @@ class Trigger List m_KeyCombinationSequence = new List(); List m_Entries = new List(); Dictionary> m_ActiveClutches = new Dictionary>(); - HashSet m_KeysDown = new HashSet(); + + public event Action invokingAction; public Trigger(IDirectory directory, IConflictResolver conflictResolver) { @@ -32,7 +33,6 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) if (evt.type == EventType.KeyUp) { - m_KeysDown.Remove(evt.keyCode); Tuple clutchTuple; if (m_ActiveClutches.TryGetValue(evt.keyCode, out clutchTuple)) { @@ -44,17 +44,18 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) context = clutchContext, state = ShortcutState.End }; + invokingAction?.Invoke(clutchTuple.Item1, args); clutchTuple.Item1.action(args); } return; } - if (m_KeysDown.Contains(evt.keyCode)) + // Use the event and return if the key is currently used in an active clutch + if (m_ActiveClutches.ContainsKey(evt.keyCode)) { evt.Use(); return; } - m_KeysDown.Add(evt.keyCode); var keyCodeCombination = new KeyCombination(evt); m_KeyCombinationSequence.Add(keyCodeCombination); @@ -64,26 +65,24 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) return; m_Directory.FindShortcutEntries(m_KeyCombinationSequence, contextManager, m_Entries); + IEnumerable entries = m_Entries; // Deal ONLY with prioritycontext - if (m_Entries.Count > 1 && contextManager.HasAnyPriorityContext()) + if (entries.Count() > 1 && contextManager.HasAnyPriorityContext()) { - var entry = m_Entries.FindAll(a => contextManager.HasPriorityContextOfType(a.context)); - if (entry.Any()) - { - m_Entries.Clear(); - m_Entries.AddRange(entry); - } + entries = m_Entries.FindAll(a => contextManager.HasPriorityContextOfType(a.context)); + if (!entries.Any()) + entries = m_Entries; } - switch (m_Entries.Count) + switch (entries.Count()) { case 0: Reset(); break; case 1: - var shortcutEntry = m_Entries.Single(); + var shortcutEntry = entries.Single(); if (ShortcutFullyMatchesKeyCombination(shortcutEntry)) { if (evt.keyCode != m_KeyCombinationSequence.Last().keyCode) @@ -95,6 +94,7 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) { case ShortcutType.Action: args.state = ShortcutState.End; + invokingAction?.Invoke(shortcutEntry, args); shortcutEntry.action(args); evt.Use(); Reset(); @@ -105,6 +105,7 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) { m_ActiveClutches.Add(evt.keyCode, new Tuple(shortcutEntry, args.context)); args.state = ShortcutState.Begin; + invokingAction?.Invoke(shortcutEntry, args); shortcutEntry.action(args); evt.Use(); Reset(); @@ -112,7 +113,8 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) break; case ShortcutType.Menu: args.state = ShortcutState.End; - EditorApplication.ExecuteMenuItem(shortcutEntry.identifier.path); + invokingAction?.Invoke(shortcutEntry, args); + shortcutEntry.action(args); evt.Use(); Reset(); break; @@ -121,20 +123,42 @@ public void HandleKeyEvent(Event evt, IContextManager contextManager) break; default: - if (HasConflicts(m_Entries, m_KeyCombinationSequence)) + if (HasConflicts(entries, m_KeyCombinationSequence)) { - m_ConflictResolver.ResolveConflict(m_KeyCombinationSequence, m_Entries); + m_ConflictResolver.ResolveConflict(m_KeyCombinationSequence, entries); + evt.Use(); Reset(); } break; } } + public void ResetActiveClutches() + { + foreach (var clutchTuple in m_ActiveClutches.Values) + { + var args = new ShortcutArguments + { + context = clutchTuple.Item2, + state = ShortcutState.End, + }; + invokingAction?.Invoke(clutchTuple.Item1, args); + clutchTuple.Item1.action(args); + } + + m_ActiveClutches.Clear(); + } + + public bool HasAnyEntries() + { + return m_Entries.Any(); + } + // filtered entries are expected to all be in the same context and/or null context and they all are known to share the prefix - bool HasConflicts(List filteredEntries, List prefix) + bool HasConflicts(IEnumerable filteredEntries, List prefix) { if (filteredEntries.Any(e => e.FullyMatches(prefix))) - return filteredEntries.Count > 1; + return filteredEntries.Count() > 1; return false; } diff --git a/Modules/Terrain/Public/BrushTransform.cs b/Modules/Terrain/Public/BrushTransform.cs new file mode 100644 index 0000000000..229d3b07ea --- /dev/null +++ b/Modules/Terrain/Public/BrushTransform.cs @@ -0,0 +1,80 @@ +// 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.Rendering; + +namespace UnityEngine.Experimental.TerrainAPI +{ + // represents a linear 2D transform between brush UV space and some other target XY space + // xy = u * brushU + v * brushV + brushOrigin + // uv = x * targetX + y * targetY + targetOrigin + public struct BrushTransform + { + public Vector2 brushOrigin { get; } // brush UV origin, in XY space + public Vector2 brushU { get; } // brush U vector, in XY space + public Vector2 brushV { get; } // brush V vector, in XY space + + public Vector2 targetOrigin { get; } // XY origin, in brush UV space + public Vector2 targetX { get; } // X vector, in brush UV space + public Vector2 targetY { get; } // Y vector, in brush UV space + + public BrushTransform(Vector2 brushOrigin, Vector2 brushU, Vector2 brushV) + { + // invert the rotation matrix [BrushU, BrushV] + // this gives us [X, Y] vectors in brush UV space + // note we run the true inverse, to support non-orthogonal brush axes + float det = brushU.x * brushV.y - brushU.y * brushV.x; + float invDet = Mathf.Approximately(det, 0.0f) ? 1.0f : 1.0f / det; // for non-invert-able matrices, we do 'something' + Vector2 targetX = new Vector2(brushV.y, -brushU.y) * invDet; + Vector2 targetY = new Vector2(-brushV.x, brushU.x) * invDet; + + // calculate XY origin in brush UV space + Vector2 targetOrigin = -brushOrigin.x * targetX - brushOrigin.y * targetY; + + this.brushOrigin = brushOrigin; + this.brushU = brushU; + this.brushV = brushV; + this.targetOrigin = targetOrigin; + this.targetX = targetX; + this.targetY = targetY; + } + + public Rect GetBrushXYBounds() // get the XY bounding rectangle around the Brush [0,1] UV space + { + // compute all four corners of the brush [0,1] UV space + Vector2 pU = brushOrigin + brushU; + Vector2 pV = brushOrigin + brushV; + Vector2 pUV = brushOrigin + brushU + brushV; + + // compute min and max XY coordinates + float minX = Mathf.Min(Mathf.Min(brushOrigin.x, pU.x), Mathf.Min(pV.x, pUV.x)); + float maxX = Mathf.Max(Mathf.Max(brushOrigin.x, pU.x), Mathf.Max(pV.x, pUV.x)); + float minY = Mathf.Min(Mathf.Min(brushOrigin.y, pU.y), Mathf.Min(pV.y, pUV.y)); + float maxY = Mathf.Max(Mathf.Max(brushOrigin.y, pU.y), Mathf.Max(pV.y, pUV.y)); + + // return the XY bounding rectangle + return Rect.MinMaxRect(minX, minY, maxX, maxY); + } + + public static BrushTransform FromRect(Rect brushRect) + { + Vector2 brushOrigin = brushRect.min; + Vector2 brushU = new Vector2(brushRect.width, 0.0f); + Vector2 brushV = new Vector2(0.0f, brushRect.height); + return new BrushTransform(brushOrigin, brushU, brushV); + } + + public Vector2 ToBrushUV(Vector2 targetXY) + { + return targetXY.x * targetX + targetXY.y * targetY + targetOrigin; + } + + public Vector2 FromBrushUV(Vector2 brushUV) + { + return brushUV.x * brushU + brushUV.y * brushV + brushOrigin; + } + } +} diff --git a/Modules/Terrain/Public/PaintContext.cs b/Modules/Terrain/Public/PaintContext.cs new file mode 100644 index 0000000000..f85775e442 --- /dev/null +++ b/Modules/Terrain/Public/PaintContext.cs @@ -0,0 +1,632 @@ +// 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.Rendering; + +namespace UnityEngine.Experimental.TerrainAPI +{ + public class PaintContext + { + // initialized by constructor + public Terrain originTerrain { get; } // the terrain that defines the coordinate system and world space position of this PaintContext + public RectInt pixelRect { get; } // the rectangle, in target texture pixels on the originTerrain, that this paint context represents + public int targetTextureWidth { get; } // the size of the target texture, per terrain tile + public int targetTextureHeight { get; } // the size of the target texture, per terrain tile + 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 int terrainCount { get { return m_TerrainTiles.Count; } } + public Terrain GetTerrain(int terrainIndex) + { + return m_TerrainTiles[terrainIndex].terrain; + } + + public RectInt GetClippedPixelRectInTerrainPixels(int terrainIndex) + { + return m_TerrainTiles[terrainIndex].clippedLocal; + } + + public RectInt GetClippedPixelRectInRenderTexturePixels(int terrainIndex) + { + Rect vp = m_TerrainTiles[terrainIndex].validPaintRect; + return new RectInt( + Mathf.RoundToInt(vp.xMin), + Mathf.RoundToInt(vp.yMin), + Mathf.RoundToInt(vp.width), + Mathf.RoundToInt(vp.height)); + } + + // initialized by constructor + 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 + { + public TerrainTile() {} + public TerrainTile(Terrain newTerrain, RectInt newRegion) { rect = newRegion; terrain = newTerrain; } + + public Terrain terrain; // the terrain object + public RectInt rect; // coordinates of this terrain tile in paint context pixels (essentially originTerrain target texture pixels) + public RectInt clippedLocal; // pixelRect in local pixel coordinates (for target texture), clipped to the local tile + public Rect validPaintRect; // the area per tile where the source texture was able to read from (in paint context pixels) + public int mapIndex; // + public int channelIndex; // + + // offsets used for gather / scatter + public Vector2Int readOffset; // offsets used when reading from the terrain heightmap + public Vector2Int writeOffset; // offsets used when copying from PaintContext clipped heightmap back to the terrain heightmap + } + + [Flags] + internal enum ToolAction + { + None = 0, + PaintHeightmap = 1 << 0, + PaintTexture = 1 << 1, + } + + // TerrainPaintUtilityEditor hooks to this event to do automatic undo + internal static event Action onTerrainTileBeforePaint; + + public PaintContext(Terrain terrain, RectInt pixelRect, int targetTextureWidth, int targetTextureHeight) + { + this.originTerrain = terrain; + this.pixelRect = pixelRect; + this.targetTextureWidth = targetTextureWidth; + this.targetTextureHeight = targetTextureHeight; + TerrainData terrainData = terrain.terrainData; + this.pixelSize = new Vector2( + terrainData.size.x / (targetTextureWidth - 1.0f), + terrainData.size.z / (targetTextureHeight - 1.0f)); + + FindTerrainTiles(); + ClipTerrainTiles(); + } + + public static PaintContext CreateFromBounds(Terrain terrain, Rect boundsInTerrainSpace, int inputTextureWidth, int inputTextureHeight, int extraBorderPixels = 0) + { + return new PaintContext( + terrain, + TerrainPaintUtility.CalcPixelRectFromBounds(terrain, boundsInTerrainSpace, inputTextureWidth, inputTextureHeight, extraBorderPixels), + inputTextureWidth, inputTextureHeight); + } + + internal void FindTerrainTiles() + { + m_TerrainTiles = new List(); + + Terrain left = originTerrain.leftNeighbor; + Terrain right = originTerrain.rightNeighbor; + Terrain top = originTerrain.topNeighbor; + Terrain bottom = originTerrain.bottomNeighbor; + + bool wantLeft = (pixelRect.x < 0); + bool wantRight = (pixelRect.xMax > (targetTextureWidth - 1)); + bool wantTop = (pixelRect.yMax > (targetTextureHeight - 1)); + bool wantBottom = (pixelRect.y < 0); + + if (wantLeft && wantRight) + { + Debug.LogWarning("PaintContext pixelRect is too large! It should touch a maximum of 2 Terrains horizontally."); + wantRight = false; + } + + if (wantTop && wantBottom) + { + Debug.LogWarning("PaintContext pixelRect is too large! It should touch a maximum of 2 Terrains vertically."); + wantBottom = false; + } + + // add center tile + TerrainTile tile = new TerrainTile(originTerrain, new RectInt(0, 0, targetTextureWidth, targetTextureHeight)); + tile.readOffset = Vector2Int.zero; + tile.writeOffset = Vector2Int.zero; + m_TerrainTiles.Add(tile); + + // add horizontal and vertical neighbors + Terrain horiz = null; + Terrain vert = null; + Terrain cornerTerrain = null; + + int xBias = 0; + int yBias = 0; + int xReadBias = 0; + int yReadBias = 0; + int xWriteBias = 0; + int yWriteBias = 0; + + if (wantLeft) + { + xBias = -1; + xReadBias = -1; + xWriteBias = 1; + horiz = left; + } + else if (wantRight) + { + xBias = 1; + xReadBias = 1; + xWriteBias = -1; + horiz = right; + } + + if (wantTop) + { + yBias = 1; + yReadBias = 1; + yWriteBias = -1; + vert = top; + } + else if (wantBottom) + { + yBias = -1; + yReadBias = -1; + yWriteBias = 1; + vert = bottom; + } + + if (horiz) + { + tile = new TerrainTile(horiz, new RectInt(xBias * targetTextureWidth, 0, targetTextureWidth, targetTextureHeight)); + tile.readOffset = new Vector2Int(xReadBias, 0); + tile.writeOffset = new Vector2Int(xWriteBias, 0); + m_TerrainTiles.Add(tile); + + // add corner, if we have a link + if (wantTop && horiz.topNeighbor) + cornerTerrain = horiz.topNeighbor; + else if (wantBottom && horiz.bottomNeighbor) + cornerTerrain = horiz.bottomNeighbor; + } + + if (vert) + { + tile = new PaintContext.TerrainTile(vert, new RectInt(0, yBias * targetTextureHeight, targetTextureWidth, targetTextureHeight)); + tile.readOffset = new Vector2Int(0, yReadBias); + tile.writeOffset = new Vector2Int(0, yWriteBias); + m_TerrainTiles.Add(tile); + + // add corner, if we have a link + if (wantLeft && vert.leftNeighbor) + cornerTerrain = vert.leftNeighbor; + else if (wantRight && vert.rightNeighbor) + cornerTerrain = vert.rightNeighbor; + } + + if (cornerTerrain != null) + { + tile = new TerrainTile(cornerTerrain, new RectInt(xBias * targetTextureWidth, yBias * targetTextureHeight, targetTextureWidth, targetTextureHeight)); + tile.readOffset = new Vector2Int(xReadBias, yReadBias); + tile.writeOffset = new Vector2Int(xWriteBias, yWriteBias); + m_TerrainTiles.Add(tile); + } + } + + internal void ClipTerrainTiles() + { + for (int i = 0; i < m_TerrainTiles.Count; i++) + { + TerrainTile tile = m_TerrainTiles[i]; + tile.clippedLocal = new RectInt(); + tile.clippedLocal.x = Mathf.Max(0, pixelRect.x - tile.rect.x); + tile.clippedLocal.y = Mathf.Max(0, pixelRect.y - tile.rect.y); + tile.clippedLocal.xMax = Mathf.Min(tile.rect.width, pixelRect.xMax - tile.rect.x); + tile.clippedLocal.yMax = Mathf.Min(tile.rect.height, pixelRect.yMax - tile.rect.y); + + tile.validPaintRect = new Rect( + tile.clippedLocal.x + tile.rect.x - pixelRect.x, + tile.clippedLocal.y + tile.rect.y - pixelRect.y, + tile.clippedLocal.width, + tile.clippedLocal.height); + } + } + + 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; + } + + 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; + } + + public void GatherHeightmap() + { + Material blitMaterial = TerrainPaintUtility.GetBlitMaterial(); + + RenderTexture.active = sourceRenderTexture; + GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); + + for (int i = 0; i < m_TerrainTiles.Count; i++) + { + TerrainTile terrainTile = m_TerrainTiles[i]; + if (terrainTile.clippedLocal.width == 0 || terrainTile.clippedLocal.height == 0) + continue; + + Texture sourceTexture = terrainTile.terrain.terrainData.heightmapTexture; + if ((sourceTexture.width != targetTextureWidth) || (sourceTexture.height != targetTextureHeight)) + { + Debug.LogWarning("PaintContext heightmap operations must use the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); + continue; + } + + Rect readRect = new Rect( + (terrainTile.clippedLocal.x + terrainTile.readOffset.x) / (float)targetTextureWidth, + (terrainTile.clippedLocal.y + terrainTile.readOffset.y) / (float)targetTextureHeight, + (terrainTile.clippedLocal.width) / (float)targetTextureWidth, + (terrainTile.clippedLocal.height) / (float)targetTextureHeight); + + FilterMode oldFilterMode = sourceTexture.filterMode; + + sourceTexture.filterMode = FilterMode.Point; + + blitMaterial.SetTexture("_MainTex", sourceTexture); + blitMaterial.SetPass(0); + + TerrainPaintUtility.DrawQuad(pixelRect.width, pixelRect.height, readRect, terrainTile.validPaintRect); + + sourceTexture.filterMode = oldFilterMode; + } + + RenderTexture.active = oldRenderTexture; + } + + public void ScatterHeightmap(string editorUndoName) + { + Material blitMaterial = TerrainPaintUtility.GetBlitMaterial(); + + for (int i = 0; i < m_TerrainTiles.Count; i++) + { + TerrainTile terrainTile = m_TerrainTiles[i]; + if (terrainTile.clippedLocal.width == 0 || terrainTile.clippedLocal.height == 0) + continue; + + RenderTexture heightmap = terrainTile.terrain.terrainData.heightmapTexture; + if ((heightmap.width != targetTextureWidth) || (heightmap.height != 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; + + Rect readRect = new Rect( + (terrainTile.clippedLocal.x + terrainTile.rect.x - pixelRect.x + terrainTile.writeOffset.x) / (float)pixelRect.width, + (terrainTile.clippedLocal.y + terrainTile.rect.y - pixelRect.y + terrainTile.writeOffset.y) / (float)pixelRect.height, + (terrainTile.clippedLocal.width) / (float)pixelRect.width, + (terrainTile.clippedLocal.height) / (float)pixelRect.height); + + Rect writeRect = new Rect( + terrainTile.clippedLocal.x, + terrainTile.clippedLocal.y, + terrainTile.clippedLocal.width, + terrainTile.clippedLocal.height); + + destinationRenderTexture.filterMode = FilterMode.Point; + + blitMaterial.SetTexture("_MainTex", destinationRenderTexture); + blitMaterial.SetPass(0); + + TerrainPaintUtility.DrawQuad(heightmap.width, heightmap.height, readRect, writeRect); + + terrainTile.terrain.terrainData.UpdateDirtyRegion(terrainTile.clippedLocal.x, terrainTile.clippedLocal.y, terrainTile.clippedLocal.width, terrainTile.clippedLocal.height, !terrainTile.terrain.drawInstanced); + OnTerrainPainted(terrainTile, ToolAction.PaintHeightmap); + } + } + + public void GatherNormals() + { + RenderTexture rt = originTerrain.normalmapTexture; + + Material blitMaterial = TerrainPaintUtility.GetBlitMaterial(); + + RenderTexture.active = sourceRenderTexture; + GL.Clear(false, true, new Color(0.5f, 0.5f, 0.5f, 0.5f)); + + for (int i = 0; i < m_TerrainTiles.Count; i++) + { + TerrainTile terrainTile = m_TerrainTiles[i]; + if (terrainTile.clippedLocal.width == 0 || terrainTile.clippedLocal.height == 0) + continue; + + Texture sourceTexture = terrainTile.terrain.normalmapTexture; + if ((sourceTexture.width != targetTextureWidth) || (sourceTexture.height != targetTextureHeight)) + { + Debug.LogWarning("PaintContext normalmap operations must use the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); + continue; + } + + Rect readRect = new Rect( + (terrainTile.clippedLocal.x + terrainTile.readOffset.x) / (float)targetTextureWidth, + (terrainTile.clippedLocal.y + terrainTile.readOffset.y) / (float)targetTextureHeight, + (terrainTile.clippedLocal.width) / (float)targetTextureWidth, + (terrainTile.clippedLocal.height) / (float)targetTextureHeight); + + FilterMode oldFilterMode = sourceTexture.filterMode; + + sourceTexture.filterMode = FilterMode.Point; + + blitMaterial.SetTexture("_MainTex", sourceTexture); + blitMaterial.SetPass(0); + + TerrainPaintUtility.DrawQuad(pixelRect.width, pixelRect.height, readRect, terrainTile.validPaintRect); + + sourceTexture.filterMode = oldFilterMode; + } + + RenderTexture.active = oldRenderTexture; + } + + public void GatherAlphamap(TerrainLayer inputLayer, bool addLayerIfDoesntExist = true) + { + 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)); + + Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; + + Material copyTerrainLayerMaterial = TerrainPaintUtility.GetCopyTerrainLayerMaterial(); + for (int i = 0; i < m_TerrainTiles.Count; i++) + { + TerrainTile terrainTile = m_TerrainTiles[i]; + if (terrainTile.clippedLocal.width == 0 || terrainTile.clippedLocal.height == 0) + continue; + + Rect readRect = new Rect( + (terrainTile.clippedLocal.x + terrainTile.readOffset.x) / (float)targetTextureWidth, + (terrainTile.clippedLocal.y + terrainTile.readOffset.y) / (float)targetTextureHeight, + (terrainTile.clippedLocal.width) / (float)targetTextureWidth, + (terrainTile.clippedLocal.height) / (float)targetTextureHeight); + + int tileLayerIndex = TerrainPaintUtility.FindTerrainLayerIndex(terrainTile.terrain, inputLayer); + if (tileLayerIndex == -1) + { + if (!addLayerIfDoesntExist) + { + // setting these to zero will prevent them from being used later + terrainTile.clippedLocal.width = 0; + terrainTile.clippedLocal.height = 0; + terrainTile.validPaintRect.width = 0; + terrainTile.validPaintRect.height = 0; + continue; + } + tileLayerIndex = TerrainPaintUtility.AddTerrainLayer(terrainTile.terrain, inputLayer); + } + + terrainTile.mapIndex = tileLayerIndex >> 2; + terrainTile.channelIndex = tileLayerIndex & 0x3; + + Texture sourceTexture = TerrainPaintUtility.GetTerrainAlphaMapChecked(terrainTile.terrain, terrainTile.mapIndex); + if ((sourceTexture.width != targetTextureWidth) || (sourceTexture.height != targetTextureHeight)) + { + Debug.LogWarning("PaintContext alphamap operations must use the same resolution for all Terrains - mismatched Terrains are ignored.", terrainTile.terrain); + continue; + } + + FilterMode oldFilterMode = sourceTexture.filterMode; + sourceTexture.filterMode = FilterMode.Point; + + copyTerrainLayerMaterial.SetVector("_LayerMask", layerMasks[terrainTile.channelIndex]); + copyTerrainLayerMaterial.SetTexture("_MainTex", sourceTexture); + copyTerrainLayerMaterial.SetPass(0); + + TerrainPaintUtility.DrawQuad(pixelRect.width, pixelRect.height, readRect, terrainTile.validPaintRect); + + sourceTexture.filterMode = oldFilterMode; + } + + RenderTexture.active = oldRenderTexture; + } + + public void ScatterAlphamap(string editorUndoName) + { + Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; + + Material copyTerrainLayerMaterial = TerrainPaintUtility.GetCopyTerrainLayerMaterial(); + + for (int i = 0; i < m_TerrainTiles.Count; i++) + { + TerrainTile terrainTile = m_TerrainTiles[i]; + if (terrainTile.clippedLocal.width == 0 || terrainTile.clippedLocal.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; + + var writeRect = new RectInt( + terrainTile.clippedLocal.x + terrainTile.rect.x - pixelRect.x + terrainTile.writeOffset.x, + terrainTile.clippedLocal.y + terrainTile.rect.y - pixelRect.y + terrainTile.writeOffset.y, + terrainTile.clippedLocal.width, + terrainTile.clippedLocal.height); + + var readRect = new Rect( + writeRect.x / (float)pixelRect.width, + writeRect.y / (float)pixelRect.height, + writeRect.width / (float)pixelRect.width, + writeRect.height / (float)pixelRect.height); + + destinationRenderTexture.filterMode = FilterMode.Point; + + for (int j = 0; j < terrainTile.terrain.terrainData.alphamapTextureCount; j++) + { + Texture2D sourceTex = terrainTile.terrain.terrainData.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); + continue; + } + + int mapIndex = terrainTile.mapIndex; + int channelIndex = terrainTile.channelIndex; + + Rect combineRect = new Rect( + terrainTile.clippedLocal.x / (float)sourceTex.width, + terrainTile.clippedLocal.y / (float)sourceTex.height, + terrainTile.clippedLocal.width / (float)sourceTex.width, + terrainTile.clippedLocal.height / (float)sourceTex.height); + + copyTerrainLayerMaterial.SetTexture("_MainTex", destinationRenderTexture); + copyTerrainLayerMaterial.SetTexture("_OldAlphaMapTexture", sourceRenderTexture); + copyTerrainLayerMaterial.SetTexture("_AlphaMapTexture", sourceTex); + copyTerrainLayerMaterial.SetVector("_LayerMask", j == mapIndex ? layerMasks[channelIndex] : Vector4.zero); + copyTerrainLayerMaterial.SetPass(1); + + GL.PushMatrix(); + GL.LoadOrtho(); + GL.LoadPixelMatrix(0, destTarget.width, 0, destTarget.height); + + GL.Begin(GL.QUADS); + GL.Color(new Color(1.0f, 1.0f, 1.0f, 1.0f)); + + GL.MultiTexCoord2(0, readRect.x, readRect.y); + GL.MultiTexCoord2(1, combineRect.x, combineRect.y); + GL.Vertex3(writeRect.x, writeRect.y, 0.0f); + GL.MultiTexCoord2(0, readRect.x, readRect.yMax); + GL.MultiTexCoord2(1, combineRect.x, combineRect.yMax); + GL.Vertex3(writeRect.x, writeRect.yMax, 0.0f); + GL.MultiTexCoord2(0, readRect.xMax, readRect.yMax); + GL.MultiTexCoord2(1, combineRect.xMax, combineRect.yMax); + GL.Vertex3(writeRect.xMax, writeRect.yMax, 0.0f); + GL.MultiTexCoord2(0, readRect.xMax, readRect.y); + GL.MultiTexCoord2(1, combineRect.xMax, combineRect.y); + GL.Vertex3(writeRect.xMax, writeRect.y, 0.0f); + + 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.clippedLocal.x, terrainTile.clippedLocal.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.clippedLocal.x, terrainTile.clippedLocal.y); + else + sourceTex.ReadPixels(new Rect(writeRect.x, destTarget.height - writeRect.y - writeRect.height, writeRect.width, writeRect.height), terrainTile.clippedLocal.x, terrainTile.clippedLocal.y); + sourceTex.Apply(); + } + } + + RenderTexture.active = null; + RenderTexture.ReleaseTemporary(destTarget); + + OnTerrainPainted(terrainTile, ToolAction.PaintTexture); + } + } + + // Collects modified terrain so that we can update some deferred operations at the mouse up event + private class PaintedTerrain + { + public Terrain terrain; + public ToolAction action; + }; + private static List s_PaintedTerrain = new List(); + + private static void OnTerrainPainted(PaintContext.TerrainTile tile, ToolAction action) + { + for (int i = 0; i < s_PaintedTerrain.Count; ++i) + { + if (tile.terrain == s_PaintedTerrain[i].terrain) + { + s_PaintedTerrain[i].action |= action; + return; + } + } + s_PaintedTerrain.Add(new PaintedTerrain { terrain = tile.terrain, action = action }); + } + + public static void ApplyDelayedActions() + { + for (int i = 0; i < s_PaintedTerrain.Count; ++i) + { + var pt = s_PaintedTerrain[i]; + if ((pt.action & ToolAction.PaintHeightmap) != 0) + { + pt.terrain.ApplyDelayedHeightmapModification(); + } + 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); + } + } + } + + s_PaintedTerrain.Clear(); + } + } +} diff --git a/Modules/Terrain/Public/TerrainPaintUtility.cs b/Modules/Terrain/Public/TerrainPaintUtility.cs index 2089699697..a2d752a116 100644 --- a/Modules/Terrain/Public/TerrainPaintUtility.cs +++ b/Modules/Terrain/Public/TerrainPaintUtility.cs @@ -27,390 +27,96 @@ public static Material GetBuiltinPaintMaterial() return s_BuiltinPaintMaterial; } - public class TerrainTile + // returns a transform from terrain space to brush UV + public static BrushTransform CalculateBrushTransform( + Terrain terrain, Vector2 brushCenterTerrainUV, float brushSize, float brushRotationDegrees) { - public TerrainTile() { terrain = null; } - public TerrainTile(Terrain newTerrain, RectInt newRegion) { rect = newRegion; terrain = newTerrain; } - public Terrain terrain; - public RectInt rect; // pixel coordinates of this terrain tile in the paint context (a locally built space relative to the active 'center' tile) + float rotationRadians = brushRotationDegrees * Mathf.Deg2Rad; + float cos = Mathf.Cos(rotationRadians); + float sin = Mathf.Sin(rotationRadians); + Vector2 brushU = new Vector2(cos, -sin) * brushSize; + Vector2 brushV = new Vector2(sin, cos) * brushSize; - public int mapIndex; - public int channelIndex; + // calculate brush origin + Vector3 terrainSize = terrain.terrainData.size; + Vector2 brushCenterTerrainSpace = brushCenterTerrainUV * new Vector2(terrainSize.x, terrainSize.z); + Vector2 brushOrigin = brushCenterTerrainSpace - 0.5f * brushU - 0.5f * brushV; - // offsets used for gather / scatter - public Vector2Int readOffset; // offsets used when reading from the terrain heightmap - public Vector2Int writeOffset; // offsets used when copying from PaintContext clipped heightmap back to the terrain heightmap + BrushTransform xform = new BrushTransform(brushOrigin, brushU, brushV); + return xform; } - public class PaintContext + public static void BuildTransformPaintContextUVToPaintContextUV(PaintContext src, PaintContext dst, out Vector4 scaleOffset) { - public RectInt brushRect; // the rectangle represented by this paint context, in target texture pixels (for the active terrain tile) - public TerrainTile[] terrainTiles; // all terrain tiles touched by this paint context - public RectInt[] clippedTiles; // the intersection of brushRect with each of the terrain tiles above, clipped into local tile pixels - public Rect[] validPaintRects; // the area per tile where the source texture was able to read from - - public RenderTexture sourceRenderTexture; - public RenderTexture destinationRenderTexture; - - public RenderTexture oldRenderTexture; // active render texture before PaintContext was initialized - - - public void CalculateBrushRect(Terrain terrain, Rect bounds, int inputTextureWidth, int inputTextureHeight) - { - brushRect = CalcBrushRectInPixels(terrain, bounds, inputTextureWidth, inputTextureHeight); - } - - public void CreateTerrainTiles(Terrain terrain, int inputTextureWidth, int inputTextureHeight) - { - terrainTiles = FindTerrainTiles(terrain, inputTextureWidth, inputTextureHeight, brushRect); - clippedTiles = ClipTerrainTiles(terrainTiles, brushRect); - validPaintRects = new Rect[terrainTiles.Length]; - - for (int i = 0; i < terrainTiles.Length; ++i) - { - TerrainTile terrainTile = terrainTiles[i]; - validPaintRects[i] = new Rect( - clippedTiles[i].x + terrainTile.rect.x - brushRect.x, - clippedTiles[i].y + terrainTile.rect.y - brushRect.y, - clippedTiles[i].width, - clippedTiles[i].height); - } - } - - public void CreateRenderTargets(RenderTextureFormat colorFormat) - { - sourceRenderTexture = RenderTexture.GetTemporary(brushRect.width, brushRect.height, 0, colorFormat, RenderTextureReadWrite.Linear); - destinationRenderTexture = RenderTexture.GetTemporary(brushRect.width, brushRect.height, 0, colorFormat, RenderTextureReadWrite.Linear); - sourceRenderTexture.wrapMode = TextureWrapMode.Clamp; - sourceRenderTexture.filterMode = FilterMode.Point; - oldRenderTexture = RenderTexture.active; - } - - public void Cleanup() - { - RenderTexture.active = oldRenderTexture; - RenderTexture.ReleaseTemporary(sourceRenderTexture); - RenderTexture.ReleaseTemporary(destinationRenderTexture); - sourceRenderTexture = null; - destinationRenderTexture = null; - oldRenderTexture = null; - } - - public void GatherHeightmap(Terrain terrain) - { - RenderTexture rt = terrain.terrainData.heightmapTexture; - int heightmapWidth = rt.width; - int heightmapHeight = rt.height; - - Material blitMaterial = GetBlitMaterial(); - - RenderTexture.active = sourceRenderTexture; - - for (int i = 0; i < terrainTiles.Length; i++) - { - if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) - continue; - - TerrainTile terrainTile = terrainTiles[i]; - - Rect readRect = new Rect( - (clippedTiles[i].x + terrainTile.readOffset.x) / (float)heightmapWidth, - (clippedTiles[i].y + terrainTile.readOffset.y) / (float)heightmapHeight, - (clippedTiles[i].width) / (float)heightmapWidth, - (clippedTiles[i].height) / (float)heightmapHeight); - - Texture sourceTexture = terrainTile.terrain.terrainData.heightmapTexture; - FilterMode oldFilterMode = sourceTexture.filterMode; - - sourceTexture.filterMode = FilterMode.Point; - - blitMaterial.SetTexture("_MainTex", sourceTexture); - blitMaterial.SetPass(0); - - DrawQuad(brushRect.width, brushRect.height, readRect, validPaintRects[i]); - - sourceTexture.filterMode = oldFilterMode; - } - - RenderTexture.active = oldRenderTexture; - } - - public void ScatterHeightmap(string editorUndoName) - { - Material blitMaterial = GetBlitMaterial(); - - for (int i = 0; i < terrainTiles.Length; i++) - { - if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) - continue; - - TerrainTile terrainTile = terrainTiles[i]; - - if (onTerrainTileBeforePaint != null) - onTerrainTileBeforePaint(terrainTile, ToolAction.PaintHeightmap, editorUndoName); - - RenderTexture heightmap = terrainTile.terrain.terrainData.heightmapTexture; - RenderTexture.active = heightmap; - - Rect readRect = new Rect( - (clippedTiles[i].x + terrainTile.rect.x - brushRect.x + terrainTile.writeOffset.x) / (float)brushRect.width, - (clippedTiles[i].y + terrainTile.rect.y - brushRect.y + terrainTile.writeOffset.y) / (float)brushRect.height, - (clippedTiles[i].width) / (float)brushRect.width, - (clippedTiles[i].height) / (float)brushRect.height); - - Rect writeRect = new Rect( - clippedTiles[i].x, - clippedTiles[i].y, - clippedTiles[i].width, - clippedTiles[i].height); - - destinationRenderTexture.filterMode = FilterMode.Point; - - blitMaterial.SetTexture("_MainTex", destinationRenderTexture); - blitMaterial.SetPass(0); - - DrawQuad(heightmap.width, heightmap.height, readRect, writeRect); - - terrainTile.terrain.terrainData.UpdateDirtyRegion(clippedTiles[i].x, clippedTiles[i].y, clippedTiles[i].width, clippedTiles[i].height, !terrainTile.terrain.drawInstanced); - OnTerrainPainted(terrainTile, ToolAction.PaintHeightmap); - } - } - - public void GatherNormals(Terrain terrain) - { - RenderTexture rt = terrain.normalmapTexture; - - RenderTextureFormat colorFormat = rt.format; - int heightmapWidth = rt.width; - int heightmapHeight = rt.height; - - Material blitMaterial = GetBlitMaterial(); - - RenderTexture.active = sourceRenderTexture; - - for (int i = 0; i < terrainTiles.Length; i++) - { - if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) - continue; - - TerrainTile terrainTile = terrainTiles[i]; - - Rect readRect = new Rect( - (clippedTiles[i].x + terrainTile.readOffset.x) / (float)heightmapWidth, - (clippedTiles[i].y + terrainTile.readOffset.y) / (float)heightmapHeight, - (clippedTiles[i].width) / (float)heightmapWidth, - (clippedTiles[i].height) / (float)heightmapHeight); - - Texture sourceTexture = terrainTile.terrain.normalmapTexture; - FilterMode oldFilterMode = sourceTexture.filterMode; - - sourceTexture.filterMode = FilterMode.Point; - - blitMaterial.SetTexture("_MainTex", sourceTexture); - blitMaterial.SetPass(0); - - DrawQuad(brushRect.width, brushRect.height, readRect, validPaintRects[i]); - - sourceTexture.filterMode = oldFilterMode; - } - - RenderTexture.active = oldRenderTexture; - } - - public void GatherAlphamap(Terrain terrain, TerrainLayer inputLayer, bool addLayerIfDoesntExist = true) - { - if (inputLayer == null) - return; - - int terrainLayerIndex = FindTerrainLayerIndex(terrain, inputLayer); - if (terrainLayerIndex == -1 && addLayerIfDoesntExist) - terrainLayerIndex = AddTerrainLayer(terrain, inputLayer); - - Texture2D inputTexture = GetTerrainAlphaMapChecked(terrain, terrainLayerIndex >> 2); - - int inputTextureWidth = inputTexture.width; - int inputTextureHeight = inputTexture.height; - - RenderTexture.active = sourceRenderTexture; - - Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; - - Material copyTerrainLayerMaterial = GetCopyTerrainLayerMaterial(); - for (int i = 0; i < terrainTiles.Length; i++) - { - if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) - continue; - - TerrainTile terrainTile = terrainTiles[i]; - - Rect readRect = new Rect( - (clippedTiles[i].x + terrainTile.readOffset.x) / (float)inputTextureWidth, - (clippedTiles[i].y + terrainTile.readOffset.y) / (float)inputTextureHeight, - (clippedTiles[i].width) / (float)inputTextureWidth, - (clippedTiles[i].height) / (float)inputTextureHeight); - - int tileLayerIndex = FindTerrainLayerIndex(terrainTile.terrain, inputLayer); - if (tileLayerIndex == -1) - { - if (!addLayerIfDoesntExist) - { - // setting these to zero will prevent them from being used later - clippedTiles[i].width = 0; - clippedTiles[i].height = 0; - validPaintRects[i].width = 0; - validPaintRects[i].height = 0; - continue; - } - tileLayerIndex = AddTerrainLayer(terrainTile.terrain, inputLayer); - } - - terrainTile.mapIndex = tileLayerIndex >> 2; - terrainTile.channelIndex = tileLayerIndex & 0x3; - - Texture sourceTexture = GetTerrainAlphaMapChecked(terrainTile.terrain, terrainTile.mapIndex); - - FilterMode oldFilterMode = sourceTexture.filterMode; - sourceTexture.filterMode = FilterMode.Point; - - copyTerrainLayerMaterial.SetVector("_LayerMask", layerMasks[terrainTile.channelIndex]); - copyTerrainLayerMaterial.SetTexture("_MainTex", sourceTexture); - copyTerrainLayerMaterial.SetPass(0); - - DrawQuad(brushRect.width, brushRect.height, readRect, validPaintRects[i]); - - sourceTexture.filterMode = oldFilterMode; - } - - RenderTexture.active = oldRenderTexture; - } - - public void ScatterAlphamap(string editorUndoName) - { - Vector4[] layerMasks = { new Vector4(1, 0, 0, 0), new Vector4(0, 1, 0, 0), new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 1) }; - - Material copyTerrainLayerMaterial = GetCopyTerrainLayerMaterial(); - - for (int i = 0; i < terrainTiles.Length; i++) - { - if (clippedTiles[i].width == 0 || clippedTiles[i].height == 0) - continue; - - TerrainTile terrainTile = terrainTiles[i]; - - 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; - - var writeRect = new RectInt( - clippedTiles[i].x + terrainTile.rect.x - brushRect.x + terrainTile.writeOffset.x, - clippedTiles[i].y + terrainTile.rect.y - brushRect.y + terrainTile.writeOffset.y, - clippedTiles[i].width, - clippedTiles[i].height); - - var readRect = new Rect( - writeRect.x / (float)brushRect.width, - writeRect.y / (float)brushRect.height, - writeRect.width / (float)brushRect.width, - writeRect.height / (float)brushRect.height); - - destinationRenderTexture.filterMode = FilterMode.Point; - - for (int j = 0; j < terrainTile.terrain.terrainData.alphamapTextureCount; j++) - { - Texture2D sourceTex = terrainTile.terrain.terrainData.alphamapTextures[j]; - - int mapIndex = terrainTile.mapIndex; - int channelIndex = terrainTile.channelIndex; - - Rect combineRect = new Rect( - clippedTiles[i].x / (float)sourceTex.width, - clippedTiles[i].y / (float)sourceTex.height, - clippedTiles[i].width / (float)sourceTex.width, - clippedTiles[i].height / (float)sourceTex.height); - - copyTerrainLayerMaterial.SetTexture("_MainTex", destinationRenderTexture); - copyTerrainLayerMaterial.SetTexture("_OldAlphaMapTexture", sourceRenderTexture); - copyTerrainLayerMaterial.SetTexture("_AlphaMapTexture", sourceTex); - copyTerrainLayerMaterial.SetVector("_LayerMask", j == mapIndex ? layerMasks[channelIndex] : Vector4.zero); - copyTerrainLayerMaterial.SetPass(1); - - GL.PushMatrix(); - GL.LoadOrtho(); - GL.LoadPixelMatrix(0, destTarget.width, 0, destTarget.height); - - GL.Begin(GL.QUADS); - GL.Color(new Color(1.0f, 1.0f, 1.0f, 1.0f)); - - GL.MultiTexCoord2(0, readRect.x, readRect.y); - GL.MultiTexCoord2(1, combineRect.x, combineRect.y); - GL.Vertex3(writeRect.x, writeRect.y, 0.0f); - GL.MultiTexCoord2(0, readRect.x, readRect.yMax); - GL.MultiTexCoord2(1, combineRect.x, combineRect.yMax); - GL.Vertex3(writeRect.x, writeRect.yMax, 0.0f); - GL.MultiTexCoord2(0, readRect.xMax, readRect.yMax); - GL.MultiTexCoord2(1, combineRect.xMax, combineRect.yMax); - GL.Vertex3(writeRect.xMax, writeRect.yMax, 0.0f); - GL.MultiTexCoord2(0, readRect.xMax, readRect.y); - GL.MultiTexCoord2(1, combineRect.xMax, combineRect.y); - GL.Vertex3(writeRect.xMax, writeRect.y, 0.0f); - - GL.End(); - GL.PopMatrix(); - - if (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, clippedTiles[i].x, clippedTiles[i].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), clippedTiles[i].x, clippedTiles[i].y); - else - sourceTex.ReadPixels(new Rect(writeRect.x, destTarget.height - writeRect.y - writeRect.height, writeRect.width, writeRect.height), clippedTiles[i].x, clippedTiles[i].y); - sourceTex.Apply(); - } - } - - RenderTexture.active = null; - RenderTexture.ReleaseTemporary(destTarget); - - OnTerrainPainted(terrainTile, ToolAction.PaintTexture); - } - } + // for example: + // src = alphaUV + // dst = normalUV + // dst.uv = src.u * scales.xy + src.v * scales.zw + offset + // terrainspace.xz = srcOrigin + src.uv * srcSize + // terrainspace.xz = dstOrigin + dst.uv * dstSize + // dstOrigin + dst.uv * dstSize = srcOrigin + src.uv * srcSize + // dst.uv * dstSize = src.uv * srcSize + srcOrigin - dstOrigin + // dst.uv = (src.uv * srcSize + srcOrigin - dstOrigin) / dstSize + // dst.uv = (src.uv * srcSize) / dstSize + (srcOrigin - dstOrigin) / dstSize + // scales.x = srcSize.x / dstSize.x + // scales.yz = 0.0f; + // scales.w = srcSize.y / dstSize.y + // offset.xy = (srcOrigin.xy - dstOrigin.xy) / dstSize.xy + + // paint context origin in terrain space + // (note this is the UV space origin and size, not the mesh origin & size) + float srcOriginX = (src.pixelRect.xMin - 0.5f) * src.pixelSize.x; + float srcOriginZ = (src.pixelRect.yMin - 0.5f) * src.pixelSize.y; + float srcSizeX = (src.pixelRect.width) * src.pixelSize.x; + float srcSizeZ = (src.pixelRect.height) * src.pixelSize.y; + + // paint context origin in terrain space + // (note this is the UV space origin and size, not the mesh origin & size) + float dstOriginX = (dst.pixelRect.xMin - 0.5f) * dst.pixelSize.x; + float dstOriginZ = (dst.pixelRect.yMin - 0.5f) * dst.pixelSize.y; + float dstSizeX = (dst.pixelRect.width) * dst.pixelSize.x; + float dstSizeZ = (dst.pixelRect.height) * dst.pixelSize.y; + + scaleOffset = new Vector4( + srcSizeX / dstSizeX, + srcSizeZ / dstSizeZ, + (srcOriginX - dstOriginX) / dstSizeX, + (srcOriginZ - dstOriginZ) / dstSizeZ + ); } - [Flags] - public enum ToolAction + // this function sets up material properties used by functions provided in TerrainTool.cginc + public static void SetupTerrainToolMaterialProperties( + PaintContext paintContext, + BrushTransform brushXform, // the brush transform to terrain space (of paintContext.originTerrain) + Material material) { - None = 0, - PaintHeightmap = 1 << 0, - PaintTexture = 1 << 1, + // BrushUV = f(terrainSpace.xz) = f(g(pc.uv)) + // f(ts.xy) = ts.x * brushXform.X + ts.y * brushXform.Y + brushXform.Origin + // g(pc.uv) = ts.xz = pcOrigin + pc.uv * pcSize + // f(g(pc.uv)) == (pcOrigin + pc.uv * pcSize).x * brushXform.X + (pcOrigin + pc.uv * pcSize).y * brushXform.Y + brushXform.Origin + // f(g(pc.uv)) == (pcOrigin.x + pc.u * pcSize.x) * brushXform.X + (pcOrigin.y + pc.v * pcSize.y) * brushXform.Y + brushXform.Origin + // f(g(pc.uv)) == (pcOrigin.x * brushXform.X) + (pc.u * pcSize.x) * brushXform.X + (pcOrigin.y * brushXform.Y) + (pc.v * pcSize.y) * brushXform.Y + brushXform.Origin + // f(g(pc.uv)) == pc.u * (pcSize.x * brushXform.X) + pc.v * (pcSize.y * brushXform.Y) + (brushXform.Origin + (pcOrigin.x * brushXform.X) + (pcOrigin.y * brushXform.Y)) + + // pcOrigin = (pc.pixelRect.xyMin - 0.5) * pc.pixelSize.xy + // pcSize = (pc.pixelRect.wh) * pc.pixelSize.xy + + // paint context origin in terrain space + // (note this is the UV space origin and size, not the mesh origin & size) + float pcOriginX = (paintContext.pixelRect.xMin - 0.5f) * paintContext.pixelSize.x; + float pcOriginZ = (paintContext.pixelRect.yMin - 0.5f) * paintContext.pixelSize.y; + float pcSizeX = (paintContext.pixelRect.width) * paintContext.pixelSize.x; + float pcSizeZ = (paintContext.pixelRect.height) * paintContext.pixelSize.y; + + Vector2 scaleU = pcSizeX * brushXform.targetX; + Vector2 scaleV = pcSizeZ * brushXform.targetY; + Vector2 offset = brushXform.targetOrigin + pcOriginX * brushXform.targetX + pcOriginZ * brushXform.targetY; + material.SetVector("_PCUVToBrushUVScales", new Vector4(scaleU.x, scaleU.y, scaleV.x, scaleV.y)); + material.SetVector("_PCUVToBrushUVOffset", new Vector4(offset.x, offset.y, 0.0f, 0.0f)); } - private static bool paintTextureUsesCopyTexture + internal static bool paintTextureUsesCopyTexture { get { @@ -419,12 +125,10 @@ private static bool paintTextureUsesCopyTexture } } - static PaintContext InitializePaintContext(Terrain terrain, Rect bounds, int inputTextureWidth, int inputTextureHeight, RenderTextureFormat colorFormat) + static PaintContext InitializePaintContext(Terrain terrain, Texture target, RenderTextureFormat pcFormat, Rect boundsInTerrainSpace, int extraBorderPixels = 0) { - PaintContext ctx = new PaintContext(); - ctx.CalculateBrushRect(terrain, bounds, inputTextureWidth, inputTextureHeight); - ctx.CreateTerrainTiles(terrain, inputTextureWidth, inputTextureHeight); - ctx.CreateRenderTargets(colorFormat); + PaintContext ctx = PaintContext.CreateFromBounds(terrain, boundsInTerrainSpace, target.width, target.height, extraBorderPixels); + ctx.CreateRenderTargets(pcFormat); return ctx; } @@ -433,77 +137,11 @@ public static void ReleaseContextResources(PaintContext ctx) ctx.Cleanup(); } - public static Rect CalculateBrushRectInTerrainUnits(Terrain terrain, Vector2 uv, float brushSize) - { - Vector3 terrainSize = terrain.terrainData.size; - return new Rect(uv * new Vector2(terrainSize.x, terrainSize.z) - Vector2.one * brushSize * 0.5f, Vector2.one * brushSize); - } - - // Collects modified terrain so that we can update some deferred operations at the mouse up event - private class PaintedTerrain - { - public Terrain terrain; - public ToolAction action; - }; - private static List s_PaintedTerrain = new List(); - - private static void OnTerrainPainted(TerrainTile tile, ToolAction action) - { - for (int i = 0; i < s_PaintedTerrain.Count; ++i) - { - if (tile.terrain == s_PaintedTerrain[i].terrain) - { - s_PaintedTerrain[i].action |= action; - return; - } - } - s_PaintedTerrain.Add(new PaintedTerrain { terrain = tile.terrain, action = action }); - } - - public static void FlushAllPaints() - { - for (int i = 0; i < s_PaintedTerrain.Count; ++i) - { - var pt = s_PaintedTerrain[i]; - if ((pt.action & ToolAction.PaintHeightmap) != 0) - { - pt.terrain.ApplyDelayedHeightmapModification(); - } - if ((pt.action & ToolAction.PaintTexture) != 0) - { - var terrainData = pt.terrain.terrainData; - if (terrainData == null) - continue; - terrainData.SetBaseMapDirty(); - if (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); - } - } - } - - s_PaintedTerrain.Clear(); - } - - // TerrainPaintUtilityEditor hooks to this event to do automatic undo - internal static event Action onTerrainTileBeforePaint; - - public static PaintContext BeginPaintHeightmap(Terrain terrain, Rect bounds) // bounds in terrain space units + public static PaintContext BeginPaintHeightmap(Terrain terrain, Rect boundsInTerrainSpace, int extraBorderPixels = 0) { RenderTexture rt = terrain.terrainData.heightmapTexture; - PaintContext ctx = InitializePaintContext(terrain, bounds, rt.width, rt.height, rt.format); - ctx.GatherHeightmap(terrain); + PaintContext ctx = InitializePaintContext(terrain, rt, rt.format, boundsInTerrainSpace, extraBorderPixels); + ctx.GatherHeightmap(); return ctx; } @@ -513,15 +151,15 @@ public static void EndPaintHeightmap(PaintContext ctx, string editorUndoName) ctx.Cleanup(); } - public static PaintContext CollectNormals(Terrain terrain, Rect bounds) + public static PaintContext CollectNormals(Terrain terrain, Rect boundsInTerrainSpace, int extraBorderPixels = 0) { RenderTexture rt = terrain.normalmapTexture; - PaintContext ctx = InitializePaintContext(terrain, bounds, rt.width, rt.height, rt.format); - ctx.GatherNormals(terrain); + PaintContext ctx = InitializePaintContext(terrain, rt, rt.format, boundsInTerrainSpace, extraBorderPixels); + ctx.GatherNormals(); return ctx; } - public static PaintContext BeginPaintTexture(Terrain terrain, Rect bounds, TerrainLayer inputLayer) + public static PaintContext BeginPaintTexture(Terrain terrain, Rect boundsInTerrainSpace, TerrainLayer inputLayer, int extraBorderPixels = 0) { if (inputLayer == null) return null; @@ -532,8 +170,8 @@ public static PaintContext BeginPaintTexture(Terrain terrain, Rect bounds, Terra Texture2D inputTexture = GetTerrainAlphaMapChecked(terrain, terrainLayerIndex >> 2); - PaintContext ctx = InitializePaintContext(terrain, bounds, inputTexture.width, inputTexture.height, RenderTextureFormat.R8); - ctx.GatherAlphamap(terrain, inputLayer); + PaintContext ctx = InitializePaintContext(terrain, inputTexture, RenderTextureFormat.R8, boundsInTerrainSpace, extraBorderPixels); + ctx.GatherAlphamap(inputLayer); return ctx; } @@ -560,7 +198,7 @@ public static Material GetCopyTerrainLayerMaterial() return m_CopyTerrainLayerMaterial; } - static void DrawQuad(int width, int height, Rect source, Rect destination) + internal static void DrawQuad(int width, int height, Rect source, Rect destination) { GL.PushMatrix(); GL.LoadOrtho(); @@ -582,139 +220,15 @@ static void DrawQuad(int width, int height, Rect source, Rect destination) GL.PopMatrix(); } - public static RectInt CalcBrushRectInPixels(Terrain terrain, Rect brushRect, int textureWidth, int textureHeight) - { - int xMin = Mathf.FloorToInt(((float)textureWidth) * brushRect.xMin / terrain.terrainData.size.x); - int yMin = Mathf.FloorToInt(((float)textureHeight) * brushRect.yMin / terrain.terrainData.size.z); - int xMax = Mathf.CeilToInt(((float)textureWidth) * brushRect.xMax / terrain.terrainData.size.x); - int yMax = Mathf.CeilToInt(((float)textureHeight) * brushRect.yMax / terrain.terrainData.size.z); - return new RectInt(xMin, yMin, xMax - xMin, yMax - yMin); - } - - public static TerrainTile[] FindTerrainTiles(Terrain terrain, int width, int height, RectInt brushRect) + internal static RectInt CalcPixelRectFromBounds(Terrain terrain, Rect boundsInTerrainSpace, int textureWidth, int textureHeight, int extraBorderPixels) { - List terrainTiles = new List(); - - Terrain left = terrain.leftNeighbor; - Terrain right = terrain.rightNeighbor; - Terrain top = terrain.topNeighbor; - Terrain bottom = terrain.bottomNeighbor; - - bool wantLeft = (brushRect.x < 0); - bool wantRight = (brushRect.xMax > (width - 1)); - bool wantTop = (brushRect.yMax > (height - 1)); - bool wantBottom = (brushRect.y < 0); - - if (wantLeft && wantRight) - { - Debug.Log("FindTerrainTiles query rectangle too large!"); - wantRight = false; - } - - if (wantTop && wantBottom) - { - Debug.Log("FindTerrainTiles query rectangle too large!"); - wantBottom = false; - } - - // add center tile - TerrainTile tile = new TerrainTile(terrain, new RectInt(0, 0, width, height)); - tile.readOffset = Vector2Int.zero; - tile.writeOffset = Vector2Int.zero; - terrainTiles.Add(tile); - - // add horizontal and vertical neighbors - Terrain horiz = null; - Terrain vert = null; - Terrain cornerTerrain = null; - - int xBias = 0; - int yBias = 0; - int xReadBias = 0; - int yReadBias = 0; - int xWriteBias = 0; - int yWriteBias = 0; - - if (wantLeft) - { - xBias = -1; - xReadBias = -1; - xWriteBias = 1; - horiz = left; - } - else if (wantRight) - { - xBias = 1; - xReadBias = 1; - xWriteBias = -1; - horiz = right; - } - - if (wantTop) - { - yBias = 1; - yReadBias = 1; - yWriteBias = -1; - vert = top; - } - else if (wantBottom) - { - yBias = -1; - yReadBias = -1; - yWriteBias = 1; - vert = bottom; - } - - if (horiz) - { - tile = new TerrainTile(horiz, new RectInt(xBias * width, 0, width, height)); - tile.readOffset = new Vector2Int(xReadBias, 0); - tile.writeOffset = new Vector2Int(xWriteBias, 0); - terrainTiles.Add(tile); - - // add corner, if we have a link - if (wantTop && horiz.topNeighbor) - cornerTerrain = horiz.topNeighbor; - else if (wantBottom && horiz.bottomNeighbor) - cornerTerrain = horiz.bottomNeighbor; - } - - if (vert) - { - tile = new TerrainTile(vert, new RectInt(0, yBias * height, width, height)); - tile.readOffset = new Vector2Int(0, yReadBias); - tile.writeOffset = new Vector2Int(0, yWriteBias); - terrainTiles.Add(tile); - - // add corner, if we have a link - if (wantLeft && vert.leftNeighbor) - cornerTerrain = vert.leftNeighbor; - else if (wantRight && vert.rightNeighbor) - cornerTerrain = vert.rightNeighbor; - } - - if (cornerTerrain != null) - { - tile = new TerrainTile(cornerTerrain, new RectInt(xBias * width, yBias * height, width, height)); - tile.readOffset = new Vector2Int(xReadBias, yReadBias); - tile.writeOffset = new Vector2Int(xWriteBias, yWriteBias); - terrainTiles.Add(tile); - } - - return terrainTiles.ToArray(); - } - - public static RectInt[] ClipTerrainTiles(TerrainTile[] terrainTiles, RectInt brushRect) - { - RectInt[] clippedTiles = new RectInt[terrainTiles.Length]; - for (int i = 0; i < terrainTiles.Length; i++) - { - clippedTiles[i].x = Mathf.Max(0, brushRect.x - terrainTiles[i].rect.x); - clippedTiles[i].y = Mathf.Max(0, brushRect.y - terrainTiles[i].rect.y); - clippedTiles[i].xMax = Mathf.Min(terrainTiles[i].rect.width, brushRect.xMax - terrainTiles[i].rect.x); - clippedTiles[i].yMax = Mathf.Min(terrainTiles[i].rect.height, brushRect.yMax - terrainTiles[i].rect.y); - } - return clippedTiles; + float scaleX = (textureWidth - 1.0f) / terrain.terrainData.size.x; + float scaleY = (textureHeight - 1.0f) / terrain.terrainData.size.z; + int xMin = Mathf.FloorToInt(boundsInTerrainSpace.xMin * scaleX) - extraBorderPixels; + int yMin = Mathf.FloorToInt(boundsInTerrainSpace.yMin * scaleY) - extraBorderPixels; + int xMax = Mathf.CeilToInt(boundsInTerrainSpace.xMax * scaleX) + extraBorderPixels; + int yMax = Mathf.CeilToInt(boundsInTerrainSpace.yMax * scaleY) + extraBorderPixels; + return new RectInt(xMin, yMin, xMax - xMin + 1, yMax - yMin + 1); } // Alphamap utilities @@ -736,7 +250,7 @@ static public int FindTerrainLayerIndex(Terrain terrain, TerrainLayer inputLayer return -1; } - static int AddTerrainLayer(Terrain terrain, TerrainLayer inputLayer) + internal static int AddTerrainLayer(Terrain terrain, TerrainLayer inputLayer) { int newIndex = terrain.terrainData.terrainLayers.Length; var newarray = new TerrainLayer[newIndex + 1]; diff --git a/Modules/TerrainEditor/Brush/Brush.cs b/Modules/TerrainEditor/Brush/Brush.cs index 8453538495..a300ec29ac 100644 --- a/Modules/TerrainEditor/Brush/Brush.cs +++ b/Modules/TerrainEditor/Brush/Brush.cs @@ -99,7 +99,7 @@ internal static Texture2D GenerateBrushTexture(Texture2D mask, AnimationCurve fa s_CreateBrushMaterial = new Material(EditorGUIUtility.LoadRequired("Brushes/CreateBrush.shader") as Shader); int sampleCount = Mathf.Max(width, 1024); - Texture2D falloffTex = new Texture2D(sampleCount, 1, TextureFormat.R8, false); + Texture2D falloffTex = new Texture2D(sampleCount, 1, TextureFormat.R16, false); Color[] falloffPix = new Color[sampleCount]; for (int i = 0; i < sampleCount; i++) { diff --git a/Modules/TerrainEditor/Brush/BrushList.cs b/Modules/TerrainEditor/Brush/BrushList.cs index 7e199ba0ed..553ef2891d 100644 --- a/Modules/TerrainEditor/Brush/BrushList.cs +++ b/Modules/TerrainEditor/Brush/BrushList.cs @@ -97,6 +97,11 @@ public void UpdateSelection(int newSelectedBrush) m_BrushEditor = Editor.CreateEditor(GetActiveBrush()); } + public Brush GetCircleBrush() + { + return m_BrushList[0]; + } + public Brush GetActiveBrush() { if (m_SelectedBrush >= m_BrushList.Length) diff --git a/Modules/TerrainEditor/PaintTools/PaintHeightTool.cs b/Modules/TerrainEditor/PaintTools/PaintHeightTool.cs index eef201b7d3..3770163db0 100644 --- a/Modules/TerrainEditor/PaintTools/PaintHeightTool.cs +++ b/Modules/TerrainEditor/PaintTools/PaintHeightTool.cs @@ -25,25 +25,56 @@ public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext editContext.ShowBrushesGUI(5); } - public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) + private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform) { - TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, editContext.brushTexture, editContext.brushStrength * 0.01f, editContext.brushSize, editContext.brushStrength * 0.01f); + Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); + + brushStrength = Event.current.shift ? -brushStrength : brushStrength; + Vector4 brushParams = new Vector4(0.01f * brushStrength, 0.0f, 0.0f, 0.0f); + mat.SetTexture("_BrushTex", brushTexture); + mat.SetVector("_BrushParams", brushParams); + + TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); + + Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.RaiseLowerHeight); } - public override bool OnPaint(Terrain terrain, IOnPaint editContext) + public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { - float brushStrength = Event.current.shift ? -editContext.brushStrength : editContext.brushStrength; + // We're only doing painting operations, early out if it's not a repaint + if (Event.current.type != EventType.Repaint) + return; - Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); - Rect brushRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(terrain, editContext.uv, editContext.brushSize); - TerrainPaintUtility.PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushRect); + if (editContext.hitValidTerrain) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); - // apply brush - Vector4 brushParams = new Vector4(brushStrength * 0.01f, 0.0f, 0.0f, 0.0f); - mat.SetTexture("_BrushTex", editContext.brushTexture); - mat.SetVector("_BrushParams", brushParams); - Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.RaiseLowerHeight); + Material material = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(); + TerrainPaintUtilityEditor.DrawBrushPreview( + paintContext, TerrainPaintUtilityEditor.BrushPreview.SourceRenderTexture, editContext.brushTexture, brushXform, material, 0); + + // draw result preview + { + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); + + // restore old render target + RenderTexture.active = paintContext.oldRenderTexture; + + material.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture); + TerrainPaintUtilityEditor.DrawBrushPreview( + paintContext, TerrainPaintUtilityEditor.BrushPreview.DestinationRenderTexture, editContext.brushTexture, brushXform, material, 1); + } + TerrainPaintUtility.ReleaseContextResources(paintContext); + } + } + + public override bool OnPaint(Terrain terrain, IOnPaint editContext) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds()); + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Raise or Lower Height"); return true; } diff --git a/Modules/TerrainEditor/PaintTools/PaintTextureTool.cs b/Modules/TerrainEditor/PaintTools/PaintTextureTool.cs index 827487c55e..0fae39fd1a 100644 --- a/Modules/TerrainEditor/PaintTools/PaintTextureTool.cs +++ b/Modules/TerrainEditor/PaintTools/PaintTextureTool.cs @@ -24,6 +24,7 @@ public class PaintTextureTool : TerrainPaintTool [SerializeField] float m_SplatAlpha = 1.0f; + public override string GetName() { return "Paint Texture"; @@ -36,17 +37,20 @@ public override string GetDesc() public override bool OnPaint(Terrain terrain, IOnPaint editContext) { - Rect brushRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(terrain, editContext.uv, editContext.brushSize); - - TerrainPaintUtility.PaintContext paintContext = TerrainPaintUtility.BeginPaintTexture(terrain, brushRect, m_SelectedTerrainLayer); + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintTexture(terrain, brushXform.GetBrushXYBounds(), m_SelectedTerrainLayer); if (paintContext == null) return false; Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); + // apply brush Vector4 brushParams = new Vector4(editContext.brushStrength, m_SplatAlpha, 0.0f, 0.0f); mat.SetTexture("_BrushTex", editContext.brushTexture); mat.SetVector("_BrushParams", brushParams); + + TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); + Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.PaintTexture); TerrainPaintUtility.EndPaintTexture(paintContext, "Terrain Paint - Texture"); @@ -55,7 +59,17 @@ public override bool OnPaint(Terrain terrain, IOnPaint editContext) public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { - TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, editContext.brushTexture, editContext.brushStrength, editContext.brushSize, 0.0f); + // We're only doing painting operations, early out if it's not a repaint + if (Event.current.type != EventType.Repaint) + return; + + if (editContext.hitValidTerrain) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f); + PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); + TerrainPaintUtilityEditor.DrawBrushPreview(ctx, TerrainPaintUtilityEditor.BrushPreview.SourceRenderTexture, editContext.brushTexture, brushXform, TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(), 0); + TerrainPaintUtility.ReleaseContextResources(ctx); + } } private void DrawFoldoutEditor(Editor editor, int controlId, ref bool visible) diff --git a/Modules/TerrainEditor/PaintTools/SetHeightTool.cs b/Modules/TerrainEditor/PaintTools/SetHeightTool.cs index a2d3999f35..2d3087b176 100644 --- a/Modules/TerrainEditor/PaintTools/SetHeightTool.cs +++ b/Modules/TerrainEditor/PaintTools/SetHeightTool.cs @@ -29,7 +29,48 @@ public override string GetDesc() public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { - TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, editContext.brushTexture, editContext.brushStrength * 0.01f, editContext.brushSize, 0); + // We're only doing painting operations, early out if it's not a repaint + if (Event.current.type != EventType.Repaint) + return; + + if (editContext.hitValidTerrain) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); + + Material material = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(); + + TerrainPaintUtilityEditor.DrawBrushPreview( + paintContext, TerrainPaintUtilityEditor.BrushPreview.SourceRenderTexture, editContext.brushTexture, brushXform, material, 0); + + // draw result preview + { + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); + + // restore old render target + RenderTexture.active = paintContext.oldRenderTexture; + + material.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture); + + TerrainPaintUtilityEditor.DrawBrushPreview( + paintContext, TerrainPaintUtilityEditor.BrushPreview.DestinationRenderTexture, editContext.brushTexture, brushXform, material, 1); + } + + TerrainPaintUtility.ReleaseContextResources(paintContext); + } + } + + private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform) + { + Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); + + Vector4 brushParams = new Vector4(brushStrength * 0.01f, 0.5f * m_Height, 0.0f, 0.0f); + mat.SetTexture("_BrushTex", brushTexture); + mat.SetVector("_BrushParams", brushParams); + + TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); + + Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.SetHeights); } public override bool OnPaint(Terrain terrain, IOnPaint editContext) @@ -40,17 +81,10 @@ public override bool OnPaint(Terrain terrain, IOnPaint editContext) editContext.RepaintAllInspectors(); return true; } - Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); - - Rect brushRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(terrain, editContext.uv, editContext.brushSize); - TerrainPaintUtility.PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushRect); - - Vector4 brushParams = new Vector4(editContext.brushStrength * 0.01f, 0.5f * m_Height, 0.0f, 0.0f); - mat.SetTexture("_BrushTex", editContext.brushTexture); - mat.SetVector("_BrushParams", brushParams); - - Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.SetHeights); + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds()); + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Set Height"); return true; } diff --git a/Modules/TerrainEditor/PaintTools/SmoothHeightTool.cs b/Modules/TerrainEditor/PaintTools/SmoothHeightTool.cs index d345368f35..ed607efb85 100644 --- a/Modules/TerrainEditor/PaintTools/SmoothHeightTool.cs +++ b/Modules/TerrainEditor/PaintTools/SmoothHeightTool.cs @@ -25,22 +25,41 @@ public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext editContext.ShowBrushesGUI(5); } - public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) + private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform) { - TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, editContext.brushTexture, editContext.brushStrength, editContext.brushSize, 0.0f); - } + Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); - public override bool OnPaint(Terrain terrain, IOnPaint editContext) - { - Rect brushRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(terrain, editContext.uv, editContext.brushSize); - TerrainPaintUtility.PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushRect); + brushStrength = Event.current.shift ? -brushStrength : brushStrength; - Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); - Vector4 brushParams = new Vector4(editContext.brushStrength, 0.0f, 0.0f, 0.0f); - mat.SetTexture("_BrushTex", editContext.brushTexture); + Vector4 brushParams = new Vector4(brushStrength, 0.0f, 0.0f, 0.0f); + mat.SetTexture("_BrushTex", brushTexture); mat.SetVector("_BrushParams", brushParams); + + TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); + Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.SmoothHeights); + } + + public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) + { + // We're only doing painting operations, early out if it's not a repaint + if (Event.current.type != EventType.Repaint) + return; + if (editContext.hitValidTerrain) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f); + PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); + TerrainPaintUtilityEditor.DrawBrushPreview(ctx, TerrainPaintUtilityEditor.BrushPreview.SourceRenderTexture, editContext.brushTexture, brushXform, TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(), 0); + TerrainPaintUtility.ReleaseContextResources(ctx); + } + } + + public override bool OnPaint(Terrain terrain, IOnPaint editContext) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds()); + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Smooth Height"); return true; } diff --git a/Modules/TerrainEditor/PaintTools/StampTool.cs b/Modules/TerrainEditor/PaintTools/StampTool.cs index f4f4eafa62..d6d59e57da 100644 --- a/Modules/TerrainEditor/PaintTools/StampTool.cs +++ b/Modules/TerrainEditor/PaintTools/StampTool.cs @@ -21,45 +21,84 @@ public override string GetName() public override string GetDesc() { - return "Left click to stamp the brush onto the terrain.\n\nHold shift and left click to stamp negative."; + return "Left click to stamp the brush onto the terrain.\n\nHold shift and mousewheel to adjust height."; } - public override bool OnPaint(Terrain terrain, IOnPaint editContext) + private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform) { - if (Event.current.type == EventType.MouseDrag) - return true; - Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial(); - Rect brushRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(terrain, editContext.uv, editContext.brushSize); - TerrainPaintUtility.PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushRect); - - Vector4 brushParams = new Vector4(editContext.brushStrength * 0.01f, 0.0f, m_StampHeight, 0.0f); + Vector4 brushParams = new Vector4(0.01f * brushStrength, 0.0f, m_StampHeight, 0.0f); + mat.SetTexture("_BrushTex", brushTexture); + mat.SetVector("_BrushParams", brushParams); - if (Event.current.shift) - brushParams.x = -brushParams.x; + TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat); - mat.SetTexture("_BrushTex", editContext.brushTexture); - mat.SetVector("_BrushParams", brushParams); Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainPaintUtility.BuiltinPaintMaterialPasses.StampHeight); + } + + public override bool OnPaint(Terrain terrain, IOnPaint editContext) + { + // ignore mouse drags + if (Event.current.type == EventType.MouseDrag) + return true; + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds()); + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Stamp"); return true; } public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) { - TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, editContext.brushTexture, editContext.brushStrength * 0.01f, editContext.brushSize, m_StampHeight); + Event evt = Event.current; + if (evt.shift && (evt.type == EventType.ScrollWheel)) + { + m_StampHeight += Event.current.delta.y * -0.0000007f * editContext.raycastHit.distance; + evt.Use(); + } + + // We're only doing painting operations, early out if it's not a repaint + if (evt.type != EventType.Repaint) + return; + + if (editContext.hitValidTerrain) + { + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f); + PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); + + Material material = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(); + + TerrainPaintUtilityEditor.DrawBrushPreview( + paintContext, TerrainPaintUtilityEditor.BrushPreview.SourceRenderTexture, editContext.brushTexture, brushXform, material, 0); + + // draw result preview + { + ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform); + + // restore old render target + RenderTexture.active = paintContext.oldRenderTexture; + + material.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture); + + TerrainPaintUtilityEditor.DrawBrushPreview( + paintContext, TerrainPaintUtilityEditor.BrushPreview.DestinationRenderTexture, editContext.brushTexture, brushXform, material, 1); + } + + TerrainPaintUtility.ReleaseContextResources(paintContext); + } } public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) { EditorGUI.BeginChangeCheck(); - m_StampHeight = EditorGUILayout.Slider(new GUIContent("Stamp Height", "You can set the Stamp Height property manually or you can shift-click on the terrain to sample the height at the mouse position (rather like the “eyedropper” tool in an image editor)."), m_StampHeight * terrain.terrainData.size.y, 0, terrain.terrainData.size.y) / terrain.terrainData.size.y; + m_StampHeight = EditorGUILayout.Slider(new GUIContent("Stamp Height", "You can set the Stamp Height manually or you can hold shift and mouse wheel on the terrain to adjust it."), m_StampHeight * terrain.terrainData.size.y, 0, terrain.terrainData.size.y) / terrain.terrainData.size.y; if (EditorGUI.EndChangeCheck()) Save(true); // show built-in brushes + editContext.ShowBrushesGUI(5); base.OnInspectorGUI(terrain, editContext); } } diff --git a/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs b/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs index 65eb147cdc..9f1de28910 100644 --- a/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs +++ b/Modules/TerrainEditor/PaintTools/TerrainPaintTool.cs @@ -15,7 +15,6 @@ public interface IOnPaint Texture brushTexture { get; } Vector2 uv { get; } float brushStrength { get; } - float brushRotation { get; } float brushSize { get; } void RepaintAllInspectors(); @@ -25,8 +24,9 @@ public interface IOnSceneGUI SceneView sceneView { get; } Texture brushTexture { get; } float brushStrength { get; } - float brushRotation { get; } float brushSize { get; } + bool hitValidTerrain { get; } + RaycastHit raycastHit { get; } } public interface IOnInspectorGUI @@ -40,6 +40,8 @@ internal interface ITerrainPaintTool string GetDesc(); void OnEnable(); void OnDisable(); + void OnEnterToolMode(); + void OnExitToolMode(); void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext); void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext); bool OnPaint(Terrain terrain, IOnPaint editContext); @@ -51,6 +53,8 @@ public abstract class TerrainPaintTool : ScriptableSingleton, ITerrainPain public abstract string GetDesc(); public virtual void OnEnable() {} public virtual void OnDisable() {} + public virtual void OnEnterToolMode() {} + public virtual void OnExitToolMode() {} public virtual void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext) {} public virtual void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) {} public virtual bool OnPaint(Terrain terrain, IOnPaint editContext) { return false; } @@ -62,27 +66,28 @@ internal class OnPaintContext : IOnPaint internal Vector2 m_UV = Vector2.zero; internal float m_BrushStrength = 0.0f; internal float m_BrushSize = 0; - internal float m_BrushRotation = 0.0f; + internal bool m_HitValidTerrain = false; + internal RaycastHit m_RaycastHit; - public OnPaintContext(Texture brushTexture, Vector2 uv, float brushStrength, float brushRotation, float brushSize) + public OnPaintContext(RaycastHit raycastHit, Texture brushTexture, Vector2 uv, float brushStrength, float brushSize) { - Set(brushTexture, uv, brushStrength, brushRotation, brushSize); + Set(false, raycastHit, brushTexture, uv, brushStrength, brushSize); } - public OnPaintContext Set(Texture brushTexture, Vector2 uv, float brushStrength, float brushRotation, float brushSize) + public OnPaintContext Set(bool hitValidTerrain, RaycastHit raycastHit, Texture brushTexture, Vector2 uv, float brushStrength, float brushSize) { m_BrushTexture = brushTexture; m_UV = uv; m_BrushStrength = brushStrength; m_BrushSize = brushSize; - m_BrushRotation = brushRotation; + m_HitValidTerrain = hitValidTerrain; + m_RaycastHit = raycastHit; return this; } public Texture brushTexture { get { return m_BrushTexture; } } public Vector2 uv { get { return m_UV; } } public float brushStrength { get { return m_BrushStrength; } } - public float brushRotation { get { return m_BrushRotation; } } public float brushSize { get { return m_BrushSize; } } public void RepaintAllInspectors() { InspectorWindow.RepaintAllInspectors(); } @@ -94,28 +99,31 @@ internal class OnSceneGUIContext : IOnSceneGUI internal Texture m_BrushTexture = null; internal float m_BrushStrength = 0.0f; internal float m_BrushSize = 0; - internal float m_BrushRotation = 0.0f; + internal bool m_HitValidTerrain = false; + internal RaycastHit m_RaycastHit; - public OnSceneGUIContext(SceneView sceneView, Texture brushTexture, float brushStrength, float brushRotation, float brushSize) + public OnSceneGUIContext(SceneView sceneView, RaycastHit raycastHit, Texture brushTexture, float brushStrength, float brushSize) { - Set(sceneView, brushTexture, brushStrength, brushSize, brushRotation); + Set(sceneView, false, raycastHit, brushTexture, brushStrength, brushSize); } - public OnSceneGUIContext Set(SceneView sceneView, Texture brushTexture, float brushStrength, float brushRotation, float brushSize) + public OnSceneGUIContext Set(SceneView sceneView, bool hitValidTerrain, RaycastHit raycastHit, Texture brushTexture, float brushStrength, float brushSize) { m_SceneView = sceneView; m_BrushTexture = brushTexture; m_BrushStrength = brushStrength; m_BrushSize = brushSize; - m_BrushRotation = brushRotation; + m_HitValidTerrain = hitValidTerrain; + m_RaycastHit = raycastHit; return this; } public SceneView sceneView { get { return m_SceneView; } } public Texture brushTexture { get { return m_BrushTexture; } } public float brushStrength { get { return m_BrushStrength; } } - public float brushRotation { get { return m_BrushRotation; } } public float brushSize { get { return m_BrushSize; } } + public bool hitValidTerrain { get { return m_HitValidTerrain; } } + public RaycastHit raycastHit { get { return m_RaycastHit; } } } internal class OnInspectorGUIContext : IOnInspectorGUI diff --git a/Modules/TerrainEditor/TerrainInspector.cs b/Modules/TerrainEditor/TerrainInspector.cs index fcc226c9cb..de381c2fe1 100644 --- a/Modules/TerrainEditor/TerrainInspector.cs +++ b/Modules/TerrainEditor/TerrainInspector.cs @@ -635,9 +635,9 @@ public bool active static internal ITerrainPaintTool[] m_Tools = null; static internal string[] m_ToolNames = null; - static OnPaintContext onPaintEditContext = new OnPaintContext(null, Vector2.zero, 0.0f, 0.0f, 0.0f); + static OnPaintContext onPaintEditContext = new OnPaintContext(new RaycastHit(), null, Vector2.zero, 0.0f, 0.0f); static OnInspectorGUIContext onInspectorGUIEditContext = new OnInspectorGUIContext(); - static OnSceneGUIContext onSceneGUIEditContext = new OnSceneGUIContext(null, null, 0.0f, 0.0f, 0.0f); + static OnSceneGUIContext onSceneGUIEditContext = new OnSceneGUIContext(null, new RaycastHit(), null, 0.0f, 0.0f); ITerrainPaintTool GetActiveTool() { @@ -813,6 +813,7 @@ void ResetPaintTools() void Initialize() { m_Terrain = target as Terrain; + CheckToolActivation(); } void LoadInspectorSettings() @@ -826,7 +827,7 @@ void LoadInspectorSettings() int selected = EditorPrefs.GetInt("TerrainSelectedBrush", 0); s_DetailPainter.selectedDetail = EditorPrefs.GetInt("TerrainSelectedDetail", 0); - m_ActivePaintToolIndex = EditorPrefs.GetInt("TerraiActivePaintToolIndex", 0); + m_ActivePaintToolIndex = EditorPrefs.GetInt("TerrainActivePaintToolIndex", 0); // TODO: this should be stored by name if (m_ActivePaintToolIndex > m_Tools.Length) m_ActivePaintToolIndex = 0; @@ -844,7 +845,7 @@ void SaveInspectorSettings() EditorPrefs.SetFloat("TerrainBrushSize", m_Size); EditorPrefs.SetFloat("TerrainBrushStrength", m_Strength); - EditorPrefs.SetInt("TerraiActivePaintToolIndex", m_ActivePaintToolIndex); + EditorPrefs.SetInt("TerrainActivePaintToolIndex", m_ActivePaintToolIndex); } public void OnEnable() @@ -874,6 +875,9 @@ public void OnEnable() LoadInspectorSettings(); + // now that tool selection has been loaded from inspector, activate the selected tool + CheckToolActivation(); + InitializeLightingFields(); m_TerrainToolContext = new TerrainToolContext(this); @@ -886,9 +890,11 @@ public void OnEnable() public void OnDisable() { ShortcutIntegration.instance.contextManager.DeregisterToolContext(m_TerrainToolContext); - TerrainPaintUtility.FlushAllPaints(); + PaintContext.ApplyDelayedActions(); SceneView.onSceneGUIDelegate -= OnSceneGUICallback; + SetCurrentPaintToolInactive(); + SaveInspectorSettings(); m_ShowReflectionProbesGUI.valueChanged.RemoveListener(Repaint); @@ -922,6 +928,55 @@ TerrainTool selectedTool Tools.current = Tool.None; m_SelectedTool.value = (int)value; s_activeTerrainInspector = GetInstanceID(); + CheckToolActivation(); + } + } + + // this is a bunch of tracking to ensure we don't mess up the tool mode callbacks + private bool m_PaintToolActive = false; + private void SetCurrentPaintToolActive() + { + if (!m_PaintToolActive) + { + ITerrainPaintTool paintTool = GetActiveTool(); + if (paintTool != null) + { + paintTool.OnEnterToolMode(); + m_PaintToolActive = true; + } + } + } + + private void SetCurrentPaintToolInactive() + { + if (m_PaintToolActive) + { + ITerrainPaintTool paintTool = GetActiveTool(); + if (paintTool != null) + { + paintTool.OnExitToolMode(); + m_PaintToolActive = false; + } + } + } + + // Ideally we would be notified when the active tool changes, but I can see no way to do that + // So instead we will call this function everywhere, which checks for it changing and does the proper notification callbacks + private TerrainTool m_PreviousSelectedTool = TerrainTool.None; + private void CheckToolActivation() + { + TerrainTool currentTool = selectedTool; + if (currentTool != m_PreviousSelectedTool) + { + // inactivate previous tool, if necessary + if (m_PreviousSelectedTool == TerrainTool.Paint) + SetCurrentPaintToolInactive(); + + m_PreviousSelectedTool = currentTool; + + // activate new tool, if necessary + if (currentTool == TerrainTool.Paint) + SetCurrentPaintToolActive(); } } @@ -1390,9 +1445,14 @@ public void ShowPaint() if (m_Tools != null && m_Tools.Length > 1 && m_ToolNames != null) { EditorGUI.BeginChangeCheck(); - m_ActivePaintToolIndex = EditorGUILayout.Popup(m_ActivePaintToolIndex, m_ToolNames); - if (EditorGUI.EndChangeCheck()) + int newPaintToolIndex = EditorGUILayout.Popup(m_ActivePaintToolIndex, m_ToolNames); + if (EditorGUI.EndChangeCheck() && (newPaintToolIndex != m_ActivePaintToolIndex)) + { + SetCurrentPaintToolInactive(); + m_ActivePaintToolIndex = newPaintToolIndex; + SetCurrentPaintToolActive(); Repaint(); + } ITerrainPaintTool activeTool = GetActiveTool(); GUILayout.BeginVertical(EditorStyles.helpBox); @@ -1408,7 +1468,8 @@ public void ShowBrushes(int spacing) GUILayout.Space(spacing); bool repaint = brushList.ShowGUI(); - m_Size = EditorGUILayout.Slider(styles.brushSize, m_Size, 1.0f, Mathf.Min(m_Terrain.terrainData.size.x - 1.0f, m_Terrain.terrainData.size.z - 1.0f)); + float safetyFactorHack = 0.9375f; + m_Size = EditorGUILayout.Slider(styles.brushSize, m_Size, 0.1f, Mathf.Round(Mathf.Min(m_Terrain.terrainData.size.x, m_Terrain.terrainData.size.z) * safetyFactorHack)); m_Strength = PercentSlider(styles.opacity, m_Strength, kMinBrushStrength, 1); // former string formatting: "0.0%" brushList.ShowEditGUI(); @@ -1866,23 +1927,21 @@ private bool IsModificationToolActive() return true; } - bool IsBrushPreviewVisible() + bool IsBrushPreviewVisible(Terrain overTerrain) { if (!IsModificationToolActive()) return false; - Vector3 pos; - Vector2 uv; - return Raycast(out uv, out pos); + return (overTerrain != null); } - private bool RaycastAllTerrains(out Terrain hitTerrain, out Vector2 hitUV) + private bool RaycastAllTerrains(out Terrain hitTerrain, out RaycastHit raycastHit) { Ray mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); float minDist = float.MaxValue; hitTerrain = null; - hitUV = Vector2.zero; + raycastHit = new RaycastHit(); foreach (Terrain terrain in Terrain.activeTerrains) { RaycastHit hit; @@ -1892,11 +1951,11 @@ private bool RaycastAllTerrains(out Terrain hitTerrain, out Vector2 hitUV) { minDist = hit.distance; hitTerrain = terrain; - hitUV = hit.textureCoord; + raycastHit = hit; } } } - return hitTerrain; + return (hitTerrain != null); } public void OnSceneGUICallback(SceneView sceneView) @@ -1905,47 +1964,52 @@ public void OnSceneGUICallback(SceneView sceneView) Event e = Event.current; - Terrain terrain = null; - Vector2 uv = Vector2.zero; + Terrain hitTerrain = null; + RaycastHit raycastHit = new RaycastHit(); if (selectedTool == TerrainTool.Paint || selectedTool == TerrainTool.PaintDetail || selectedTool == TerrainTool.PlaceTree) { - if (RaycastAllTerrains(out terrain, out uv)) + if (RaycastAllTerrains(out hitTerrain, out raycastHit)) { if (e.type == EventType.MouseDown || e.type == EventType.MouseUp) { if (e.button == 0 && !Event.current.alt) - Selection.activeObject = terrain; + Selection.activeObject = hitTerrain; } } } + Vector2 uv = raycastHit.textureCoord; - bool isTerrainValid = (terrain != null && terrain.terrainData != null); + bool hitValidTerrain = (hitTerrain != null && hitTerrain.terrainData != null); + if (!hitValidTerrain) + { + raycastHit = new RaycastHit(); + } if (selectedTool == TerrainTool.Paint) { - Terrain lastActiveTerrain = isTerrainValid ? terrain : s_LastActiveTerrain; + Terrain lastActiveTerrain = hitValidTerrain ? hitTerrain : s_LastActiveTerrain; if (lastActiveTerrain) { ITerrainPaintTool activeTool = GetActiveTool(); - activeTool.OnSceneGUI(lastActiveTerrain, onSceneGUIEditContext.Set(sceneView, brushList.GetActiveBrush().texture, m_Strength, 0.0f, m_Size)); + activeTool.OnSceneGUI(lastActiveTerrain, onSceneGUIEditContext.Set(sceneView, hitValidTerrain, raycastHit, brushList.GetActiveBrush().texture, m_Strength, m_Size)); } } else if (selectedTool == TerrainTool.PaintDetail || selectedTool == TerrainTool.PlaceTree) { - if (isTerrainValid) + if (hitValidTerrain) { float brushSize = selectedTool == TerrainTool.PlaceTree ? TreePainter.brushSize : m_Size; - TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(terrain, brushList.GetActiveBrush().texture, m_Strength, brushSize, 0.0f); + TerrainPaintUtilityEditor.ShowDefaultPreviewBrush(hitTerrain, brushList.GetCircleBrush().texture, brushSize); } } - if (!isTerrainValid) + if (!hitValidTerrain) return; - s_LastActiveTerrain = terrain; + s_LastActiveTerrain = hitTerrain; int id = GUIUtility.GetControlID(s_TerrainEditorHash, FocusType.Passive); switch (e.GetTypeForControl(id)) @@ -1957,7 +2021,7 @@ public void OnSceneGUICallback(SceneView sceneView) break; case EventType.MouseMove: - if (IsBrushPreviewVisible()) + if (IsBrushPreviewVisible(hitTerrain)) HandleUtility.Repaint(); break; @@ -2000,12 +2064,12 @@ public void OnSceneGUICallback(SceneView sceneView) TreePainter.BeginPlaceTrees(m_Terrain); } - TreePainter.PlaceTrees(terrain, uv.x, uv.y); + TreePainter.PlaceTrees(hitTerrain, uv.x, uv.y); } } else { - TreePainter.RemoveTrees(terrain, uv.x, uv.y, Event.current.control); + TreePainter.RemoveTrees(hitTerrain, uv.x, uv.y, Event.current.control); } } else if (selectedTool == TerrainTool.PaintDetail) @@ -2016,13 +2080,13 @@ public void OnSceneGUICallback(SceneView sceneView) } DetailPaintOperation paintOp = new DetailPaintOperation(); - paintOp.size = (int)Mathf.Max(1.0f, ((float)m_Size * ((float)terrain.terrainData.detailResolution / terrain.terrainData.size.x))); + paintOp.size = (int)Mathf.Max(1.0f, ((float)m_Size * ((float)hitTerrain.terrainData.detailResolution / hitTerrain.terrainData.size.x))); paintOp.targetStrength = m_DetailStrength * 16F; if (Event.current.shift || Event.current.control) paintOp.targetStrength *= -1; paintOp.opacity = m_DetailOpacity; paintOp.clearSelectedOnly = Event.current.control; - paintOp.terrainData = terrain.terrainData; + paintOp.terrainData = hitTerrain.terrainData; paintOp.brush = brushList.GetActiveBrush(); paintOp.tool = selectedTool; paintOp.randomizeDetails = true; @@ -2034,10 +2098,10 @@ public void OnSceneGUICallback(SceneView sceneView) else { ITerrainPaintTool activeTool = GetActiveTool(); - if (activeTool.OnPaint(terrain, onPaintEditContext.Set(brushList.GetActiveBrush().texture, uv, m_Strength, 0.0f, m_Size))) + if (activeTool.OnPaint(hitTerrain, onPaintEditContext.Set(hitValidTerrain, raycastHit, brushList.GetActiveBrush().texture, uv, m_Strength, m_Size))) { // height map modification modes - terrain.editorRenderFlags = TerrainRenderFlags.Heightmap; + hitTerrain.editorRenderFlags = TerrainRenderFlags.Heightmap; } } @@ -2067,8 +2131,8 @@ public void OnSceneGUICallback(SceneView sceneView) s_DetailPainter.EndPaintDetails(); } - terrain.editorRenderFlags = TerrainRenderFlags.All; - TerrainPaintUtility.FlushAllPaints(); + hitTerrain.editorRenderFlags = TerrainRenderFlags.All; + PaintContext.ApplyDelayedActions(); e.Use(); } diff --git a/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs b/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs index 39ccf3c7f7..22743c45f5 100644 --- a/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs +++ b/Modules/TerrainEditor/Utilities/TerrainPaintUtilityEditor.cs @@ -14,12 +14,6 @@ namespace UnityEditor.Experimental.TerrainAPI { public static class TerrainPaintUtilityEditor { - internal enum BrushPreviewMeshType - { - QuadOutline = 0, - QuadPatch - } - // This maintains the list of terrains we have touched in the current operation (and the current operation identifier, as an undo group) // We track this to have good cross-tile undo support: each modified tile should be added, at most, ONCE within a single operation private static int s_CurrentOperationUndoGroup = -1; @@ -27,7 +21,7 @@ internal enum BrushPreviewMeshType static TerrainPaintUtilityEditor() { - TerrainPaintUtility.onTerrainTileBeforePaint += (tile, action, editorUndoName) => + PaintContext.onTerrainTileBeforePaint += (tile, action, editorUndoName) => { // if we are in a new undo group (new operation) then start with an empty list if (Undo.GetCurrentGroup() != s_CurrentOperationUndoGroup) @@ -44,7 +38,7 @@ static TerrainPaintUtilityEditor() s_CurrentOperationUndoStack.Add(tile.terrain); var undoObjects = new List(); undoObjects.Add(tile.terrain.terrainData); - if (0 != (action & TerrainPaintUtility.ToolAction.PaintTexture)) + if (0 != (action & PaintContext.ToolAction.PaintTexture)) undoObjects.AddRange(tile.terrain.terrainData.alphamapTextures); Undo.RegisterCompleteObjectUndo(undoObjects.ToArray(), editorUndoName); } @@ -67,31 +61,15 @@ internal static void UpdateTerrainDataUndo(TerrainData terrainData, string undoN } } - public static void ShowDefaultPreviewBrush(Terrain terrain, Texture brushTexture, float brushStrength, float brushSize, float futurePreviewScale) + public static void ShowDefaultPreviewBrush(Terrain terrain, Texture brushTexture, float brushSize) { Ray mouseRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hit; if (terrain.GetComponent().Raycast(mouseRay, out hit, Mathf.Infinity)) { - if (Event.current.shift) - brushStrength = -brushStrength; - - Rect brushRect = TerrainPaintUtility.CalculateBrushRectInTerrainUnits(terrain, hit.textureCoord, brushSize); - TerrainPaintUtility.PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushRect); - - ctx.sourceRenderTexture.filterMode = FilterMode.Bilinear; - brushTexture.filterMode = FilterMode.Bilinear; - - Vector2 topLeft = ctx.brushRect.min; - float xfrac = ((topLeft.x - (int)topLeft.x) / (float)ctx.sourceRenderTexture.width); - float yfrac = ((topLeft.y - (int)topLeft.y) / (float)ctx.sourceRenderTexture.height); - - Vector4 texScaleOffset = new Vector4(0.5f, 0.5f, 0.5f + xfrac + 0.5f / (float)ctx.sourceRenderTexture.width, 0.5f + yfrac + 0.5f / (float)ctx.sourceRenderTexture.height); - - DrawDefaultBrushPreviewMesh(terrain, hit, ctx.sourceRenderTexture, brushTexture, brushStrength * 0.01f, brushSize, defaultPreviewPatchMesh, false, texScaleOffset); - if ((futurePreviewScale > Mathf.Epsilon) && Event.current.control) - DrawDefaultBrushPreviewMesh(terrain, hit, ctx.sourceRenderTexture, brushTexture, futurePreviewScale, brushSize, defaultPreviewPatchMesh, true, texScaleOffset); - + BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, hit.textureCoord, brushSize, 0.0f); + PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); + DrawBrushPreview(ctx, TerrainPaintUtilityEditor.BrushPreview.SourceRenderTexture, brushTexture, brushXform, GetDefaultBrushPreviewMaterial(), 0); TerrainPaintUtility.ReleaseContextResources(ctx); } } @@ -103,83 +81,96 @@ public static Material GetDefaultBrushPreviewMaterial() return m_BrushPreviewMaterial; } - // drawing utilities - - internal static Mesh GenerateDefaultBrushPreviewMesh(int tesselationLevel) + public enum BrushPreview { - if (tesselationLevel < 1) - { - Debug.LogWarning("Invalid tessellation level passed to GenerateBrushPreviewMesh."); - return null; - } - - var verts = new List(); - var indices = new List(); - - Mesh m = new Mesh(); - - float incr = 2.0f / (float)tesselationLevel; - - Vector3 v = new Vector3(-1.0f, 0, -1.0f); - - for (int i = 0; i <= tesselationLevel; i++) - { - v.x = -1.0f; - for (int j = 0; j <= tesselationLevel; j++) - { - verts.Add(v); - v.x += incr; - - if (i != tesselationLevel && j != tesselationLevel) - { - int index = i * (tesselationLevel + 1) + j; - - indices.Add(index); - indices.Add(index + tesselationLevel + 1); - indices.Add(index + 1); - - indices.Add(index + 1); - indices.Add(index + tesselationLevel + 1); - indices.Add(index + tesselationLevel + 2); - } - } - v.z += incr; - } - - m.vertices = verts.ToArray(); - m.triangles = indices.ToArray(); - - return m; - } - - public static void DrawDefaultBrushPreviewMesh(Terrain terrain, RaycastHit hit, Texture heightmapTexture, Texture brushTexture, float brushStrength, float brushSize, Mesh mesh, bool showPreviewPostBrush, Vector4 texScaleOffset) + SourceRenderTexture, + DestinationRenderTexture + }; + + public static void DrawBrushPreview( + PaintContext heightmapPC, + BrushPreview previewTexture, + Texture brushTexture, // brush texture to apply + BrushTransform brushXform, // brush transform that defines the brush UV space + Material proceduralMaterial, // the material to render with (must support procedural quad-mesh generation) + int materialPassIndex) // the pass to use within the material { - Vector4 brushParams = new Vector4(brushStrength, 2.0f * terrain.terrainData.heightmapScale.y, 0.0f, 0.0f); - - Material mat = GetDefaultBrushPreviewMaterial(); - mat.SetTexture("_MainTex", heightmapTexture); - mat.SetTexture("_BrushTex", brushTexture); - mat.SetVector("_BrushParams", brushParams); - mat.SetVector("_TexScaleOffet", texScaleOffset); - mat.SetPass(showPreviewPostBrush ? 1 : 0); - - Matrix4x4 matrix = Matrix4x4.identity; - matrix.SetTRS(new Vector3(hit.point.x, terrain.GetPosition().y, hit.point.z), Quaternion.identity, new Vector3(brushSize / 2.0f, 1, brushSize / 2.0f)); - - Graphics.DrawMeshNow(mesh, matrix); + // we want to build a quad mesh, with one vertex for each pixel in the heightmap + // i.e. a 3x3 heightmap would create a mesh that looks like this: + // + // +-+-+ + // |\|\| + // +-+-+ + // |\|\| + // +-+-+ + // + int quadsX = heightmapPC.pixelRect.width - 1; + int quadsY = heightmapPC.pixelRect.height - 1; + int vertexCount = quadsX * quadsY * (2 * 3); // two triangles (2 * 3 vertices) per quad + + // this is used to tessellate the quad mesh (from within the vertex shader) + proceduralMaterial.SetVector("_QuadRez", new Vector4(quadsX, quadsY, vertexCount, 0.0f)); + + // paint context pixels to heightmap uv: uv = (pixels + 0.5) / width + Texture heightmapTexture = (previewTexture == BrushPreview.SourceRenderTexture) ? heightmapPC.sourceRenderTexture : heightmapPC.destinationRenderTexture; + float invWidth = 1.0f / heightmapTexture.width; + float invHeight = 1.0f / heightmapTexture.height; + proceduralMaterial.SetVector("_HeightmapUV_PCPixelsX", new Vector4(invWidth, 0.0f, 0.0f, 0.0f)); + proceduralMaterial.SetVector("_HeightmapUV_PCPixelsY", new Vector4(0.0f, invHeight, 0.0f, 0.0f)); + proceduralMaterial.SetVector("_HeightmapUV_Offset", new Vector4(0.5f * invWidth, 0.5f * invHeight, 0.0f, 0.0f)); + + // make sure we point filter the heightmap + FilterMode oldFilter = heightmapTexture.filterMode; + heightmapTexture.filterMode = FilterMode.Point; + proceduralMaterial.SetTexture("_Heightmap", heightmapTexture); + + // paint context pixels to object (terrain) position + // objectPos.x = scaleX * pcPixels.x + heightmapRect.xMin * scaleX + // objectPos.y = scaleY * H + // objectPos.z = scaleZ * pcPixels.y + heightmapRect.yMin * scaleZ + float scaleX = heightmapPC.pixelSize.x; + float scaleY = 2.0f * heightmapPC.originTerrain.terrainData.heightmapScale.y; + float scaleZ = heightmapPC.pixelSize.y; + proceduralMaterial.SetVector("_ObjectPos_PCPixelsX", new Vector4(scaleX, 0.0f, 0.0f, 0.0f)); + proceduralMaterial.SetVector("_ObjectPos_HeightMapSample", new Vector4(0.0f, scaleY, 0.0f, 0.0f)); + proceduralMaterial.SetVector("_ObjectPos_PCPixelsY", new Vector4(0.0f, 0.0f, scaleZ, 0.0f)); + proceduralMaterial.SetVector("_ObjectPos_Offset", new Vector4(heightmapPC.pixelRect.xMin * scaleX, 0.0f, heightmapPC.pixelRect.yMin * scaleZ, 1.0f)); + + // heightmap paint context pixels to brush UV + // derivation: + + // BrushUV = f(terrainSpace.xz) = f(g(pcPixels.xy)) + // f(ts.xy) = ts.x * brushXform.X + ts.y * brushXform.Y + brushXform.Origin + // g(pcPixels.xy) = ts.xz = pcOrigin + pcPixels.xy * pcSize + // f(g(pcPixels.uv)) == (pcOrigin + pcPixels.uv * pcSize).x * brushXform.X + (pcOrigin + pcPixels.uv * pcSize).y * brushXform.Y + brushXform.Origin + // f(g(pcPixels.uv)) == (pcOrigin.x + pcPixels.u * pcSize.x) * brushXform.X + (pcOrigin.y + pcPixels.v * pcSize.y) * brushXform.Y + brushXform.Origin + // f(g(pcPixels.uv)) == (pcOrigin.x * brushXform.X) + (pcPixels.u * pcSize.x) * brushXform.X + (pcOrigin.y * brushXform.Y) + (pcPixels.v * pcSize.y) * brushXform.Y + brushXform.Origin + // f(g(pcPixels.uv)) == pcPixels.u * (pcSize.x * brushXform.X) + pcPixels.v * (pcSize.y * brushXform.Y) + (brushXform.Origin + (pcOrigin.x * brushXform.X) + (pcOrigin.y * brushXform.Y)) + + // paint context origin in terrain space + // (note this is the UV space origin and size, not the mesh origin & size) + float pcOriginX = heightmapPC.pixelRect.xMin * heightmapPC.pixelSize.x; + float pcOriginZ = heightmapPC.pixelRect.yMin * heightmapPC.pixelSize.y; + float pcSizeX = heightmapPC.pixelSize.x; + float pcSizeZ = heightmapPC.pixelSize.y; + + Vector2 scaleU = pcSizeX * brushXform.targetX; + Vector2 scaleV = pcSizeZ * brushXform.targetY; + Vector2 offset = brushXform.targetOrigin + pcOriginX * brushXform.targetX + pcOriginZ * brushXform.targetY; + proceduralMaterial.SetVector("_BrushUV_PCPixelsX", new Vector4(scaleU.x, scaleU.y, 0.0f, 0.0f)); + proceduralMaterial.SetVector("_BrushUV_PCPixelsY", new Vector4(scaleV.x, scaleV.y, 0.0f, 0.0f)); + proceduralMaterial.SetVector("_BrushUV_Offset", new Vector4(offset.x, offset.y, 0.0f, 1.0f)); + proceduralMaterial.SetTexture("_BrushTex", brushTexture); + + Vector3 terrainPos = heightmapPC.originTerrain.GetPosition(); + proceduralMaterial.SetVector("_TerrainObjectToWorldOffset", terrainPos); + + proceduralMaterial.SetPass(materialPassIndex); + Graphics.DrawProcedural(MeshTopology.Triangles, vertexCount); + + heightmapTexture.filterMode = oldFilter; } - static Mesh m_DefaultPreviewPatchMesh = null; static Material m_BrushPreviewMaterial = null; - - public static Mesh defaultPreviewPatchMesh - { - get - { - if (m_DefaultPreviewPatchMesh == null) - m_DefaultPreviewPatchMesh = GenerateDefaultBrushPreviewMesh(100); - return m_DefaultPreviewPatchMesh; - } - } } } diff --git a/Modules/TextCore/Managed/AssemblyInfo.cs b/Modules/TextCore/Managed/AssemblyInfo.cs index 6e1c470b4e..8400fd720c 100644 --- a/Modules/TextCore/Managed/AssemblyInfo.cs +++ b/Modules/TextCore/Managed/AssemblyInfo.cs @@ -9,3 +9,5 @@ [assembly: InternalsVisibleTo("Unity.TextCore.Editor")] [assembly: InternalsVisibleTo("Unity.TextMeshPro")] [assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")] +[assembly: InternalsVisibleTo("Unity.FontEngine.Tests")] +[assembly: InternalsVisibleTo("Unity.FontEngine.Editor.Tests")] diff --git a/Modules/TextCore/Managed/FaceInfo.cs b/Modules/TextCore/Managed/FaceInfo.cs new file mode 100644 index 0000000000..fe1b8fadb9 --- /dev/null +++ b/Modules/TextCore/Managed/FaceInfo.cs @@ -0,0 +1,261 @@ +// 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.Runtime.InteropServices; +using UnityEngine.Bindings; +using UnityEngine.Scripting; +using UnityEngine.TextCore.LowLevel; + + +namespace UnityEngine.TextCore +{ + /// + /// A structure that contains information about a given typeface and for a specific point size. + /// + [Serializable] + [UsedByNativeCode] + [StructLayout(LayoutKind.Sequential)] + public struct FaceInfo + { + /// + /// The name of the font typeface also known as family name. + /// + public string familyName { get { return m_FamilyName; } set { m_FamilyName = value; } } + + /// + /// The style name of the typeface which defines both the visual style and weight of the typeface. + /// + public string styleName { get { return m_StyleName; } set { m_StyleName = value; } } + + /// + /// The point size used for sampling the typeface. This is also referenced as sampling point size. + /// + public int pointSize { get { return m_PointSize; } set { m_PointSize = value; } } + + /// + /// The relative scale of the typeface. + /// Default value is 1.0f. + /// + public float scale { get { return m_Scale; } set { m_Scale = value; } } + + // Key metrics for the typeface + + /// + /// The line height represents the distance between consecutive lines of text. + /// This is the distance from baseline to baseline. It is usually computed as line height = ascent - descent + line gap. + /// + public float lineHeight { get { return m_LineHeight; } set { m_LineHeight = value; } } + + /// + /// The Ascent line is typically located at the top of the tallest glyph in the typeface. This represents the distance between the baseline and the tallest ascender. This value is usually positive. + /// + public float ascentLine { get { return m_AscentLine; } set { m_AscentLine = value; } } + + /// + /// The Cap line is typically located at the top of capital letters. This value represents the distance between the baseline and the top of capital letters. + /// + public float capLine { get { return m_CapLine; } set { m_CapLine = value; } } + + /// + /// The Mean line is typically located at the top of lowercase letters. This value represents the distance between the baseline and the top of lowercase letters. + /// + public float meanLine { get { return m_MeanLine; } set { m_MeanLine = value; } } + + /// + /// The Baseline is an imaginary line upon which all glyphs appear to rest on. This value is typically zero. + /// + public float baseline { get { return m_Baseline; } set { m_Baseline = value; } } + + /// + /// The Descent line is typically located at the bottom of the glyph with the lowest descender in the typeface. This represents the distance between the baseline and the lowest descender. This value is usually negative. + /// + public float descentLine { get { return m_DescentLine; } set { m_DescentLine = value; } } + + /// + /// The position of characters using superscript. + /// + public float superscriptOffset { get { return m_SuperscriptOffset; } set { m_SuperscriptOffset = value; } } + + /// + /// The relative size / scale of superscript characters. + /// + public float superscriptSize { get { return m_SuperscriptSize; } set { m_SuperscriptSize = value; } } + + /// + /// The position of characters using subscript. + /// + public float subscriptOffset { get { return m_SubscriptOffset; } set { m_SubscriptOffset = value; } } + + /// + /// The relative size / scale of subscript characters. + /// + public float subscriptSize { get { return m_SubscriptSize; } set { m_SubscriptSize = value; } } + + /// + /// The position of the underline. + /// + public float underlineOffset { get { return m_UnderlineOffset; } set { m_UnderlineOffset = value; } } + + /// + /// The thickness of the underline. + /// + public float underlineThickness { get { return m_UnderlineThickness; } set { m_UnderlineThickness = value; } } + + /// + /// The position of the strikethrough. + /// + public float strikethroughOffset { get { return m_StrikethroughOffset; } set { m_StrikethroughOffset = value; } } + + /// + /// The thickness of the strikethrough. + /// + public float strikethroughThickness { get { return m_StrikethroughThickness; } set { m_StrikethroughThickness = value; } } + + /// + /// The width of the tab character. This width is typically the same as the space character. + /// + public float tabWidth { get { return m_TabWidth; } set { m_TabWidth = value; } } + + // ============================================= + // Private backing fields for public properties. + // ============================================= + + [SerializeField] + [NativeName("familyName")] + private string m_FamilyName; + + [SerializeField] + [NativeName("styleName")] + private string m_StyleName; + + [SerializeField] + [NativeName("pointSize")] + private int m_PointSize; + + [SerializeField] + [NativeName("scale")] + private float m_Scale; + + [SerializeField] + [NativeName("lineHeight")] + private float m_LineHeight; + + [SerializeField] + [NativeName("ascentLine")] + private float m_AscentLine; + + [SerializeField] + [NativeName("capLine")] + private float m_CapLine; + + [SerializeField] + [NativeName("meanLine")] + private float m_MeanLine; + + [SerializeField] + [NativeName("baseline")] + private float m_Baseline; + + [SerializeField] + [NativeName("descentLine")] + private float m_DescentLine; + + [SerializeField] + [NativeName("superscriptOffset")] + private float m_SuperscriptOffset; + + [SerializeField] + [NativeName("superscriptSize")] + private float m_SuperscriptSize; + + [SerializeField] + [NativeName("subscriptOffset")] + private float m_SubscriptOffset; + + [SerializeField] + [NativeName("subscriptSize")] + private float m_SubscriptSize; + + [SerializeField] + [NativeName("underlineOffset")] + private float m_UnderlineOffset; + + [SerializeField] + [NativeName("underlineThickness")] + private float m_UnderlineThickness; + + [SerializeField] + [NativeName("strikethroughOffset")] + private float m_StrikethroughOffset; + + [SerializeField] + [NativeName("strikethroughThickness")] + private float m_StrikethroughThickness; + + [SerializeField] + [NativeName("tabWidth")] + private float m_TabWidth; + + /// + /// Constructor used for testing + /// + internal FaceInfo(string familyName, string styleName, int pointSize, float scale, float lineHeight, float ascentLine, float capLine, float meanLine, float baseline, float descentLine, float superscriptOffset, float superscriptSize, float subscriptOffset, float subscriptSize, float underlineOffset, float underlineThickness, float strikethroughOffset, float strikethroughThickness, float tabWidth) + { + m_FamilyName = familyName; + m_StyleName = styleName; + + m_PointSize = pointSize; + m_Scale = scale; + + m_LineHeight = lineHeight; + m_AscentLine = ascentLine; + m_CapLine = capLine; + m_MeanLine = meanLine; + m_Baseline = baseline; + m_DescentLine = descentLine; + + m_SuperscriptOffset = superscriptOffset; + m_SuperscriptSize = superscriptSize; + m_SubscriptOffset = subscriptOffset; + m_SubscriptSize = subscriptSize; + + m_UnderlineOffset = underlineOffset; + m_UnderlineThickness = underlineThickness; + + m_StrikethroughOffset = strikethroughOffset; + m_StrikethroughThickness = strikethroughThickness; + + m_TabWidth = tabWidth; + } + + /// + /// Compares the information in this FaceInfo structure with the information in the given FaceInfo structure to determine whether they have the same values. + /// + /// The FaceInfo structure to compare this FaceInfo structure with. + /// Returns true if the FaceInfo structures have the same values. False if not. + public bool Compare(FaceInfo other) + { + return familyName == other.familyName && + styleName == other.styleName && + pointSize == other.pointSize && + FontEngineUtilities.Approximately(scale, other.scale) && + FontEngineUtilities.Approximately(lineHeight, other.lineHeight) && + FontEngineUtilities.Approximately(ascentLine, other.ascentLine) && + FontEngineUtilities.Approximately(capLine, other.capLine) && + FontEngineUtilities.Approximately(meanLine, other.meanLine) && + FontEngineUtilities.Approximately(baseline, other.baseline) && + FontEngineUtilities.Approximately(descentLine, other.descentLine) && + FontEngineUtilities.Approximately(superscriptOffset, other.superscriptOffset) && + FontEngineUtilities.Approximately(superscriptSize, other.superscriptSize) && + FontEngineUtilities.Approximately(subscriptOffset, other.subscriptOffset) && + FontEngineUtilities.Approximately(subscriptSize, other.subscriptSize) && + FontEngineUtilities.Approximately(underlineOffset, other.underlineOffset) && + FontEngineUtilities.Approximately(underlineThickness, other.underlineThickness) && + FontEngineUtilities.Approximately(strikethroughOffset, other.strikethroughOffset) && + FontEngineUtilities.Approximately(strikethroughThickness, other.strikethroughThickness) && + FontEngineUtilities.Approximately(tabWidth, other.tabWidth); + } + } +} diff --git a/Modules/TextCore/Managed/Glyph.cs b/Modules/TextCore/Managed/Glyph.cs index 0499ff254c..0aa3275e2d 100644 --- a/Modules/TextCore/Managed/Glyph.cs +++ b/Modules/TextCore/Managed/Glyph.cs @@ -6,211 +6,367 @@ using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; +using UnityEngine.TextCore.LowLevel; namespace UnityEngine.TextCore { /// - /// A Glyph is the visual representation of a text element / character. + /// A rectangle that defines the position of a glyph within an atlas texture. /// [Serializable] - [NativeAsStruct] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] - public class Glyph + public struct GlyphRect : IEquatable { /// - /// Constructor for a new glyph. + /// The x position of the glyph in the font atlas texture. /// - public Glyph() - { - this.index = 0; - this.x = 0; - this.y = 0; - this.width = 0; - this.height = 0; - this.bearingX = 0; - this.bearingY = 0; - this.advanceX = 0; - this.scale = 1; - this.atlasIndex = 0; - } + public int x { get { return m_X; } set { m_X = value; } } /// - /// Constructor for a new glyph + /// The y position of the glyph in the font atlas texture. /// - /// Glyph whose values are copied to the new glyph. - public Glyph(Glyph glyph) - { - this.index = glyph.index; - this.x = glyph.x; - this.y = glyph.y; - this.width = glyph.width; - this.height = glyph.height; - this.bearingX = glyph.bearingX; - this.bearingY = glyph.bearingY; - this.advanceX = glyph.advanceX; - this.scale = glyph.scale; - this.atlasIndex = glyph.atlasIndex; - } + public int y { get { return m_Y; } set { m_Y = value; } } /// - /// Constructor for a new glyph + /// The width of the glyph. /// - /// Index of the glyph. - /// The bearingX of the glyph. - /// The bearingY of the glyph. - /// The width of the glyph. - /// The height of the glyph. - /// The advanceX of the glyph. - /// The relative scale of the glyph. - public Glyph(uint index, int bearingX, int bearingY, int width, int height, int advanceX, float scale, int atlasIndex) - { - this.index = index; - this.x = 0; - this.y = 0; - this.width = width; - this.height = height; - this.bearingX = bearingX; - this.bearingY = bearingY; - this.advanceX = advanceX; - this.scale = scale; - this.atlasIndex = atlasIndex; - } + public int width { get { return m_Width; } set { m_Width = value; } } /// - /// The index of the glyph in the source font file. + /// The height of the glyph. /// - public uint index; + public int height { get { return m_Height; } set { m_Height = value; } } + + // ============================================= + // Private backing fields for public properties. + // ============================================= + + [SerializeField] + [NativeName("x")] + private int m_X; + + [SerializeField] + [NativeName("y")] + private int m_Y; + + [SerializeField] + [NativeName("width")] + private int m_Width; + + [SerializeField] + [NativeName("height")] + private int m_Height; + + static readonly GlyphRect s_ZeroGlyphRect = new GlyphRect(0, 0, 0, 0); /// - /// The point size at which this glyph was rastered. + /// A GlyphRect with all values set to zero. Shorthand for writing GlyphRect(0, 0, 0, 0). /// - //public int pointSize; + public static GlyphRect zero { get { return s_ZeroGlyphRect; } } /// - /// The x position of the glyph in the font atlas texture + /// Constructor for new GlyphRect. /// - public int x { get { return m_XMin; } set { m_XMin = value; } } - [SerializeField] - [NativeName("x")] - private int m_XMin; + /// The x position of the glyph in the atlas texture. + /// The y position of the glyph in the atlas texture. + /// The width of the glyph. + /// The height of the glyph. + public GlyphRect(int x, int y, int width, int height) + { + m_X = x; + m_Y = y; + m_Width = width; + m_Height = height; + } /// - /// The y position of the glyph in the font atlas texture. + /// Construct new GlyphRect from a Rect. /// - public int y { get { return m_YMin; } set { m_YMin = value; } } - [SerializeField] - [NativeName("y")] - private int m_YMin; + /// The Rect used to construct the new GlyphRect. + public GlyphRect(Rect rect) + { + m_X = (int)rect.x; + m_Y = (int)rect.y; + m_Width = (int)rect.width; + m_Height = (int)rect.height; + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } + + public override bool Equals(object obj) + { + return base.Equals(obj); + } + + public bool Equals(GlyphRect other) + { + return base.Equals(other); + } + public static bool operator==(GlyphRect lhs, GlyphRect rhs) + { + return lhs.x == rhs.x && + lhs.y == rhs.y && + lhs.width == rhs.width && + lhs.height == rhs.height; + } - // ======================= - // Glyph Metrics - // ======================= + public static bool operator!=(GlyphRect lhs, GlyphRect rhs) + { + return !(lhs == rhs); + } + } + /// + /// A set of values that define the size, position and spacing of a glyph when performing text layout. + /// + [Serializable] + [UsedByNativeCode] + [StructLayout(LayoutKind.Sequential)] + public struct GlyphMetrics : IEquatable + { /// /// The width of the glyph. /// - public int width { get { return m_Width; } set { m_Width = value; } } - [SerializeField] - [NativeName("width")] - private int m_Width; + public float width { get { return m_Width; } set { m_Width = value; } } /// /// The height of the glyph. /// - public int height { get { return m_Height; } set { m_Height = value; } } - [SerializeField] - [NativeName("height")] - private int m_Height; + public float height { get { return m_Height; } set { m_Height = value; } } /// - /// The horizontal distance from the current drawing position (origin) relative to the elements' left bounding box edge (bbox). + /// The horizontal distance from the current drawing position (origin) relative to the element's left bounding box edge (bbox). /// - public int bearingX; + public float horizontalBearingX { get { return m_HorizontalBearingX; } set { m_HorizontalBearingX = value; } } /// - /// The vertical distance from the current baseline relative to the elements' top bounding box edge (bbox). + /// The vertical distance from the current baseline relative to the element's top bounding box edge (bbox). /// - public int bearingY; + public float horizontalBearingY { get { return m_HorizontalBearingY; } set { m_HorizontalBearingY = value; } } /// /// The horizontal distance to increase (left to right) or decrease (right to left) the drawing position relative to the origin of the text element. - /// This determines the origin position of the next element. + /// This determines the origin position of the next text element. /// - public int advanceX; + public float horizontalAdvance { get { return m_HorizontalAdvance; } set { m_HorizontalAdvance = value; } } + + // ============================================= + // Private backing fields for public properties. + // ============================================= + + [SerializeField] + [NativeName("width")] + private float m_Width; + + [SerializeField] + [NativeName("height")] + private float m_Height; + + [SerializeField] + [NativeName("horizontalBearingX")] + private float m_HorizontalBearingX; + + [SerializeField] + [NativeName("horizontalBearingy")] + private float m_HorizontalBearingY; + + [SerializeField] + [NativeName("horizontalAdvance")] + private float m_HorizontalAdvance; /// - /// The relative scale of the text element. The default value is 1.0. + /// Constructor for new glyph metrics. /// - public float scale; + /// The width of the glyph. + /// The height of the glyph. + /// The horizontal bearingX. + /// The horizontal bearingY. + /// The horizontal advance. + public GlyphMetrics(float width, float height, float bearingX, float bearingY, float advance) + { + m_Width = width; + m_Height = height; + m_HorizontalBearingX = bearingX; + m_HorizontalBearingY = bearingY; + m_HorizontalAdvance = advance; + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } + + public override bool Equals(object obj) + { + return base.Equals(obj); + } + + public bool Equals(GlyphMetrics other) + { + return base.Equals(other); + } + public static bool operator==(GlyphMetrics lhs, GlyphMetrics rhs) + { + return lhs.width == rhs.width && + lhs.height == rhs.height && + lhs.horizontalBearingX == rhs.horizontalBearingX && + lhs.horizontalBearingY == rhs.horizontalBearingY && + lhs.horizontalAdvance == rhs.horizontalAdvance; + } - // ======================= - // Font Atlas Information - // ======================= + public static bool operator!=(GlyphMetrics lhs, GlyphMetrics rhs) + { + return !(lhs == rhs); + } + } + /// + /// A Glyph is the visual representation of a text element or character. + /// + [Serializable] + [UsedByNativeCode] + [StructLayout(LayoutKind.Sequential)] + public class Glyph + { /// - /// The index of the atlas texture that contains this glyph. + /// The index of the glyph in the source font file. /// - public int atlasIndex; + public uint index { get { return m_Index; } set { m_Index = value; } } /// - /// The x position of the glyph in the font atlas texture + /// The metrics that define the size, position and spacing of a glyph when performing text layout. /// - //public int x { get { return m_XMin; } set { m_XMin = value; } } - //[SerializeField] - //[NativeName("x")] - //private int m_XMin; + public GlyphMetrics metrics { get { return m_Metrics; } set { m_Metrics = value; } } /// - /// The y position of the glyph in the font atlas texture. + /// A rectangle that defines the position of a glyph within an atlas texture. /// - //public int y { get { return m_YMin; } set { m_YMin = value; } } - //[SerializeField] - //[NativeName("y")] - //private int m_YMin; + public GlyphRect glyphRect { get { return m_GlyphRect; } set { m_GlyphRect = value; } } /// - /// A Rect that contains the uv coordinates of the glyph in the atlas texture. These values correspond to the xMin, yMin, xMax, yMax positions. + /// The relative scale of the glyph. The default value is 1.0. /// - //public Vector4 uv; + public float scale { get { return m_Scale; } set { m_Scale = value; } } /// - /// The UV coordinate corresponding to the bottom left of the glyph in texture space. + /// The index of the atlas texture that contains this glyph. /// - //public Vector2 uv0 { get { return new Vector2(uv.xMin, uv.yMin); } } + public int atlasIndex { get { return m_AtlasIndex; } set { m_AtlasIndex = value; } } + + // ============================================= + // Private backing fields for public properties. + // ============================================= + + [SerializeField] + [NativeName("index")] + private uint m_Index; + + [SerializeField] + [NativeName("metrics")] + private GlyphMetrics m_Metrics; + + [SerializeField] + [NativeName("glyphRect")] + private GlyphRect m_GlyphRect; + + [SerializeField] + [NativeName("scale")] + private float m_Scale; + + [SerializeField] + [NativeName("atlasIndex")] + private int m_AtlasIndex; /// - /// The UV coordinate corresponding to the top left of the glyph in texture space. + /// Constructor for a new glyph. /// - //public Vector2 uv1 { get { return new Vector2(uv.xMin, uv.yMax); } } + public Glyph() + { + m_Index = 0; + m_Metrics = new GlyphMetrics(); + m_GlyphRect = new GlyphRect(); + m_Scale = 1; + m_AtlasIndex = 0; + } /// - /// The UV coordinate corresponding to the top right of the glyph in texture space. + /// Constructor for a new glyph /// - //public Vector2 uv2 { get { return new Vector2(uv.xMax, uv.yMax); } } + /// Glyph whose values are copied to the new glyph. + public Glyph(Glyph glyph) + { + m_Index = glyph.index; + m_Metrics = glyph.metrics; + m_GlyphRect = glyph.glyphRect; + m_Scale = glyph.scale; + m_AtlasIndex = glyph.atlasIndex; + } /// - /// The UV coordinate corresponding to the bottom right of the glyph in texture space. + /// Constructor for a new glyph /// - //public Vector2 uv3 { get { return new Vector2(uv.xMax, uv.yMin); } } + /// Glyph whose values are copied to the new glyph. + internal Glyph(GlyphMarshallingStruct glyphStruct) + { + m_Index = glyphStruct.index; + m_Metrics = glyphStruct.metrics; + m_GlyphRect = glyphStruct.glyphRect; + m_Scale = glyphStruct.scale; + m_AtlasIndex = glyphStruct.atlasIndex; + } /// - /// Set the uv coordinates of the glyph in the atlas texture. + /// Constructor for new glyph. + /// The scale will be set to a value of 1.0 and atlas index to 0. /// - /// The x position of the glyph in the atlas texture. - /// The y position of the glyph in the atlas texture. - /// The width of the atlas texture. - /// The height of the atlas texture. - //public void SetUV(int x, int y, int texWidth, int texHeight) - //{ - // uv.xMin = x / texWidth; - // uv.xMax = uv.xMin + m_Width / texWidth; - - // uv.xMin = y / texHeight; - // uv.yMax = uv.yMin + m_Height / texHeight; - //} + /// The index of the glyph in the font file. + /// The metrics of the glyph. + /// The GlyphRect defining the position of the glyph in the atlas texture. + public Glyph(uint index, GlyphMetrics metrics, GlyphRect glyphRect) + { + m_Index = index; + m_Metrics = metrics; + m_GlyphRect = glyphRect; + m_Scale = 1; + m_AtlasIndex = 0; + } + + /// + /// Constructor for new glyph. + /// + /// The index of the glyph in the font file. + /// The metrics of the glyph. + /// The GlyphRect defining the position of the glyph in the atlas texture. + /// The relative scale of the glyph. + /// The index of the atlas texture that contains the glyph. + public Glyph(uint index, GlyphMetrics metrics, GlyphRect glyphRect, float scale, int atlasIndex) + { + m_Index = index; + m_Metrics = metrics; + m_GlyphRect = glyphRect; + m_Scale = scale; + m_AtlasIndex = atlasIndex; + } + + /// + /// Compares two glyphs to determine if they have the same values. + /// + /// The glyph to compare with. + /// Returns true if the glyphs have the same values. False if not. + public bool Compare(Glyph other) + { + return index == other.index && + metrics == other.metrics && + glyphRect == other.glyphRect && + scale == other.scale && + atlasIndex == other.atlasIndex; + } } } diff --git a/Modules/TextCore/ScriptBindings/FontEngine.bindings.cs b/Modules/TextCore/ScriptBindings/FontEngine.bindings.cs index b0b99f22f0..d886798a11 100644 --- a/Modules/TextCore/ScriptBindings/FontEngine.bindings.cs +++ b/Modules/TextCore/ScriptBindings/FontEngine.bindings.cs @@ -2,6 +2,7 @@ // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License +using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine.Scripting; using UnityEngine.Bindings; @@ -27,12 +28,11 @@ public enum GlyphLoadFlags //LOAD_LINEAR_DESIGN = 1 << 13, LOAD_NO_AUTOHINT = 1 << 15, /* Bits 16-19 are used by `LOAD_TARGET_' */ - LOAD_COLOR = 1 << 20, + //LOAD_COLOR = 1 << 20, LOAD_COMPUTE_METRICS = 1 << 21, LOAD_BITMAP_METRICS_ONLY = 1 << 22 } - /// /// Rasterizing modes used by the Font Engine to raster glyphs. /// @@ -71,21 +71,33 @@ public enum FontEngineError Invalid_File_Path = 0x1, Invalid_File_Format = 0x2, Invalid_File_Structure = 0x3, + Invalid_File = 0x4, // Glyph related errors. Invalid_Glyph_Index = 0x10, Invalid_Character_Code = 0x11, Invalid_Pixel_Size = 0x17, + // + Invalid_Library = 0x21, + + // Font face related errors. + Invalid_Face = 0x23, + + Invalid_Library_or_Face = 0x29, + + // Font atlas generation and glyph rendering related errors. + Atlas_Generation_Cancelled = 0x64, + Invalid_SharedTextureData = 0x65, + // Additional errors codes will be added as necessary to cover new FontEngine features and functionality. } - /// /// Rendering modes used by the Font Engine to render glyphs. /// [UsedByNativeCode] - public enum GlyphRenderModes + public enum GlyphRenderMode { SMOOTH_HINTED = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X, SMOOTH = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X, @@ -98,17 +110,38 @@ public enum GlyphRenderModes SDF16 = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_SDF | GlyphRasterModes.RASTER_MODE_16X, SDF32 = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_SDF | GlyphRasterModes.RASTER_MODE_32X, - SDFAA = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_SDFAA | GlyphRasterModes.RASTER_MODE_1X, + SDFAA_HINTED = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_SDFAA | GlyphRasterModes.RASTER_MODE_1X, + SDFAA = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_SDFAA | GlyphRasterModes.RASTER_MODE_1X, //MSDF = RasterModes.RASTER_MODE_HINTED | RasterModes.RASTER_MODE_8BIT | RasterModes.RASTER_MODE_MSDF | RasterModes.RASTER_MODE_1X, //MSDFA = RasterModes.RASTER_MODE_HINTED | RasterModes.RASTER_MODE_8BIT | RasterModes.RASTER_MODE_MSDFA | RasterModes.RASTER_MODE_1X, } + /// + /// The modes available when packing glyphs into an atlas texture. + /// + [UsedByNativeCode] + public enum GlyphPackingMode + { + BestShortSideFit = 0x0, + BestLongSideFit = 0x1, + BestAreaFit = 0x2, + BottomLeftRule = 0x3, + ContactPointRule = 0x4, + } - [NativeHeader("Modules/TextCore/Native/FontEngine.h")] + [NativeHeader("Modules/TextCore/Native/FontEngine/FontEngine.h")] public sealed class FontEngine { private static readonly FontEngine s_Instance = new FontEngine(); + private static GlyphMarshallingStruct[] s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[16]; + private static GlyphMarshallingStruct[] s_GlyphMarshallingStruct_OUT = new GlyphMarshallingStruct[16]; + + private static GlyphRect[] s_FreeGlyphRects = new GlyphRect[16]; + private static GlyphRect[] s_UsedGlyphRects = new GlyphRect[16]; + + private static Dictionary s_GlyphLookupDictionary = new Dictionary(); + internal FontEngine() {} /// @@ -144,6 +177,38 @@ public static FontEngineError DestroyFontEngine() [NativeMethod(Name = "TextCore::FontEngine::DestroyFontEngine", IsFreeFunction = true)] static extern int DestroyFontEngine_Internal(); + /// + /// Force the cancellation of any atlas or glyph rendering process. + /// Used primarily by the Font Asset Creator. + /// + internal static void SendCancellationRequest() + { + SendCancellationRequest_Internal(); + } + + [NativeMethod(Name = "TextCore::FontEngine::SendCancellationRequest", IsFreeFunction = true)] + static extern void SendCancellationRequest_Internal(); + + /// + /// Determines if the font engine is currently in the process of rendering and adding glyphs into an atlas texture. + /// Used primarily by the Font Asset Creator. + /// + internal static extern bool isProcessingDone + { + [NativeMethod(Name = "TextCore::FontEngine::GetIsProcessingDone", IsFreeFunction = true)] + get; + } + + /// + /// Returns the generation progress on glyph packing and rendering. + /// Used primarily by the Font Asset Creator. + /// + internal static extern float generationProgress + { + [NativeMethod(Name = "TextCore::FontEngine::GetGenerationProgress", IsFreeFunction = true)] + get; + } + /// /// Load the source font file at the given file path. /// @@ -180,6 +245,9 @@ public static FontEngineError LoadFontFace(string filePath, int pointSize) /// Returns a value of zero if the font face was loaded successfully. public static FontEngineError LoadFontFace(byte[] sourceFontFile) { + if (sourceFontFile.Length == 0) + return FontEngineError.Invalid_File; + return (FontEngineError)LoadFontFace_FromSourceFontFile_Internal(sourceFontFile); } @@ -195,6 +263,9 @@ public static FontEngineError LoadFontFace(byte[] sourceFontFile) /// Returns a value of zero if the font face was loaded successfully. public static FontEngineError LoadFontFace(byte[] sourceFontFile, int pointSize) { + if (sourceFontFile.Length == 0) + return FontEngineError.Invalid_File; + return (FontEngineError)LoadFontFace_With_Size_FromSourceFontFile_Internal(sourceFontFile, pointSize); } @@ -202,6 +273,35 @@ public static FontEngineError LoadFontFace(byte[] sourceFontFile, int pointSize) static extern int LoadFontFace_With_Size_FromSourceFontFile_Internal(byte[] sourceFontFile, int pointSize); + /// + /// Load the font file from the Unity font's internal font data. Note the Unity font must be set to Dynamic with Include Font Data enabled. + /// + /// The font from which to load the data. + /// Returns a value of zero if the font face was loaded successfully. + public static FontEngineError LoadFontFace(Font font) + { + return (FontEngineError)LoadFontFace_FromFont_Internal(font); + } + + [NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)] + static extern int LoadFontFace_FromFont_Internal(Font font); + + + /// + /// Load the font file from the Unity font's internal font data. Note the Unity font must be set to Dynamic with Include Font Data enabled. + /// + /// The font from which to load the data. + /// The point size used to scale the font face. + /// Returns a value of zero if the font face was loaded successfully. + public static FontEngineError LoadFontFace(Font font, int pointSize) + { + return (FontEngineError)LoadFontFace_With_Size_FromFont_Internal(font, pointSize); + } + + [NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)] + static extern int LoadFontFace_With_Size_FromFont_Internal(Font font, int pointSize); + + /// /// Set the size of the currently loaded font face. /// @@ -212,17 +312,44 @@ public static FontEngineError SetFaceSize(int pointSize) return (FontEngineError)SetFaceSize_Internal(pointSize); } - [NativeMethod(Name = "TextCore::FontEngine::SetFaceSize", IsFreeFunction = true)] + [NativeMethod(Name = "TextCore::FontEngine::SetFaceSize", IsThreadSafe = true, IsFreeFunction = true)] static extern int SetFaceSize_Internal(int pointSize); + /// + /// Get information about the currently loaded and sized font face. + /// + /// Returns the FaceInfo of the currently loaded font face. + public static FaceInfo GetFaceInfo() + { + FaceInfo faceInfo = new FaceInfo(); + + GetFaceInfo_Internal(ref faceInfo); + + return faceInfo; + } + + [NativeMethod(Name = "TextCore::FontEngine::GetFaceInfo", IsThreadSafe = true, IsFreeFunction = true)] + static extern int GetFaceInfo_Internal(ref FaceInfo faceInfo); + + /// /// Get the index of the glyph for the character mapped at Unicode value. /// /// The Unicode value of the character for which to lookup the glyph index. /// Returns the index of the glyph used by the character using the Unicode value. Returns zero if no glyph exists for the given Unicode value. - [NativeMethod(Name = "TextCore::FontEngine::GetGlyphIndex", IsFreeFunction = true)] - public static extern int GetGlyphIndex(uint unicode); + [NativeMethod(Name = "TextCore::FontEngine::GetGlyphIndex", IsThreadSafe = true, IsFreeFunction = true)] + internal static extern uint GetGlyphIndex(uint unicode); + + + /// + /// Try to get the glyph index for the character at the given Unicode value. + /// + /// The unicode value of the character for which to lookup the glyph index. + /// The index of the glyph for the given unicode character or the .notdef glyph (index 0) if no glyph is available for the given Unicode value. + /// Returns true if the given unicode has a glyph index. + [NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphIndex", IsThreadSafe = true, IsFreeFunction = true)] + public static extern bool TryGetGlyphIndex(uint unicode, out uint glyphIndex); /// @@ -236,7 +363,7 @@ internal static FontEngineError LoadGlyph(uint unicode, GlyphLoadFlags flags) return (FontEngineError)LoadGlyph_Internal(unicode, flags); } - [NativeMethod(Name = "TextCore::FontEngine::LoadGlyph", IsFreeFunction = true)] + [NativeMethod(Name = "TextCore::FontEngine::LoadGlyph", IsThreadSafe = true, IsFreeFunction = true)] static extern int LoadGlyph_Internal(uint unicode, GlyphLoadFlags loadFlags); @@ -249,13 +376,23 @@ internal static FontEngineError LoadGlyph(uint unicode, GlyphLoadFlags flags) /// Returns true if a glyph exists for the given unicode value. Otherwise returns false. public static bool TryGetGlyphWithUnicodeValue(uint unicode, GlyphLoadFlags flags, out Glyph glyph) { - glyph = new Glyph(); + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(); + + if (TryGetGlyphWithUnicodeValue_Internal(unicode, flags, ref glyphStruct)) + { + glyph = new Glyph(glyphStruct); + + return true; + } + + // Set glyph to null if no glyph exists for the given unicode value. + glyph = null; - return TryGetGlyphWithUnicodeValue_Internal(unicode, flags, glyph); + return false; } - [NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphWithUnicodeValue", IsFreeFunction = true)] - static extern bool TryGetGlyphWithUnicodeValue_Internal(uint unicode, GlyphLoadFlags loadFlags, [Out] Glyph glyph); + [NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphWithUnicodeValue", IsThreadSafe = true, IsFreeFunction = true)] + static extern bool TryGetGlyphWithUnicodeValue_Internal(uint unicode, GlyphLoadFlags loadFlags, ref GlyphMarshallingStruct glyphStruct); /// @@ -267,46 +404,485 @@ public static bool TryGetGlyphWithUnicodeValue(uint unicode, GlyphLoadFlags flag /// Returns true if a glyph exists at the given index. Otherwise returns false. public static bool TryGetGlyphWithIndexValue(uint glyphIndex, GlyphLoadFlags flags, out Glyph glyph) { - glyph = new Glyph(); + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(); + + if (TryGetGlyphWithIndexValue_Internal(glyphIndex, flags, ref glyphStruct)) + { + glyph = new Glyph(glyphStruct); + + return true; + } + + // Set glyph to null if no glyph exists for the given unicode value. + glyph = null; + + return false; + } - return TryGetGlyphWithIndexValue_Internal(glyphIndex, flags, glyph); + [NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphWithIndexValue", IsThreadSafe = true, IsFreeFunction = true)] + static extern bool TryGetGlyphWithIndexValue_Internal(uint glyphIndex, GlyphLoadFlags loadFlags, ref GlyphMarshallingStruct glyphStruct); + + + /// + /// Try to pack the given glyph into the given texture width and height. + /// + /// The glyph to try to pack. + /// The padding between this glyph and other glyphs. + /// The packing algorithm used to pack the glyphs. + /// The glyph rendering mode. + /// The width of the target atlas texture. + /// The height of the target atlas texture. + /// List of GlyphRects representing the available space in the atlas. + /// List of GlyphRects representing the occupied space in the atlas. + /// + internal static bool TryPackGlyphInAtlas(Glyph glyph, int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height, List freeGlyphRects, List usedGlyphRects) + { + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyph); + + int freeGlyphRectCount = freeGlyphRects.Count; + int usedGlyphRectCount = usedGlyphRects.Count; + int totalGlyphRects = freeGlyphRectCount + usedGlyphRectCount; + + // Make sure marshalling arrays allocations are appropriate. + if (s_FreeGlyphRects.Length < totalGlyphRects || s_UsedGlyphRects.Length < totalGlyphRects) + { + int newSize = Mathf.NextPowerOfTwo(totalGlyphRects + 1); + s_FreeGlyphRects = new GlyphRect[newSize]; + s_UsedGlyphRects = new GlyphRect[newSize]; + } + + // Copy glyph rect data to marshalling arrays. + int glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount); + for (int i = 0; i < glyphRectCount; i++) + { + if (i < freeGlyphRectCount) + s_FreeGlyphRects[i] = freeGlyphRects[i]; + + if (i < usedGlyphRectCount) + s_UsedGlyphRects[i] = usedGlyphRects[i]; + } + + if (TryPackGlyphInAtlas_Internal(ref glyphStruct, padding, packingMode, renderMode, width, height, s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount)) + { + // Copy new glyph position to source glyph. + glyph.glyphRect = glyphStruct.glyphRect; + + freeGlyphRects.Clear(); + usedGlyphRects.Clear(); + + // Copy marshalled glyph rect data + glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount); + for (int i = 0; i < glyphRectCount; i++) + { + if (i < freeGlyphRectCount) + freeGlyphRects.Add(s_FreeGlyphRects[i]); + + if (i < usedGlyphRectCount) + usedGlyphRects.Add(s_UsedGlyphRects[i]); + } + + return true; + } + + return false; } - [NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphWithIndexValue", IsFreeFunction = true)] - static extern bool TryGetGlyphWithIndexValue_Internal(uint glyphIndex, GlyphLoadFlags loadFlags, [Out] Glyph glyph); + [NativeMethod(Name = "TextCore::FontEngine::TryPackGlyph", IsThreadSafe = true, IsFreeFunction = true)] + extern static bool TryPackGlyphInAtlas_Internal(ref GlyphMarshallingStruct glyph, int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height, + [Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount); /// - /// Try rasterizing and adding the given glyph to the provided texture. + /// Pack glyphs in the given atlas size. + /// + /// Glyphs to pack in atlas. + /// Glyphs packed in atlas. + /// The padding between glyphs. + /// The packing algorithm used to pack the glyphs. + /// The glyph rendering mode. + /// The width of the target atlas texture. + /// The height of the target atlas texture. + /// List of GlyphRects representing the available space in the atlas. + /// List of GlyphRects representing the occupied space in the atlas. + /// + internal static bool TryPackGlyphsInAtlas(List glyphsToAdd, List glyphsAdded, int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height, List freeGlyphRects, List usedGlyphRects) + { + // Determine potential total allocations required for glyphs and glyph rectangles. + int glyphsToAddCount = glyphsToAdd.Count; + int glyphsAddedCount = glyphsAdded.Count; + int freeGlyphRectCount = freeGlyphRects.Count; + int usedGlyphRectCount = usedGlyphRects.Count; + int totalCount = glyphsToAddCount + glyphsAddedCount + freeGlyphRectCount + usedGlyphRectCount; + + // Make sure marshaling arrays allocations are appropriate. + if (s_GlyphMarshallingStruct_IN.Length < totalCount || s_GlyphMarshallingStruct_OUT.Length < totalCount || s_FreeGlyphRects.Length < totalCount || s_UsedGlyphRects.Length < totalCount) + { + int newSize = Mathf.NextPowerOfTwo(totalCount + 1); + s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize]; + s_GlyphMarshallingStruct_OUT = new GlyphMarshallingStruct[newSize]; + s_FreeGlyphRects = new GlyphRect[newSize]; + s_UsedGlyphRects = new GlyphRect[newSize]; + } + + s_GlyphLookupDictionary.Clear(); + + // Copy glyph data into appropriate marshaling array. + for (int i = 0; i < totalCount; i++) + { + if (i < glyphsToAddCount) + { + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyphsToAdd[i]); + + s_GlyphMarshallingStruct_IN[i] = glyphStruct; + + // Add reference to glyph in lookup dictionary + if (s_GlyphLookupDictionary.ContainsKey(glyphStruct.index) == false) + s_GlyphLookupDictionary.Add(glyphStruct.index, glyphsToAdd[i]); + } + + if (i < glyphsAddedCount) + { + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyphsAdded[i]); + + s_GlyphMarshallingStruct_OUT[i] = glyphStruct; + + // Add reference to glyph in lookup dictionary + if (s_GlyphLookupDictionary.ContainsKey(glyphStruct.index) == false) + s_GlyphLookupDictionary.Add(glyphStruct.index, glyphsAdded[i]); + } + + if (i < freeGlyphRectCount) + s_FreeGlyphRects[i] = freeGlyphRects[i]; + + if (i < usedGlyphRectCount) + s_UsedGlyphRects[i] = usedGlyphRects[i]; + } + + bool allGlyphsIncluded = TryPackGlyphsInAtlas_Internal(s_GlyphMarshallingStruct_IN, ref glyphsToAddCount, s_GlyphMarshallingStruct_OUT, ref glyphsAddedCount, + padding, packingMode, renderMode, width, height, + s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount); + + // Clear lists and / or re-allocate arrays. + glyphsToAdd.Clear(); + glyphsAdded.Clear(); + freeGlyphRects.Clear(); + usedGlyphRects.Clear(); + + // Copy marshaled glyph data back into the appropriate lists. + for (int i = 0; i < totalCount; i++) + { + if (i < glyphsToAddCount) + { + GlyphMarshallingStruct glyphStruct = s_GlyphMarshallingStruct_IN[i]; + Glyph glyph = s_GlyphLookupDictionary[glyphStruct.index]; + + // Note: In theory, only new glyphRect x and y need to be copied. + glyph.metrics = glyphStruct.metrics; + glyph.glyphRect = glyphStruct.glyphRect; + glyph.scale = glyphStruct.scale; + glyph.atlasIndex = glyphStruct.atlasIndex; + + glyphsToAdd.Add(glyph); + } + + if (i < glyphsAddedCount) + { + GlyphMarshallingStruct glyphStruct = s_GlyphMarshallingStruct_OUT[i]; + Glyph glyph = s_GlyphLookupDictionary[glyphStruct.index]; + + glyph.metrics = glyphStruct.metrics; + glyph.glyphRect = glyphStruct.glyphRect; + glyph.scale = glyphStruct.scale; + glyph.atlasIndex = glyphStruct.atlasIndex; + + glyphsAdded.Add(glyph); + } + + if (i < freeGlyphRectCount) + { + freeGlyphRects.Add(s_FreeGlyphRects[i]); + } + + if (i < usedGlyphRectCount) + { + usedGlyphRects.Add(s_UsedGlyphRects[i]); + } + } + + return allGlyphsIncluded; + } + + [NativeMethod(Name = "TextCore::FontEngine::TryPackGlyphs", IsThreadSafe = true, IsFreeFunction = true)] + extern static bool TryPackGlyphsInAtlas_Internal([Out] GlyphMarshallingStruct[] glyphsToAdd, ref int glyphsToAddCount, [Out] GlyphMarshallingStruct[] glyphsAdded, ref int glyphsAddedCount, + int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height, + [Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount); + + + /// + /// Render and add glyph to the provided texture. /// /// The Glyph that should be added into the provided texture. /// The padding value around the glyph. /// The Rendering Mode for the Glyph. /// The Texture to which the glyph should be added. /// Returns a value of zero if the glyph was successfully added to the texture. - public static FontEngineError AddGlyphToTexture(Glyph glyph, int padding, GlyphRenderModes renderMode, Texture2D texture) + internal static FontEngineError RenderGlyphToTexture(Glyph glyph, int padding, GlyphRenderMode renderMode, Texture2D texture) { - return (FontEngineError)AddGlyphToTexture_Internal(glyph, padding, renderMode, texture); + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyph); + + return (FontEngineError)RenderGlyphToTexture_Internal(glyphStruct, padding, renderMode, texture); } - [NativeMethod(Name = "TextCore::FontEngine::AddGlyphToTexture", IsFreeFunction = true)] - extern static int AddGlyphToTexture_Internal(Glyph glyph, int padding, GlyphRenderModes renderMode, Texture2D texture); + [NativeMethod(Name = "TextCore::FontEngine::RenderGlyphToTexture", IsFreeFunction = true)] + extern static int RenderGlyphToTexture_Internal(GlyphMarshallingStruct glyphStruct, int padding, GlyphRenderMode renderMode, Texture2D texture); /// - /// Try rasterizing and adding the given list of glyphs to the provided texture. + /// Render and add the glyphs in the provided list to the texture. /// - /// The list of glyphs to be added into the provided texture. + /// The list of glyphs to be rendered and added to the provided texture. /// The padding value around the glyphs. - /// The rendering mode used rasterize the glyphs. + /// The rendering mode used to rasterize the glyphs. /// Returns a value of zero if the glyphs were successfully added to the texture. /// - public static FontEngineError AddGlyphsToTexture(Glyph[] glyphs, int padding, GlyphRenderModes renderMode, Texture2D texture) + internal static FontEngineError RenderGlyphsToTexture(List glyphs, int padding, GlyphRenderMode renderMode, Texture2D texture) { - return (FontEngineError)AddGlyphsToTextureFromArray_Internal(glyphs, padding, renderMode, texture); + int glyphCount = glyphs.Count; + + // Make sure marshaling arrays allocations are appropriate. + if (s_GlyphMarshallingStruct_IN.Length < glyphCount) + { + int newSize = Mathf.NextPowerOfTwo(glyphCount + 1); + s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize]; + } + + // Copy data to marshalling buffers + for (int i = 0; i < glyphCount; i++) + s_GlyphMarshallingStruct_IN[i] = new GlyphMarshallingStruct(glyphs[i]); + + // Call extern function to render and add glyphs to texture. + int error = RenderGlyphsToTexture_Internal(s_GlyphMarshallingStruct_IN, glyphCount, padding, renderMode, texture); + + return (FontEngineError)error; } - [NativeMethod(Name = "TextCore::FontEngine::AddGlyphsToTexture", IsFreeFunction = true)] - extern static int AddGlyphsToTextureFromArray_Internal(Glyph[] glyphs, int padding, GlyphRenderModes renderMode, Texture2D texture); + [NativeMethod(Name = "TextCore::FontEngine::RenderGlyphsToTexture", IsFreeFunction = true)] + extern static int RenderGlyphsToTexture_Internal(GlyphMarshallingStruct[] glyphs, int glyphCount, int padding, GlyphRenderMode renderMode, Texture2D texture); + + + internal static FontEngineError RenderGlyphsToTexture(List glyphs, int padding, GlyphRenderMode renderMode, byte[] texBuffer, int texWidth, int texHeight) + { + int glyphCount = glyphs.Count; + + // Make sure marshaling arrays allocations are appropriate. + if (s_GlyphMarshallingStruct_IN.Length < glyphCount) + { + int newSize = Mathf.NextPowerOfTwo(glyphCount + 1); + s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize]; + } + + // Copy data to marshalling buffers + for (int i = 0; i < glyphCount; i++) + s_GlyphMarshallingStruct_IN[i] = new GlyphMarshallingStruct(glyphs[i]); + + int error = RenderGlyphsToTextureBuffer_Internal(s_GlyphMarshallingStruct_IN, glyphCount, padding, renderMode, texBuffer, texWidth, texHeight); + + return (FontEngineError)error; + } + + [NativeMethod(Name = "TextCore::FontEngine::RenderGlyphsToTextureBuffer", IsThreadSafe = true, IsFreeFunction = true)] + extern static int RenderGlyphsToTextureBuffer_Internal(GlyphMarshallingStruct[] glyphs, int glyphCount, int padding, GlyphRenderMode renderMode, [Out] byte[] texBuffer, int texWidth, int texHeight); + + + /// + /// Internal function used to render and add glyphs to the cached shared texture data from outside the main thread. + /// It is necessary to use SetSharedTextureData(texture) prior to calling this function. + /// + /// The list of glyphs to be added into the provided texture. + /// The padding value around the glyphs. + /// The rendering mode used to rasterize the glyphs. + /// + internal static FontEngineError RenderGlyphsToSharedTexture(List glyphs, int padding, GlyphRenderMode renderMode) + { + int glyphCount = glyphs.Count; + + // Make sure marshaling arrays allocations are appropriate. + if (s_GlyphMarshallingStruct_IN.Length < glyphCount) + { + int newSize = Mathf.NextPowerOfTwo(glyphCount + 1); + s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize]; + } + + // Copy data to marshalling buffers + for (int i = 0; i < glyphCount; i++) + s_GlyphMarshallingStruct_IN[i] = new GlyphMarshallingStruct(glyphs[i]); + + int error = RenderGlyphsToSharedTexture_Internal(s_GlyphMarshallingStruct_IN, glyphCount, padding, renderMode); + + return (FontEngineError)error; + } + + [NativeMethod(Name = "TextCore::FontEngine::RenderGlyphsToSharedTexture", IsThreadSafe = true, IsFreeFunction = true)] + extern static int RenderGlyphsToSharedTexture_Internal(GlyphMarshallingStruct[] glyphs, int glyphCount, int padding, GlyphRenderMode renderMode); + + + /// + /// Internal function used to get a reference to the shared texture data which is required for accessing the texture data outside of the main thread. + /// + [NativeMethod(Name = "TextCore::FontEngine::SetSharedTextureData", IsFreeFunction = true)] + internal extern static void SetSharedTexture(Texture2D texture); + + + /// + /// Internal function used to release the shared texture data. + /// + [NativeMethod(Name = "TextCore::FontEngine::ReleaseSharedTextureData", IsThreadSafe = true, IsFreeFunction = true)] + internal extern static void ReleaseSharedTexture(); + + + internal static bool TryAddGlyphToTexture(uint glyphIndex, int padding, GlyphPackingMode packingMode, List freeGlyphRects, List usedGlyphRects, GlyphRenderMode renderMode, Texture2D texture, out Glyph glyph) + { + // Determine potential total allocations required for glyphs and glyph rectangles. + int freeGlyphRectCount = freeGlyphRects.Count; + int usedGlyphRectCount = usedGlyphRects.Count; + int totalGlyphRects = freeGlyphRectCount + usedGlyphRectCount; + + // Make sure marshalling arrays allocations are appropriate. + if (s_FreeGlyphRects.Length < totalGlyphRects || s_UsedGlyphRects.Length < totalGlyphRects) + { + int newSize = Mathf.NextPowerOfTwo(totalGlyphRects + 1); + s_FreeGlyphRects = new GlyphRect[newSize]; + s_UsedGlyphRects = new GlyphRect[newSize]; + } + + // Copy glyph rect data to marshalling arrays. + int glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount); + for (int i = 0; i < glyphRectCount; i++) + { + if (i < freeGlyphRectCount) + s_FreeGlyphRects[i] = freeGlyphRects[i]; + + if (i < usedGlyphRectCount) + s_UsedGlyphRects[i] = usedGlyphRects[i]; + } + + GlyphMarshallingStruct glyphStruct; + + // Marshall data over to the native side. + if (TryAddGlyphToTexture_Internal(glyphIndex, padding, packingMode, s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount, renderMode, texture, out glyphStruct)) + { + // Copy marshalled data over to new glyph. + glyph = new Glyph(glyphStruct); + + freeGlyphRects.Clear(); + usedGlyphRects.Clear(); + + // Copy marshalled free and used GlyphRect data over. + glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount); + for (int i = 0; i < glyphRectCount; i++) + { + if (i < freeGlyphRectCount) + freeGlyphRects.Add(s_FreeGlyphRects[i]); + + if (i < usedGlyphRectCount) + usedGlyphRects.Add(s_UsedGlyphRects[i]); + } + + return true; + } + + glyph = null; + + return false; + } + + [NativeMethod(Name = "TextCore::FontEngine::TryAddGlyphToTexture", IsThreadSafe = true, IsFreeFunction = true)] + extern static bool TryAddGlyphToTexture_Internal(uint glyphIndex, int padding, + GlyphPackingMode packingMode, [Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount, + GlyphRenderMode renderMode, Texture2D texture, out GlyphMarshallingStruct glyph); + + + /// + /// + /// + [NativeMethod(Name = "TextCore::FontEngine::GetGlyphPairAdjustmentTable", IsFreeFunction = true)] + internal extern static void GetGlyphPairAdjustmentTable(); + + // ================================================ + // Experimental / Testing / Benchmarking Functions + // ================================================ + + /// + /// Internal function used for testing rasterizing of shapes and glyphs. + /// + /// Texture containing the source shape to raster. + /// Padding value. + /// The rendering mode. + /// Texture containing the rastered shape. + [NativeMethod(Name = "TextCore::FontEngine::RenderToTexture", IsFreeFunction = true)] + internal extern static void RenderBufferToTexture(Texture2D srcTexture, int padding, GlyphRenderMode renderMode, Texture2D dstTexture); + + /* + [NativeMethod(Name = "TextCore::FontEngine::ModifyGlyph", IsFreeFunction = true)] + extern public static void ModifyGlyph([Out] Glyph glyph); + + /// + /// + /// + /// + public static void ModifyGlyphStruct(Glyph glyph) + { + GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyph); + + ModifyGlyph_Internal(ref glyphStruct); + + glyph.metrics = glyphStruct.metrics; + glyph.glyphRect = glyphStruct.glyphRect; + glyph.scale = glyphStruct.scale; + glyph.atlasIndex = glyphStruct.atlasIndex; + } + + [NativeMethod(Name = "TextCore::FontEngine::ModifyGlyph", IsThreadSafe = true, IsFreeFunction = true)] + extern static void ModifyGlyph_Internal(ref GlyphMarshallingStruct glyphs); + + /// + /// + /// + /// + [NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphMarshallingStruct", IsFreeFunction = true)] + extern public static void ModifyGlyphMarshallingStruct(GlyphMarshallingStruct[] glyph); + + /// + /// + /// + /// + [NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphMarshallingStruct", IsFreeFunction = true)] + extern public static void ModifyGlyphMarshallingStructArray(GlyphMarshallingStruct[] glyph); + + /// + /// + /// + /// + [NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphs", IsFreeFunction = true)] + extern public static void ModifyGlyphStructArray([Out] GlyphMarshallingStruct[] glyph); + + /// + /// + /// + /// + [NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphs", IsFreeFunction = true)] + extern public static void ModifyGlyphArray([Out] Glyph[] glyph); + + [NativeMethod(Name = "TextCore::FontEngine::AccessFont", IsFreeFunction = true)] + extern public static void AccessFont(Font font); + */ + } + + internal struct FontEngineUtilities + { + internal static bool Approximately(float a, float b) + { + return Mathf.Abs(a - b) < 0.001f; + } } } diff --git a/Modules/TextCore/ScriptBindings/GlyphMarshallingStruct.cs b/Modules/TextCore/ScriptBindings/GlyphMarshallingStruct.cs new file mode 100644 index 0000000000..f293121789 --- /dev/null +++ b/Modules/TextCore/ScriptBindings/GlyphMarshallingStruct.cs @@ -0,0 +1,74 @@ +// Unity C# reference source +// Copyright (c) Unity Technologies. For terms of use, see +// https://unity3d.com/legal/licenses/Unity_Reference_Only_License + +using System.Runtime.InteropServices; +using UnityEngine.Bindings; +using UnityEngine.Scripting; + + +namespace UnityEngine.TextCore.LowLevel +{ + /// + /// Structure used for marshalling glyphs between managed and native code. + /// + [UsedByNativeCode] + [StructLayout(LayoutKind.Sequential)] + internal struct GlyphMarshallingStruct + { + /// + /// The index of the glyph in the source font file. + /// + public uint index; + + /// + /// Metrics defining the size, positioning and spacing of a glyph when doing text layout. + /// + public GlyphMetrics metrics; + + /// + /// A rectangle that defines the position of a glyph within an atlas texture. + /// + public GlyphRect glyphRect; + + /// + /// The relative scale of the text element. The default value is 1.0. + /// + public float scale; + + /// + /// The index of the atlas texture that contains this glyph. + /// + public int atlasIndex; + + /// + /// Constructor for a new glyph + /// + /// Glyph whose values are copied to the new glyph. + public GlyphMarshallingStruct(Glyph glyph) + { + this.index = glyph.index; + this.metrics = glyph.metrics; + this.glyphRect = glyph.glyphRect; + this.scale = glyph.scale; + this.atlasIndex = glyph.atlasIndex; + } + + /// + /// Constructor for new glyph + /// + /// The index of the glyph in the font file. + /// The metrics of the glyph. + /// A rectangle defining the position of the glyph in the atlas texture. + /// The relative scale of the glyph. + /// The index of the atlas texture that contains the glyph. + public GlyphMarshallingStruct(uint index, GlyphMetrics metrics, GlyphRect glyphRect, float scale, int atlasIndex) + { + this.index = index; + this.metrics = metrics; + this.glyphRect = glyphRect; + this.scale = scale; + this.atlasIndex = atlasIndex; + } + } +} diff --git a/Modules/TextRendering/FontStyle.cs b/Modules/TextRendering/FontStyle.cs deleted file mode 100644 index a66155853a..0000000000 --- a/Modules/TextRendering/FontStyle.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 System; - -namespace UnityEngine -{ - // Font Style applied to GUI Texts, Text Meshes or GUIStyles. - public enum FontStyle - { - // No special style is applied. - Normal = 0, - - // Bold style applied to your texts. - Bold = 1, - - // Italic style applied to your texts. - Italic = 2, - - // Bold and Italic styles applied to your texts. - BoldAndItalic = 3, - } -} diff --git a/Modules/TextRendering/TextRendering.bindings.cs b/Modules/TextRendering/TextRendering.bindings.cs index 63d1ff0d0b..d2d1875ef8 100644 --- a/Modules/TextRendering/TextRendering.bindings.cs +++ b/Modules/TextRendering/TextRendering.bindings.cs @@ -365,7 +365,14 @@ public static int GetMaxVertsForString(string str) } internal static extern Font GetDefault(); - public extern bool HasCharacter(char c); + + public bool HasCharacter(char c) + { + return HasCharacter((int)c); + } + + private extern bool HasCharacter(int c); + public static extern string[] GetOSInstalledFontNames(); private static extern void Internal_CreateFont([Writable] Font self, string name); diff --git a/Modules/Tilemap/Managed/CustomGridBrushAttribute.cs b/Modules/Tilemap/Managed/CustomGridBrushAttribute.cs deleted file mode 100644 index 7c59f107f4..0000000000 --- a/Modules/Tilemap/Managed/CustomGridBrushAttribute.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 System; - -namespace UnityEngine -{ - [AttributeUsage(AttributeTargets.Class)] - public class CustomGridBrushAttribute : Attribute - { - private bool m_HideAssetInstances; - private bool m_HideDefaultInstance; - private bool m_DefaultBrush; - private string m_DefaultName; - - public bool hideAssetInstances - { - get { return m_HideAssetInstances; } - } - - public bool hideDefaultInstance - { - get { return m_HideDefaultInstance; } - } - - public bool defaultBrush - { - get { return m_DefaultBrush; } - } - - public string defaultName - { - get { return m_DefaultName; } - } - - public CustomGridBrushAttribute() - { - m_HideAssetInstances = false; - m_HideDefaultInstance = false; - m_DefaultBrush = false; - m_DefaultName = ""; - } - - public CustomGridBrushAttribute(bool hideAssetInstances, bool hideDefaultInstance, bool defaultBrush, string defaultName) - { - this.m_HideAssetInstances = hideAssetInstances; - this.m_HideDefaultInstance = hideDefaultInstance; - this.m_DefaultBrush = defaultBrush; - this.m_DefaultName = defaultName; - } - } -} diff --git a/Modules/Tilemap/Managed/GridBrushBase.cs b/Modules/Tilemap/Managed/GridBrushBase.cs index 73c38221d0..9b7bf651bb 100644 --- a/Modules/Tilemap/Managed/GridBrushBase.cs +++ b/Modules/Tilemap/Managed/GridBrushBase.cs @@ -49,5 +49,8 @@ public virtual void Pick(GridLayout gridLayout, GameObject brushTarget, BoundsIn public virtual void Move(GridLayout gridLayout, GameObject brushTarget, BoundsInt from, BoundsInt to) {} public virtual void MoveStart(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) {} public virtual void MoveEnd(GridLayout gridLayout, GameObject brushTarget, BoundsInt position) {} + + public virtual void ChangeZPosition(int change) {} + public virtual void ResetZPosition() {} } } diff --git a/Modules/Tilemap/Managed/ITilemap.cs b/Modules/Tilemap/Managed/ITilemap.cs deleted file mode 100644 index e82a475e80..0000000000 --- a/Modules/Tilemap/Managed/ITilemap.cs +++ /dev/null @@ -1,79 +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.Scripting; - -namespace UnityEngine.Tilemaps -{ - [RequiredByNativeCode] - public class ITilemap - { - internal static ITilemap s_Instance; - internal Tilemap m_Tilemap; - - internal ITilemap() - { - } - - internal void SetTilemapInstance(Tilemap tilemap) - { - m_Tilemap = tilemap; - } - - // Tilemap - public Vector3Int origin { get { return m_Tilemap.origin; } } - public Vector3Int size { get { return m_Tilemap.size; } } - public Bounds localBounds { get { return m_Tilemap.localBounds; } } - public BoundsInt cellBounds { get { return m_Tilemap.cellBounds; } } - - // Tile - public virtual Sprite GetSprite(Vector3Int position) - { - return m_Tilemap.GetSprite(position); - } - - public virtual Color GetColor(Vector3Int position) - { - return m_Tilemap.GetColor(position); - } - - public virtual Matrix4x4 GetTransformMatrix(Vector3Int position) - { - return m_Tilemap.GetTransformMatrix(position); - } - - public virtual TileFlags GetTileFlags(Vector3Int position) - { - return m_Tilemap.GetTileFlags(position); - } - - // Tile Assets - public virtual TileBase GetTile(Vector3Int position) - { - return m_Tilemap.GetTile(position); - } - - public virtual T GetTile(Vector3Int position) where T : TileBase - { - return m_Tilemap.GetTile(position); - } - - public void RefreshTile(Vector3Int position) - { - m_Tilemap.RefreshTile(position); - } - - public T GetComponent() - { - return m_Tilemap.GetComponent(); - } - - [RequiredByNativeCode] - private static ITilemap CreateInstance() - { - s_Instance = new ITilemap(); - return s_Instance; - } - } -} diff --git a/Modules/Tilemap/Managed/Tile.cs b/Modules/Tilemap/Managed/Tile.cs deleted file mode 100644 index dfdd432d81..0000000000 --- a/Modules/Tilemap/Managed/Tile.cs +++ /dev/null @@ -1,49 +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 UnityEngine.Scripting; - -namespace UnityEngine.Tilemaps -{ - [Serializable] - [RequiredByNativeCode] - public class Tile : TileBase - { - public enum ColliderType { None = 0, Sprite = 1, Grid = 2 } - - public Sprite sprite { get { return m_Sprite; } set { m_Sprite = value; } } - public Color color { get { return m_Color; } set { m_Color = value; } } - public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } } - public GameObject gameObject { get { return m_InstancedGameObject; } set { m_InstancedGameObject = value; } } - public TileFlags flags { get { return m_Flags; } set { m_Flags = value; } } - public ColliderType colliderType { get { return m_ColliderType; } set { m_ColliderType = value; } } - - [SerializeField] - private Sprite m_Sprite; - [SerializeField] - private Color m_Color = Color.white; - [SerializeField] - private Matrix4x4 m_Transform = Matrix4x4.identity; - [SerializeField] - private GameObject m_InstancedGameObject; - [SerializeField] - private TileFlags m_Flags = TileFlags.LockColor; - [SerializeField] - private ColliderType m_ColliderType = ColliderType.Sprite; - - public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData) - { - tileData.sprite = m_Sprite; - tileData.color = m_Color; - tileData.transform = m_Transform; - tileData.gameObject = m_InstancedGameObject; - tileData.flags = m_Flags; - tileData.colliderType = m_ColliderType; - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/EditorPreviewTilemap.cs b/Modules/TilemapEditor/Editor/Managed/EditorPreviewTilemap.cs deleted file mode 100644 index f33aec55d7..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/EditorPreviewTilemap.cs +++ /dev/null @@ -1,78 +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.Scripting; -using UnityEngine.Tilemaps; - -namespace UnityEditor -{ - [RequiredByNativeCode] - internal class EditorPreviewTilemap : ITilemap - { - private EditorPreviewTilemap() - { - } - - // Tile - public override Sprite GetSprite(Vector3Int position) - { - var tile = m_Tilemap.GetEditorPreviewTile(position); - return tile ? m_Tilemap.GetEditorPreviewSprite(position) : m_Tilemap.GetSprite(position); - } - - public override Color GetColor(Vector3Int position) - { - var tile = m_Tilemap.GetEditorPreviewTile(position); - return tile ? m_Tilemap.GetEditorPreviewColor(position) : m_Tilemap.GetColor(position); - } - - public override Matrix4x4 GetTransformMatrix(Vector3Int position) - { - var tile = m_Tilemap.GetEditorPreviewTile(position); - return tile ? m_Tilemap.GetEditorPreviewTransformMatrix(position) : m_Tilemap.GetTransformMatrix(position); - } - - public override TileFlags GetTileFlags(Vector3Int position) - { - var tile = m_Tilemap.GetEditorPreviewTile(position); - return tile ? m_Tilemap.GetEditorPreviewTileFlags(position) : m_Tilemap.GetTileFlags(position); - } - - // Tile Assets - public override TileBase GetTile(Vector3Int position) - { - var tile = m_Tilemap.GetEditorPreviewTile(position); - return tile ?? m_Tilemap.GetTile(position); - } - - public override T GetTile(Vector3Int position) - { - var tile = m_Tilemap.GetEditorPreviewTile(position); - return tile ?? m_Tilemap.GetTile(position); - } - - private TileBase CreateInvalidTile() - { - Texture2D tex = Texture2D.whiteTexture; - Sprite sprite = Sprite.Create(tex, new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0.5f, 0.5f), tex.width); - - Tile tile = ScriptableObject.CreateInstance(); - tile.sprite = sprite; - // Try to get a pinkish look with a random color to differentiate between other invalid tiles - tile.color = UnityEngine.Random.ColorHSV(340f / 360f, 1f, 0.3f, 0.6f, 0.7f, 1.0f); - tile.transform = Matrix4x4.identity; - tile.flags = TileFlags.LockAll; - - return tile; - } - - private static ITilemap CreateInstance() - { - s_Instance = new EditorPreviewTilemap(); - return s_Instance; - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridBrush.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridBrush.cs index 9e14183cba..978133932c 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridBrush.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridBrush.cs @@ -453,6 +453,7 @@ public override int GetHashCode() { hash = tile != null ? tile.GetInstanceID() : 0; hash = hash * 33 + matrix.GetHashCode(); + hash = hash * 33 + matrix.rotation.GetHashCode(); hash = hash * 33 + color.GetHashCode(); } return hash; diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushEditorBase.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushEditorBase.cs index 80d520831b..72ceacb7d1 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushEditorBase.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushEditorBase.cs @@ -56,6 +56,12 @@ internal static void OnPaintSceneGUIInternal(GridLayout gridLayout, GameObject b } GridEditorUtility.DrawGridMarquee(gridLayout, position, color); + if (position.zMin != 0) + { + var zeroBounds = position; + zeroBounds.zMin = 0; + GridEditorUtility.DrawGridMarquee(gridLayout, zeroBounds, Color.blue); + } } } } diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushesDropdown.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushesDropdown.cs deleted file mode 100644 index 23226537dd..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridBrushesDropdown.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; - -namespace UnityEditor -{ - internal class GridBrushesDropdown : FlexibleMenu - { - public GridBrushesDropdown(IFlexibleMenuItemProvider itemProvider, int selectionIndex, FlexibleMenuModifyItemUI modifyItemUi, Action itemClickedCallback, float minWidth) - : base(itemProvider, selectionIndex, modifyItemUi, itemClickedCallback) - { - minTextWidth = minWidth; - } - - internal class MenuItemProvider : IFlexibleMenuItemProvider - { - public int Count() - { - return GridPaletteBrushes.brushes.Count; - } - - public object GetItem(int index) - { - return GridPaletteBrushes.brushes[index]; - } - - public int Add(object obj) - { - throw new NotImplementedException(); - } - - public void Replace(int index, object newPresetObject) - { - throw new NotImplementedException(); - } - - public void Remove(int index) - { - throw new NotImplementedException(); - } - - public object Create() - { - throw new NotImplementedException(); - } - - public void Move(int index, int destIndex, bool insertAfterDestIndex) - { - throw new NotImplementedException(); - } - - public string GetName(int index) - { - return GridPaletteBrushes.brushNames[index]; - } - - public bool IsModificationAllowed(int index) - { - return false; - } - - public int[] GetSeperatorIndices() - { - return new int[0]; - } - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteClipboard.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteClipboard.cs index 74278db16c..fcdb778094 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteClipboard.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteClipboard.cs @@ -353,7 +353,7 @@ protected override void OnDisable() public override void OnGUI() { - if (guiRect.width == 0f || guiRect.height == 0f) + if (Mathf.Approximately(guiRect.width, 0f) || Mathf.Approximately(guiRect.height, 0f)) return; UpdateMouseGridPosition(); @@ -389,7 +389,7 @@ public override void OnGUI() public void OnViewSizeChanged(Rect oldSize, Rect newSize) { - if (oldSize.height * oldSize.width * newSize.height * newSize.width == 0f) + if (Mathf.Approximately(oldSize.height * oldSize.width * newSize.height * newSize.width, 0f)) return; Camera cam = previewUtility.camera; @@ -625,13 +625,13 @@ private void RenderDragAndDropPreview() RectInt rect = TileDragAndDrop.GetMinMaxRect(m_HoverData.Keys.ToList()); rect.position += mouseGridPosition; DragAndDrop.visualMode = DragAndDropVisualMode.Copy; - GridEditorUtility.DrawGridMarquee(grid, new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, 0), new Vector3Int(rect.width, rect.height, 1)), Color.white); + GridEditorUtility.DrawGridMarquee(grid, new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.width, rect.height, 1)), Color.white); } private void RenderGrid() { // MeshTopology.Lines doesn't give nice pixel perfect grid so we have to have separate codepath with MeshTopology.Quads specially for palette window here - if (m_GridMesh == null && grid.cellLayout == Grid.CellLayout.Rectangle) + if (m_GridMesh == null && grid.cellLayout == GridLayout.CellLayout.Rectangle) m_GridMesh = GridEditorUtility.GenerateCachedGridMesh(grid, k_GridColor, 1f / LocalToScreenRatio(), paddedBoundsInt, MeshTopology.Quads); GridEditorUtility.DrawGridGizmo(grid, grid.transform, k_GridColor, ref m_GridMesh, ref m_GridMaterial); @@ -750,7 +750,7 @@ public void SetEditorPreviewTile(Tilemap tilemap, Vector2Int position, TileBase public void SetTile(Tilemap tilemap, Vector2Int position, TileBase tile, Color color, Matrix4x4 matrix) { - Vector3Int pos3 = new Vector3Int(position.x, position.y, 0); + Vector3Int pos3 = new Vector3Int(position.x, position.y, zPosition); tilemap.SetTile(pos3, tile); tilemap.SetColor(pos3, color); tilemap.SetTransformMatrix(pos3, matrix); @@ -809,7 +809,7 @@ protected override void PickBrush(BoundsInt position, Vector3Int pickingStart) gridBrush.Pick(grid, brushTarget, position, pickingStart); if (!PaintableGrid.InGridEditMode()) - EditMode.ChangeEditMode(EditMode.SceneViewEditMode.GridPainting, new Bounds(), GridPaintingState.instance); + EditMode.ChangeEditMode(EditMode.SceneViewEditMode.GridPainting, GridPaintingState.instance); m_ActivePick = new RectInt(position.min.x, position.min.y, position.size.x, position.size.y); } @@ -873,7 +873,7 @@ private void PingTileAsset(RectInt rect) // Only able to ping asset if only one asset is selected if (rect.size == Vector2Int.zero && tilemap != null) { - TileBase tile = tilemap.GetTile(new Vector3Int(rect.xMin, rect.yMin, 0)); + TileBase tile = tilemap.GetTile(new Vector3Int(rect.xMin, rect.yMin, zPosition)); EditorGUIUtility.PingObject(tile); Selection.activeObject = tile; } @@ -931,29 +931,6 @@ protected void DrawSelectionGizmo(RectInt rect) private void HandleMouseEnterLeave() { - if (Event.current.type == EventType.MouseEnterWindow) - { - if (PaintableGrid.InGridEditMode()) - { - GridPaintingState.activeGrid = this; - Event.current.Use(); - } - } - else if (Event.current.type == EventType.MouseLeaveWindow) - { - if (m_PreviousMousePosition.HasValue && guiRect.Contains(m_PreviousMousePosition.Value) && GridPaintingState.activeBrushEditor != null) - { - GridPaintingState.activeBrushEditor.OnMouseLeave(); - } - m_PreviousMousePosition = null; - if (PaintableGrid.InGridEditMode()) - { - GridPaintingState.activeGrid = null; - Event.current.Use(); - Repaint(); - } - } - if (guiRect.Contains(Event.current.mousePosition)) { if (m_PreviousMousePosition.HasValue && !guiRect.Contains(m_PreviousMousePosition.Value) || !m_PreviousMousePosition.HasValue) @@ -998,7 +975,7 @@ private void CallOnPaintSceneGUI(Vector2Int position) rect = new RectInt(GridSelection.position.xMin, GridSelection.position.yMin, GridSelection.position.size.x, GridSelection.position.size.y); var gridLayout = tilemap != null ? tilemap as GridLayout : grid as GridLayout; - BoundsInt brushBounds = new BoundsInt(new Vector3Int(rect.x, rect.y, 0), new Vector3Int(rect.width, rect.height, 1)); + BoundsInt brushBounds = new BoundsInt(new Vector3Int(rect.x, rect.y, zPosition), new Vector3Int(rect.width, rect.height, 1)); if (GridPaintingState.activeBrushEditor != null) GridPaintingState.activeBrushEditor.OnPaintSceneGUI(gridLayout, brushTarget, brushBounds, EditModeToBrushTool(EditMode.editMode), m_MarqueeStart.HasValue || executing); diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteWindow.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteWindow.cs index 04dc841fa8..17081082fc 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteWindow.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintPaletteWindow.cs @@ -97,6 +97,8 @@ static class Styles public static readonly GUIContent tilePalette = EditorGUIUtility.TrTextContent("Tile Palette"); public static readonly GUIContent edit = EditorGUIUtility.TrTextContent("Edit"); public static readonly GUIContent editModified = EditorGUIUtility.TrTextContent("Edit*"); + public static readonly GUIContent zPosition = EditorGUIUtility.TrTextContent("Z Position"); + public static readonly GUIContent resetZPosition = EditorGUIUtility.TrTextContent("Reset"); public static readonly GUIStyle ToolbarTitleStyle = "Toolbar"; public static readonly GUIStyle dragHandle = "RL DragHandle"; public static readonly float dragPadding = 3f; @@ -280,6 +282,31 @@ static void FlipBrushY() FlipBrush(GridBrush.FlipAxis.Y); } + static void ChangeBrushZ(int change) + { + GridPaintingState.gridBrush.ChangeZPosition(change); + GridPaintingState.activeGrid.ChangeZPosition(change); + GridPaintingState.activeGrid.Repaint(); + foreach (var window in GridPaintPaletteWindow.instances) + { + window.Repaint(); + } + } + + [Shortcut("Grid Painting/Increase Z", typeof(ShortcutContext), "-")] + static void IncreaseBrushZ() + { + if (GridPaintingState.gridBrush != null && GridPaintingState.activeGrid != null) + ChangeBrushZ(1); + } + + [Shortcut("Grid Painting/Decrease Z", typeof(ShortcutContext), "=")] + static void DecreaseBrushZ() + { + if (GridPaintingState.gridBrush != null && GridPaintingState.activeGrid != null) + ChangeBrushZ(-1); + } + [SettingsProvider] internal static SettingsProvider CreateSettingsProvider() { @@ -556,7 +583,9 @@ public void SavePalette() GridPaintingState.savingPalette = true; SetHideFlagsRecursivelyIgnoringTilemapChildren(paletteInstance, HideFlags.HideInHierarchy); string path = AssetDatabase.GetAssetPath(palette); + #pragma warning disable CS0618 // Type or member is obsolete PrefabUtility.ReplacePrefabAssetNameBased(paletteInstance, path, true); + #pragma warning restore CS0618 // Type or member is obsolete SetHideFlagsRecursivelyIgnoringTilemapChildren(paletteInstance, HideFlags.HideAndDontSave); GridPaintingState.savingPalette = false; } @@ -688,6 +717,7 @@ public void OnEnable() GridPaintingState.brushChanged += OnBrushChanged; SceneView.onSceneGUIDelegate += OnSceneViewGUI; PrefabUtility.prefabInstanceUpdated += PrefabInstanceUpdated; + EditorApplication.projectWasLoaded += OnProjectLoaded; AssetPreview.SetPreviewTextureCacheSize(256, GetInstanceID()); wantsMouseMove = true; @@ -726,6 +756,12 @@ private void PrefabInstanceUpdated(GameObject updatedPrefab) } } + private void OnProjectLoaded() + { + // ShortcutIntegration instance is recreated after LoadLayout which wipes the OnEnable registration + ShortcutIntegration.instance.contextManager.RegisterToolContext(m_ShortcutContext); + } + private void OnBrushChanged(GridBrushBase brush) { DisableFocus(); @@ -774,6 +810,7 @@ public void OnDisable() GridPaintingState.brushChanged -= OnBrushChanged; GridPaintingState.UnregisterPainterInterest(this); PrefabUtility.prefabInstanceUpdated -= PrefabInstanceUpdated; + EditorApplication.projectWasLoaded -= OnProjectLoaded; ShortcutIntegration.instance.contextManager.DeregisterToolContext(m_ShortcutContext); } @@ -787,7 +824,7 @@ private void OnScenePaintTargetChanged(GameObject scenePaintTarget) public void ChangeToTool(GridBrushBase.Tool tool) { - EditMode.ChangeEditMode(PaintableGrid.BrushToolToEditMode(tool), new Bounds(Vector3.zero, Vector3.positiveInfinity), GridPaintingState.instance); + EditMode.ChangeEditMode(PaintableGrid.BrushToolToEditMode(tool), GridPaintingState.instance); Repaint(); } @@ -838,12 +875,18 @@ private void CallOnToolDeactivated() } } + internal void ResetZPosition() + { + GridPaintingState.gridBrush.ResetZPosition(); + GridPaintingState.lastActiveGrid.ResetZPosition(); + } + private void OnBrushInspectorGUI() { - var brush = GridPaintingState.gridBrush; - if (brush == null) + if (GridPaintingState.gridBrush == null) return; + // Brush Inspector GUI EditorGUI.BeginChangeCheck(); if (GridPaintingState.activeBrushEditor != null) GridPaintingState.activeBrushEditor.OnPaintInspectorGUI(); @@ -853,6 +896,25 @@ private void OnBrushInspectorGUI() { GridPaletteBrushes.ActiveGridBrushAssetChanged(); } + + // Z Position Inspector + var hasLastActiveGrid = GridPaintingState.lastActiveGrid != null; + using (new EditorGUI.DisabledScope(!hasLastActiveGrid)) + { + EditorGUILayout.BeginHorizontal(); + EditorGUI.BeginChangeCheck(); + var zPosition = EditorGUILayout.DelayedIntField(Styles.zPosition, hasLastActiveGrid ? GridPaintingState.lastActiveGrid.zPosition : 0); + if (EditorGUI.EndChangeCheck()) + { + GridPaintingState.gridBrush.ChangeZPosition(zPosition - GridPaintingState.lastActiveGrid.zPosition); + GridPaintingState.lastActiveGrid.zPosition = zPosition; + } + if (GUILayout.Button(Styles.resetZPosition)) + { + ResetZPosition(); + } + EditorGUILayout.EndHorizontal(); + } } private bool IsObjectPrefabInstance(Object target) @@ -938,19 +1000,19 @@ private void SelectTarget(int i, object o) var option = EditorUtility.DisplayDialogComplex(TilePaletteProperties.targetEditModeDialogTitle , TilePaletteProperties.targetEditModeDialogMessage , TilePaletteProperties.targetEditModeDialogYes - , TilePaletteProperties.targetEditModeDialogChange - , TilePaletteProperties.targetEditModeDialogNo); + , TilePaletteProperties.targetEditModeDialogNo + , TilePaletteProperties.targetEditModeDialogChange); switch (option) { case 0: GoToPrefabMode(obj); return; case 1: - var settingsWindow = SettingsWindow.Show(SettingsScopes.User); - settingsWindow.FilterProviders(TilePaletteProperties.targetEditModeLookup); + // Do nothing here for "No" break; case 2: - // Do nothing here for "No" + var settingsWindow = SettingsWindow.Show(SettingsScopes.User); + settingsWindow.FilterProviders(TilePaletteProperties.targetEditModeLookup); break; } } @@ -1037,7 +1099,7 @@ private void OpenAddPalettePopup(Rect rect) private void OnClipboardGUI(Rect position) { - if (Event.current.type != EventType.Layout && position.Contains(Event.current.mousePosition) && GridPaintingState.activeGrid != clipboardView) + if (Event.current.type != EventType.Layout && position.Contains(Event.current.mousePosition) && GridPaintingState.activeGrid != clipboardView && clipboardView.unlocked) { GridPaintingState.activeGrid = clipboardView; SceneView.RepaintAll(); @@ -1182,7 +1244,18 @@ private static void OnPostprocessAllAssets(string[] importedAssets, string[] del public class PaletteAssetModificationProcessor : AssetModificationProcessor { + static void OnWillCreateAsset(string assetName) + { + SavePalettesIfRequired(); + } + static string[] OnWillSaveAssets(string[] paths) + { + SavePalettesIfRequired(); + return paths; + } + + static void SavePalettesIfRequired() { if (!GridPaintingState.savingPalette) { @@ -1195,7 +1268,6 @@ static string[] OnWillSaveAssets(string[] paths) } } } - return paths; } } } diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintTargetsDropdown.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintTargetsDropdown.cs deleted file mode 100644 index 75acbe8239..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintTargetsDropdown.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; - -namespace UnityEditor -{ - internal class GridPaintTargetsDropdown : FlexibleMenu - { - public GridPaintTargetsDropdown(IFlexibleMenuItemProvider itemProvider, int selectionIndex, FlexibleMenuModifyItemUI modifyItemUi, Action itemClickedCallback, float minWidth) - : base(itemProvider, selectionIndex, modifyItemUi, itemClickedCallback) - { - minTextWidth = minWidth; - } - - internal class MenuItemProvider : IFlexibleMenuItemProvider - { - public int Count() - { - return GridPaintingState.validTargets != null ? GridPaintingState.validTargets.Length : 0; - } - - public object GetItem(int index) - { - return GridPaintingState.validTargets != null ? GridPaintingState.validTargets[index] : GridPaintingState.scenePaintTarget; - } - - public int Add(object obj) - { - throw new NotImplementedException(); - } - - public void Replace(int index, object newPresetObject) - { - throw new NotImplementedException(); - } - - public void Remove(int index) - { - throw new NotImplementedException(); - } - - public object Create() - { - throw new NotImplementedException(); - } - - public void Move(int index, int destIndex, bool insertAfterDestIndex) - { - throw new NotImplementedException(); - } - - public string GetName(int index) - { - return GridPaintingState.validTargets != null ? GridPaintingState.validTargets[index].name : GridPaintingState.scenePaintTarget.name; - } - - public bool IsModificationAllowed(int index) - { - return false; - } - - public int[] GetSeperatorIndices() - { - return new int[0]; - } - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs index 7f25f4a305..9010374679 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaintingState.cs @@ -15,6 +15,7 @@ internal class GridPaintingState : ScriptableSingleton, ITool [SerializeField] private GameObject m_ScenePaintTarget; // Which GameObject in scene is considered as painting target [SerializeField] private GridBrushBase m_Brush; // Which brush will handle painting callbacks [SerializeField] private PaintableGrid m_ActiveGrid; // Grid that has painting focus (can be palette, too) + [SerializeField] private PaintableGrid m_LastActiveGrid; // Grid that last had painting focus (can be palette, too) [SerializeField] private HashSet m_InterestedPainters = new HashSet(); // A list of objects that can paint using the GridPaintingState private GameObject[] m_CachedPaintTargets = null; @@ -145,7 +146,17 @@ public static Editor fallbackEditor public static PaintableGrid activeGrid { get { return instance.m_ActiveGrid; } - set { instance.m_ActiveGrid = value; } + set + { + instance.m_ActiveGrid = value; + if (instance.m_ActiveGrid != null) + instance.m_LastActiveGrid = value; + } + } + + public static PaintableGrid lastActiveGrid + { + get { return instance.m_LastActiveGrid; } } public static bool ValidatePaintTarget(GameObject candidate) diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPalette.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPalette.cs deleted file mode 100644 index 0fc0d9e5d2..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPalette.cs +++ /dev/null @@ -1,15 +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; - -namespace UnityEditor -{ - public class GridPalette : ScriptableObject - { - public enum CellSizing { Automatic = 0, Manual = 100 } - [SerializeField] - public CellSizing cellSizing; - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteAddPopup.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteAddPopup.cs index 952df16b08..6509d90f1d 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteAddPopup.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteAddPopup.cs @@ -104,6 +104,9 @@ internal void OnGUI() { if (GUILayout.Button(Styles.ok)) { + // case 1077362: Close window to prevent overlap with OS folder window when saving new palette asset + Close(); + var swizzle = Grid.CellSwizzle.XYZ; if (m_Layout == GridLayout.CellLayout.Hexagon) swizzle = Styles.hexagonSwizzleTypeValue[m_HexagonLayout]; @@ -114,6 +117,7 @@ internal void OnGUI() m_Owner.palette = go; m_Owner.Repaint(); } + GUIUtility.ExitGUI(); } } diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteBrushes.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteBrushes.cs deleted file mode 100644 index 602e2634cd..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPaletteBrushes.cs +++ /dev/null @@ -1,237 +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 UnityEngine; -using UnityEditorInternal; - -namespace UnityEditor -{ - internal class GridPaletteBrushes : ScriptableSingleton - { - private static readonly string s_LibraryPath = "Library/GridBrush"; - private static readonly string s_GridBrushExtension = ".asset"; - - private static bool s_RefreshCache; - [SerializeField] private List m_Brushes; - - public static List brushes - { - get - { - if (instance.m_Brushes == null || instance.m_Brushes.Count == 0 || s_RefreshCache) - { - instance.RefreshBrushesCache(); - s_RefreshCache = false; - } - - return instance.m_Brushes; - } - } - private string[] m_BrushNames; - - public static string[] brushNames - { - get - { - return instance.m_BrushNames; - } - } - - public static Type GetDefaultBrushType() - { - Type defaultType = typeof(GridBrush); - int count = 0; - foreach (var type in EditorAssemblies.GetAllTypesWithAttribute()) - { - var attrs = type.GetCustomAttributes(typeof(CustomGridBrushAttribute), false) as CustomGridBrushAttribute[]; - if (attrs != null && attrs.Length > 0) - { - if (attrs[0].defaultBrush) - { - defaultType = type; - count++; - } - } - } - if (count > 1) - { - Debug.LogWarning("Multiple occurrences of defaultBrush == true found. It should only be declared once."); - } - return defaultType; - } - - public static void ActiveGridBrushAssetChanged() - { - if (GridPaintingState.gridBrush == null) - return; - - if (IsLibraryBrush(GridPaintingState.gridBrush)) - { - instance.SaveLibraryGridBrushAsset(GridPaintingState.gridBrush); - } - } - - private void RefreshBrushesCache() - { - if (m_Brushes == null) - m_Brushes = new List(); - - GridBrushBase defaultBrush = null; - if (m_Brushes.Count == 0 || !(m_Brushes[0] is GridBrush)) - { - System.Type defaultType = GetDefaultBrushType(); - defaultBrush = LoadOrCreateLibraryGridBrushAsset(defaultType); - m_Brushes.Insert(0, defaultBrush); - m_Brushes[0].name = GetBrushDropdownName(m_Brushes[0]); - } - - var editorAssemblies = EditorAssemblies.loadedAssemblies; - foreach (var editorAssembly in editorAssemblies) - { - try - { - IEnumerable brushTypes = editorAssembly.GetTypes().Where(t => t != typeof(GridBrushBase) && t != typeof(GridBrush) && typeof(GridBrushBase).IsAssignableFrom(t)); - foreach (var brushType in brushTypes) - { - if (IsDefaultInstanceVisibleGridBrushType(brushType)) - { - var brush = LoadOrCreateLibraryGridBrushAsset(brushType); - if (brush != null) - m_Brushes.Add(brush); - } - } - } - catch (Exception ex) - { - Debug.Log(string.Format("TilePalette failed to get types from {0}. Error: {1}", editorAssembly.FullName, ex.Message)); - } - } - - string[] guids = AssetDatabase.FindAssets("t:GridBrushBase"); - foreach (string guid in guids) - { - string path = AssetDatabase.GUIDToAssetPath(guid); - var brush = AssetDatabase.LoadAssetAtPath(path, typeof(GridBrushBase)) as GridBrushBase; - if (brush != null && IsAssetVisibleGridBrushType(brush.GetType())) - m_Brushes.Add(brush); - } - - m_BrushNames = new string[m_Brushes.Count]; - for (int i = 0; i < m_Brushes.Count; i++) - { - m_BrushNames[i] = m_Brushes[i].name; - } - } - - private bool IsDefaultInstanceVisibleGridBrushType(Type brushType) - { - CustomGridBrushAttribute[] customBrushes = brushType.GetCustomAttributes(typeof(CustomGridBrushAttribute), false) as CustomGridBrushAttribute[]; - if (customBrushes != null && customBrushes.Length > 0) - { - return !customBrushes[0].hideDefaultInstance; - } - return false; - } - - private bool IsAssetVisibleGridBrushType(Type brushType) - { - CustomGridBrushAttribute[] customBrushes = brushType.GetCustomAttributes(typeof(CustomGridBrushAttribute), false) as CustomGridBrushAttribute[]; - if (customBrushes != null && customBrushes.Length > 0) - { - return !customBrushes[0].hideAssetInstances; - } - return false; - } - - private void SaveLibraryGridBrushAsset(GridBrushBase brush) - { - var gridBrushPath = GenerateGridBrushInstanceLibraryPath(brush.GetType()); - string folderPath = Path.GetDirectoryName(gridBrushPath); - if (!Directory.Exists(folderPath)) - { - Directory.CreateDirectory(folderPath); - } - InternalEditorUtility.SaveToSerializedFileAndForget(new[] { brush }, gridBrushPath, true); - } - - private GridBrushBase LoadOrCreateLibraryGridBrushAsset(Type brushType) - { - var serializedObjects = InternalEditorUtility.LoadSerializedFileAndForget(GenerateGridBrushInstanceLibraryPath(brushType)); - if (serializedObjects != null && serializedObjects.Length > 0) - { - GridBrushBase brush = serializedObjects[0] as GridBrushBase; - if (brush != null && brush.GetType() == brushType) - return brush; - } - return CreateLibraryGridBrushAsset(brushType); - } - - private GridBrushBase CreateLibraryGridBrushAsset(Type brushType) - { - GridBrushBase brush = ScriptableObject.CreateInstance(brushType) as GridBrushBase; - brush.hideFlags = HideFlags.DontSave; - brush.name = GetBrushDropdownName(brush); - SaveLibraryGridBrushAsset(brush); - return brush; - } - - private string GenerateGridBrushInstanceLibraryPath(Type brushType) - { - var path = FileUtil.CombinePaths(s_LibraryPath, brushType.ToString() + s_GridBrushExtension); - path = FileUtil.NiceWinPath(path); - return path; - } - - private string GetBrushDropdownName(GridBrushBase brush) - { - // Asset Brushes use the asset name - if (!IsLibraryBrush(brush)) - return brush.name; - - // Library Brushes - CustomGridBrushAttribute[] customBrushes = brush.GetType().GetCustomAttributes(typeof(CustomGridBrushAttribute), false) as CustomGridBrushAttribute[]; - if (customBrushes != null && customBrushes.Length > 0 && customBrushes[0].defaultName.Length > 0) - return customBrushes[0].defaultName; - - if (brush.GetType() == typeof(GridBrush)) - return "Default Brush"; - - return brush.GetType().Name; - } - - private static bool IsLibraryBrush(GridBrushBase brush) - { - return !AssetDatabase.Contains(brush); - } - - // TODO: Better way of clearing caches than AssetPostprocessor - public class AssetProcessor : AssetPostprocessor - { - public override int GetPostprocessOrder() - { - return 1; - } - - private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) - { - if (!GridPaintingState.savingPalette) - FlushCache(); - } - } - - internal static void FlushCache() - { - s_RefreshCache = true; - if (instance.m_Brushes != null) - { - instance.m_Brushes.Clear(); - GridPaintingState.FlushCache(); - } - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPalettes.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPalettes.cs deleted file mode 100644 index 1e73ff5e83..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPalettes.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 System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - internal class GridPalettes : ScriptableSingleton - { - private static bool s_RefreshCache; - - [SerializeField] private List m_PalettesCache; - - public static List palettes - { - get - { - if (instance.m_PalettesCache == null || s_RefreshCache) - { - instance.RefreshPalettesCache(); - s_RefreshCache = false; - } - - return instance.m_PalettesCache; - } - } - - private void RefreshPalettesCache() - { - if (instance.m_PalettesCache == null) - instance.m_PalettesCache = new List(); - - string[] guids = AssetDatabase.FindAssets("t:GridPalette"); - foreach (string guid in guids) - { - string path = AssetDatabase.GUIDToAssetPath(guid); - GridPalette paletteAsset = AssetDatabase.LoadAssetAtPath(path, typeof(GridPalette)) as GridPalette; - if (paletteAsset != null) - { - string assetPath = AssetDatabase.GetAssetPath(paletteAsset); - GameObject palette = AssetDatabase.LoadMainAssetAtPath(assetPath) as GameObject; - if (palette != null) - { - m_PalettesCache.Add(palette); - } - } - } - m_PalettesCache.Sort((x, y) => String.Compare(x.name, y.name, StringComparison.OrdinalIgnoreCase)); - } - - public class AssetProcessor : AssetPostprocessor - { - public override int GetPostprocessOrder() - { - return 1; - } - - private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) - { - if (!GridPaintingState.savingPalette) - CleanCache(); - } - } - - internal static void CleanCache() - { - instance.m_PalettesCache = null; - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridPalettesDropdown.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridPalettesDropdown.cs deleted file mode 100644 index b0f7ed7967..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridPalettesDropdown.cs +++ /dev/null @@ -1,78 +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 -{ - internal class GridPalettesDropdown : FlexibleMenu - { - public GridPalettesDropdown(IFlexibleMenuItemProvider itemProvider, int selectionIndex, FlexibleMenuModifyItemUI modifyItemUi, Action itemClickedCallback, float minWidth) - : base(itemProvider, selectionIndex, modifyItemUi, itemClickedCallback) - { - minTextWidth = minWidth; - } - - internal class MenuItemProvider : IFlexibleMenuItemProvider - { - public int Count() - { - return GridPalettes.palettes.Count + 1; - } - - public object GetItem(int index) - { - if (index < GridPalettes.palettes.Count) - return GridPalettes.palettes[index]; - - return null; - } - - public int Add(object obj) - { - throw new NotImplementedException(); - } - - public void Replace(int index, object newPresetObject) - { - throw new NotImplementedException(); - } - - public void Remove(int index) - { - throw new NotImplementedException(); - } - - public object Create() - { - throw new NotImplementedException(); - } - - public void Move(int index, int destIndex, bool insertAfterDestIndex) - { - throw new NotImplementedException(); - } - - public string GetName(int index) - { - if (index < GridPalettes.palettes.Count) - return GridPalettes.palettes[index].name; - else if (index == GridPalettes.palettes.Count) - return "Create New Palette"; - else - return ""; - } - - public bool IsModificationAllowed(int index) - { - return false; - } - - public int[] GetSeperatorIndices() - { - return new int[] { GridPalettes.palettes.Count - 1 }; - } - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/GridSelection.cs b/Modules/TilemapEditor/Editor/Managed/Grid/GridSelection.cs deleted file mode 100644 index d3877ca3ef..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/Grid/GridSelection.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 System; -using UnityEngine; -using Object = UnityEngine.Object; - -namespace UnityEditor -{ - public class GridSelection : ScriptableObject - { - public static event Action gridSelectionChanged; - private BoundsInt m_Position; - private GameObject m_Target; - [SerializeField] private Object m_PreviousSelection; - - public static bool active { get { return Selection.activeObject is GridSelection && selection.m_Target != null; } } - - private static GridSelection selection { get { return Selection.activeObject as GridSelection; } } - public static BoundsInt position - { - get { return selection != null ? selection.m_Position : new BoundsInt(); } - set - { - if (selection != null && selection.m_Position != value) - { - selection.m_Position = value; - if (gridSelectionChanged != null) - gridSelectionChanged(); - } - } - } - public static GameObject target { get { return selection != null ? selection.m_Target : null; } } - public static Grid grid { get { return selection != null && selection.m_Target != null ? selection.m_Target.GetComponentInParent() : null; } } - - public static void Select(Object target, BoundsInt bounds) - { - GridSelection newSelection = CreateInstance(); - newSelection.m_PreviousSelection = Selection.activeObject; - newSelection.m_Target = target as GameObject; - newSelection.m_Position = bounds; - Selection.activeObject = newSelection; - if (gridSelectionChanged != null) - gridSelectionChanged(); - } - - public static void Clear() - { - if (active) - { - selection.m_Position = new BoundsInt(); - Selection.activeObject = selection.m_PreviousSelection; - if (gridSelectionChanged != null) - gridSelectionChanged(); - } - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/PaintableGrid.cs b/Modules/TilemapEditor/Editor/Managed/Grid/PaintableGrid.cs index b1dced7da9..72dfeac3c6 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/PaintableGrid.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/PaintableGrid.cs @@ -53,11 +53,13 @@ protected virtual void OnBrushPickCancelled() {} private MarqueeType m_MarqueeType = MarqueeType.None; private bool m_IsExecuting; private EditMode.SceneViewEditMode m_ModeBeforePicking; + private int m_ZPosition; public Vector2Int mouseGridPosition { get { return m_MouseGridPosition; } } public bool isPicking { get { return m_MarqueeType == MarqueeType.Pick; } } public bool isBoxing { get { return m_MarqueeType == MarqueeType.Box; } } public Grid.CellLayout cellLayout { get { return CellLayout(); } } + public int zPosition { get { return m_ZPosition; } set { m_ZPosition = value; } } protected bool executing { get { return m_IsExecuting; } set { m_IsExecuting = value && isHotControl; } } @@ -101,12 +103,20 @@ public virtual void OnGUI() } } - protected void UpdateMouseGridPosition() + protected void ResetPreviousMousePositionToCurrentPosition() { - if (Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseMove || Event.current.type == EventType.DragUpdated) - { - m_MouseGridPositionChanged = false; + m_PreviousMouseGridPosition = m_MouseGridPosition; + } + protected void UpdateMouseGridPosition(bool forceUpdate = false) + { + if (Event.current.type == EventType.MouseDrag + || Event.current.type == EventType.MouseMove + // Case 1075857: Mouse Down when window is not in focus needs to update mouse grid position + || Event.current.type == EventType.MouseDown + || Event.current.type == EventType.DragUpdated + || forceUpdate) + { Vector2Int newGridPosition = ScreenToGrid(Event.current.mousePosition); if (newGridPosition != m_MouseGridPosition) { @@ -116,14 +126,23 @@ protected void UpdateMouseGridPosition() newGridPosition.x = m_MouseGridPosition.x + Math.Sign(delta.x) * k_MaxMouseCellDelta; if (Mathf.Abs(delta.y) > k_MaxMouseCellDelta) newGridPosition.y = m_MouseGridPosition.y + Math.Sign(delta.y) * k_MaxMouseCellDelta; - m_PreviousMouseGridPosition = m_MouseGridPosition; + ResetPreviousMousePositionToCurrentPosition(); m_MouseGridPosition = newGridPosition; - m_MouseGridPositionChanged = true; - m_PositionChangeRepaintDone = false; + MouseGridPositionChanged(); + } + else if (!forceUpdate) + { + m_MouseGridPositionChanged = false; } } } + private void MouseGridPositionChanged() + { + m_MouseGridPositionChanged = true; + m_PositionChangeRepaintDone = false; + } + private void HandleEditModeChange() { // Handles changes in EditMode while tool is expected to be in the same mode @@ -178,7 +197,7 @@ private void HandleBrushPicking() if (evt.type == EventType.MouseDrag && isHotControl && m_MarqueeStart.HasValue && m_MarqueeType == MarqueeType.Pick && IsPickingEvent(evt)) { RectInt rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition); - OnBrushPickDragged(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, 0), new Vector3Int(rect.size.x, rect.size.y, 1))); + OnBrushPickDragged(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.size.x, rect.size.y, 1))); Event.current.Use(); GUI.changed = true; } @@ -189,7 +208,7 @@ private void HandleBrushPicking() { RectInt rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition); Vector2Int pivot = GetMarqueePivot(m_MarqueeStart.Value, mouseGridPosition); - PickBrush(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, 0), new Vector3Int(rect.size.x, rect.size.y, 1)), new Vector3Int(pivot.x, pivot.y, 0)); + PickBrush(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.size.x, rect.size.y, 1)), new Vector3Int(pivot.x, pivot.y, 0)); if (inEditMode && EditMode.editMode != m_ModeBeforePicking) { @@ -245,7 +264,7 @@ private void HandleSelectTool() if (evt.type == EventType.MouseUp && m_MarqueeType == MarqueeType.Select) { RectInt rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition); - Select(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, 0), new Vector3Int(rect.size.x, rect.size.y, 1))); + Select(new BoundsInt(new Vector3Int(rect.xMin, rect.yMin, zPosition), new Vector3Int(rect.size.x, rect.size.y, 1))); Event.current.Use(); } if (evt.control) @@ -288,7 +307,7 @@ private void HandleMoveTool() { executing = true; BoundsInt previousRect = GridSelection.position; - BoundsInt previousBounds = new BoundsInt(new Vector3Int(previousRect.xMin, previousRect.yMin, 0), new Vector3Int(previousRect.size.x, previousRect.size.y, 1)); + BoundsInt previousBounds = new BoundsInt(new Vector3Int(previousRect.xMin, previousRect.yMin, GridSelection.position.zMin), new Vector3Int(previousRect.size.x, previousRect.size.y, 1)); Vector2Int direction = mouseGridPosition - m_PreviousMove.Value; BoundsInt pos = GridSelection.position; @@ -326,13 +345,13 @@ private void HandleBrushPaintAndErase() { if (EditMode.editMode != EditMode.SceneViewEditMode.GridEraser) EditMode.ChangeEditMode(EditMode.SceneViewEditMode.GridEraser, GridPaintingState.instance); - Erase(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, 0)); + Erase(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition)); } else { if (EditMode.editMode != EditMode.SceneViewEditMode.GridPainting) EditMode.ChangeEditMode(EditMode.SceneViewEditMode.GridPainting, GridPaintingState.instance); - Paint(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, 0)); + Paint(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition)); } Event.current.Use(); @@ -350,9 +369,9 @@ private void HandleBrushPaintAndErase() for (int i = 1; i < points.Count; i++) { if (IsErasingEvent(evt)) - Erase(new Vector3Int(points[i].x, points[i].y, 0)); + Erase(new Vector3Int(points[i].x, points[i].y, zPosition)); else - Paint(new Vector3Int(points[i].x, points[i].y, 0)); + Paint(new Vector3Int(points[i].x, points[i].y, zPosition)); } Event.current.Use(); GUI.changed = true; @@ -405,7 +424,7 @@ private void HandleFloodFill() { executing = false; RegisterUndo(); - FloodFill(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, 0)); + FloodFill(new Vector3Int(mouseGridPosition.x, mouseGridPosition.y, zPosition)); GUI.changed = true; Event.current.Use(); GUIUtility.hotControl = 0; @@ -442,9 +461,9 @@ private void HandleBoxTool() RegisterUndo(); RectInt rect = GridEditorUtility.GetMarqueeRect(m_MarqueeStart.Value, mouseGridPosition); if (evt.shift) - BoxErase(new BoundsInt(rect.x, rect.y, 0, rect.size.x, rect.size.y, 1)); + BoxErase(new BoundsInt(rect.x, rect.y, zPosition, rect.size.x, rect.size.y, 1)); else - BoxFill(new BoundsInt(rect.x, rect.y, 0, rect.size.x, rect.size.y, 1)); + BoxFill(new BoundsInt(rect.x, rect.y, zPosition, rect.size.x, rect.size.y, 1)); Event.current.Use(); executing = false; GUI.changed = true; @@ -464,6 +483,23 @@ private Vector2Int GetMarqueePivot(Vector2Int start, Vector2Int end) return pivot; } + public void ChangeZPosition(int change) + { + m_ZPosition += change; + MouseGridPositionChanged(); + Repaint(); + } + + public void ResetZPosition() + { + if (m_ZPosition == 0) + return; + + m_ZPosition = 0; + MouseGridPositionChanged(); + Repaint(); + } + public static bool InGridEditMode() { return diff --git a/Modules/TilemapEditor/Editor/Managed/Grid/PaintableSceneViewGrid.cs b/Modules/TilemapEditor/Editor/Managed/Grid/PaintableSceneViewGrid.cs index f8f53f27df..a538cc4e38 100644 --- a/Modules/TilemapEditor/Editor/Managed/Grid/PaintableSceneViewGrid.cs +++ b/Modules/TilemapEditor/Editor/Managed/Grid/PaintableSceneViewGrid.cs @@ -18,6 +18,7 @@ internal class PaintableSceneViewGrid : PaintableGrid private Grid grid { get { return brushTarget != null ? brushTarget.GetComponentInParent() : (Selection.activeGameObject != null ? Selection.activeGameObject.GetComponentInParent() : null); } } private GridBrushBase gridBrush { get { return GridPaintingState.gridBrush; } } private SceneView activeSceneView = null; + private int sceneViewTransformHash; GameObject brushTarget { @@ -64,7 +65,12 @@ private Rect GetSceneViewPositionRect(SceneView sceneView) public void OnSceneGUI(SceneView sceneView) { - UpdateMouseGridPosition(); + HandleMouseEnterLeave(sceneView); + + // Case 1077400: SceneView camera transform changes may update the mouse grid position even though the mouse position has not changed + var currentSceneViewTransformHash = sceneView.camera.transform.localToWorldMatrix.GetHashCode(); + UpdateMouseGridPosition(currentSceneViewTransformHash == sceneViewTransformHash); + sceneViewTransformHash = currentSceneViewTransformHash; var dot = 1.0f; var gridView = GetGridView(); @@ -88,7 +94,6 @@ public void OnSceneGUI(SceneView sceneView) EditorGUIUtility.AddCursorRect(GetSceneViewPositionRect(sceneView), MouseCursor.CustomCursor); } } - HandleMouseEnterLeave(sceneView); } private void HandleMouseEnterLeave(SceneView sceneView) @@ -132,6 +137,7 @@ private void OnMouseEnter(SceneView sceneView) GridPaintingState.activeBrushEditor.OnMouseEnter(); GridPaintingState.activeGrid = this; activeSceneView = sceneView; + ResetPreviousMousePositionToCurrentPosition(); } private void OnMouseLeave(SceneView sceneView) @@ -320,16 +326,16 @@ void CallOnPaintSceneGUI() rect = new RectInt(GridSelection.position.xMin, GridSelection.position.yMin, GridSelection.position.size.x, GridSelection.position.size.y); var layoutGrid = tilemap != null ? tilemap as GridLayout : grid as GridLayout; - + BoundsInt brushBounds = new BoundsInt(new Vector3Int(rect.x, rect.y, zPosition), new Vector3Int(rect.width, rect.height, 1)); if (GridPaintingState.activeBrushEditor != null) { - GridPaintingState.activeBrushEditor.OnPaintSceneGUI(layoutGrid, brushTarget, - new BoundsInt(new Vector3Int(rect.x, rect.y, 0), new Vector3Int(rect.width, rect.height, 1)), - EditModeToBrushTool(EditMode.editMode), m_MarqueeStart.HasValue || executing); + GridPaintingState.activeBrushEditor.OnPaintSceneGUI(layoutGrid, brushTarget, brushBounds + , EditModeToBrushTool(EditMode.editMode), m_MarqueeStart.HasValue || executing); } else // Fallback when user hasn't defined custom editor { - GridBrushEditorBase.OnPaintSceneGUIInternal(layoutGrid, brushTarget, new BoundsInt(new Vector3Int(rect.x, rect.y, 0), new Vector3Int(rect.width, rect.height, 1)), EditModeToBrushTool(EditMode.editMode), m_MarqueeStart.HasValue || executing); + GridBrushEditorBase.OnPaintSceneGUIInternal(layoutGrid, brushTarget, brushBounds + , EditModeToBrushTool(EditMode.editMode), m_MarqueeStart.HasValue || executing); } } diff --git a/Modules/TilemapEditor/Editor/Managed/TileUtility.cs b/Modules/TilemapEditor/Editor/Managed/TileUtility.cs deleted file mode 100644 index 0e60943817..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/TileUtility.cs +++ /dev/null @@ -1,26 +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 UnityEditor; -using UnityEngine; -using UnityEngine.Tilemaps; - -namespace UnityEditorInternal -{ - internal class TileUtility - { - [MenuItem("Assets/Create/Tile", priority = 357)] - public static void CreateNewTile() - { - string message = string.Format("Save tile'{0}':", "tile"); - string newAssetPath = EditorUtility.SaveFilePanelInProject("Save tile", "New Tile", "asset", message, ProjectWindowUtil.GetActiveFolderPath()); - - // If user canceled or save path is invalid, we can't create the tile - if (string.IsNullOrEmpty(newAssetPath)) - return; - - AssetDatabase.CreateAsset(ScriptableObject.CreateInstance(), newAssetPath); - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/TilemapCollider2DEditor.cs b/Modules/TilemapEditor/Editor/Managed/TilemapCollider2DEditor.cs deleted file mode 100644 index 4d538100a8..0000000000 --- a/Modules/TilemapEditor/Editor/Managed/TilemapCollider2DEditor.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 System; -using UnityEngine; -using UnityEngine.Tilemaps; - -namespace UnityEditor -{ - [CustomEditor(typeof(TilemapCollider2D))] - [CanEditMultipleObjects] - internal class TilemapCollider2DEditor : Collider2DEditorBase - { - public override void OnInspectorGUI() - { - serializedObject.Update(); - base.OnInspectorGUI(); - serializedObject.ApplyModifiedProperties(); - - FinalizeInspectorGUI(); - } - } -} diff --git a/Modules/TilemapEditor/Editor/Managed/TilemapEditor.cs b/Modules/TilemapEditor/Editor/Managed/TilemapEditor.cs index 36b436c627..292b2177bc 100644 --- a/Modules/TilemapEditor/Editor/Managed/TilemapEditor.cs +++ b/Modules/TilemapEditor/Editor/Managed/TilemapEditor.cs @@ -30,8 +30,10 @@ private static class Styles public static readonly GUIContent tilemapColorLabel = EditorGUIUtility.TrTextContent("Color", "Color tinting all Sprites from tiles in the tilemap"); public static readonly GUIContent tileAnchorLabel = EditorGUIUtility.TrTextContent("Tile Anchor", "Anchoring position for Sprites from tiles in the tilemap"); public static readonly GUIContent orientationLabel = EditorGUIUtility.TrTextContent("Orientation", "Orientation for tiles in the tilemap"); - public static readonly GUIContent pointTopHexagonCreateUndo = EditorGUIUtility.TrTextContent("Hexagonal Point Top Tilemap"); - public static readonly GUIContent flatTopHexagonCreateUndo = EditorGUIUtility.TrTextContent("Hexagonal Flat Top Tilemap"); + public static readonly string pointTopHexagonCreateUndo = L10n.Tr("Hexagonal Point Top Tilemap"); + public static readonly string flatTopHexagonCreateUndo = L10n.Tr("Hexagonal Flat Top Tilemap"); + public static readonly string isometricCreateUndo = L10n.Tr("Isometric Tilemap"); + public static readonly string isometricZAsYCreateUndo = L10n.Tr("Isometric Z As Y Tilemap"); } private void OnEnable() @@ -89,17 +91,28 @@ internal static void CreateRectangularTilemap() [MenuItem("GameObject/2D Object/Hexagonal Point Top Tilemap")] internal static void CreateHexagonalPointTopTilemap() { - CreateHexagonalTilemap(GridLayout.CellSwizzle.XYZ, Styles.pointTopHexagonCreateUndo.text); + CreateHexagonalTilemap(GridLayout.CellSwizzle.XYZ, Styles.pointTopHexagonCreateUndo); } [MenuItem("GameObject/2D Object/Hexagonal Flat Top Tilemap")] internal static void CreateHexagonalFlatTopTilemap() { - CreateHexagonalTilemap(GridLayout.CellSwizzle.YXZ, Styles.flatTopHexagonCreateUndo.text); + CreateHexagonalTilemap(GridLayout.CellSwizzle.YXZ, Styles.flatTopHexagonCreateUndo); } [MenuItem("GameObject/2D Object/Isometric Tilemap")] internal static void CreateIsometricTilemap() + { + CreateIsometricTilemap(GridLayout.CellLayout.Isometric, Styles.isometricCreateUndo); + } + + [MenuItem("GameObject/2D Object/Isometric Z As Y Tilemap")] + internal static void CreateIsometricZAsYTilemap() + { + CreateIsometricTilemap(GridLayout.CellLayout.IsometricZAsY, Styles.isometricZAsYCreateUndo); + } + + private static void CreateIsometricTilemap(GridLayout.CellLayout isometricLayout, string undoMessage) { var root = FindOrCreateRootGrid(); var uniqueName = GameObjectUtility.GetUniqueNameForSibling(root.transform, "Tilemap"); @@ -108,12 +121,16 @@ internal static void CreateIsometricTilemap() tilemapGO.transform.position = Vector3.zero; var grid = root.GetComponent(); - grid.cellLayout = Grid.CellLayout.Isometric; - grid.cellSize = new Vector3(1.0f, 0.5f, 0.0f); + // Case 1071703: Do not reset cell size if adding a new Tilemap to an existing Grid of the same layout + if (isometricLayout != grid.cellLayout) + { + grid.cellLayout = isometricLayout; + grid.cellSize = new Vector3(1.0f, 0.5f, 0.0f); + } var tilemapRenderer = tilemapGO.GetComponent(); tilemapRenderer.sortOrder = TilemapRenderer.SortOrder.TopRight; - Undo.RegisterCreatedObjectUndo(tilemapGO, "Create Isometric Tilemap"); + Undo.RegisterCreatedObjectUndo(tilemapGO, undoMessage); } private static void CreateHexagonalTilemap(GridLayout.CellSwizzle swizzle, string undoMessage) diff --git a/Modules/TilemapEditor/Editor/ScriptBindings/TilemapEditor.bindings.cs b/Modules/TilemapEditor/Editor/ScriptBindings/TilemapEditor.bindings.cs deleted file mode 100644 index 6a995971fa..0000000000 --- a/Modules/TilemapEditor/Editor/ScriptBindings/TilemapEditor.bindings.cs +++ /dev/null @@ -1,37 +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.Bindings; - -namespace UnityEditor -{ - [NativeHeader("Runtime/BaseClasses/GameObject.h")] - [NativeType(Header = "Modules/TilemapEditor/Editor/TilemapEditorUserSettings.h")] - [ExcludeFromPreset] - [ExcludeFromObjectFactory] - internal sealed partial class TilemapEditorUserSettings : Object - { - public enum FocusMode - { - None = 0, - Tilemap = 1, - Grid = 2 - } - - [NativeProperty(Name = "LastUsedPaletteFromInstance")] - public extern static GameObject lastUsedPalette - { - get; - set; - } - - [NativeProperty(Name = "FocusModeFromInstance")] - public extern static TilemapEditorUserSettings.FocusMode focusMode - { - get; - set; - } - } -} diff --git a/Modules/TreeEditor/TreeEditor.cs b/Modules/TreeEditor/TreeEditor.cs index 23a43f22f9..8ee5d00614 100644 --- a/Modules/TreeEditor/TreeEditor.cs +++ b/Modules/TreeEditor/TreeEditor.cs @@ -310,8 +310,6 @@ static void CreateNewTree(MenuCommand menuCommand) AssetDatabase.AddObjectToAsset(materialCutoutAsset, prefabAsset); AssetDatabase.AddObjectToAsset(data, prefabAsset); - PrefabUtility.ApplyPrefabInstance(prefabInstance); - GameObjectUtility.SetParentAndAlign(prefabInstance, menuCommand.context as GameObject); // Store Creation undo diff --git a/Modules/UIElements/Events/EventPool.cs b/Modules/UIElements/Events/EventPool.cs deleted file mode 100644 index ff1c8a63e5..0000000000 --- a/Modules/UIElements/Events/EventPool.cs +++ /dev/null @@ -1,26 +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.Collections.Generic; - -namespace UnityEngine.Experimental.UIElements -{ - class EventPool where T : EventBase, new() - { - private readonly Stack m_Stack = new Stack(); - - public T Get() - { - T evt = m_Stack.Count == 0 ? new T() : m_Stack.Pop(); - return evt; - } - - public void Release(T element) - { - if (m_Stack.Contains(element)) - Debug.LogError("Internal error. Trying to destroy object that is already released to pool."); - m_Stack.Push(element); - } - } -} diff --git a/Modules/UIElements/IDataWatchService.cs b/Modules/UIElements/IDataWatchService.cs deleted file mode 100644 index f0cd28feba..0000000000 --- a/Modules/UIElements/IDataWatchService.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 UnityEngine.Experimental.UIElements -{ - public interface IDataWatchHandle : IDisposable - { - Object watched { get; } - bool disposed { get; } - } - - internal interface IDataWatchService - { - IDataWatchHandle AddWatch(Object watched, Action onDataChanged); - void RemoveWatch(IDataWatchHandle handle); - void ForceDirtyNextPoll(Object obj); - } -} diff --git a/Modules/UIElements/ISerializableJsonDictionary.cs b/Modules/UIElements/ISerializableJsonDictionary.cs deleted file mode 100644 index c7c6aac3b1..0000000000 --- a/Modules/UIElements/ISerializableJsonDictionary.cs +++ /dev/null @@ -1,29 +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 UnityEngine; - -namespace UnityEngine.Experimental.UIElements -{ - internal interface ISerializableJsonDictionary - { - void Set(string key, T value) where T : class; - - T Get(string key) where T : class; - - T GetScriptable(string key) where T : ScriptableObject; - - void Overwrite(object obj, string key); - - bool ContainsKey(string key); - - void OnBeforeSerialize(); - - void OnAfterDeserialize(); - } -} diff --git a/Modules/UIElements/ITransform.cs b/Modules/UIElements/ITransform.cs deleted file mode 100644 index 88c681ec2b..0000000000 --- a/Modules/UIElements/ITransform.cs +++ /dev/null @@ -1,14 +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 UnityEngine.Experimental.UIElements -{ - public interface ITransform - { - Vector3 position { get; set; } - Quaternion rotation { get; set; } - Vector3 scale { get; set; } - Matrix4x4 matrix { get; } - } -} diff --git a/Modules/UIElements/ImmediateStylePainter.cs b/Modules/UIElements/ImmediateStylePainter.cs index 56e15fffdf..e6b037476e 100644 --- a/Modules/UIElements/ImmediateStylePainter.cs +++ b/Modules/UIElements/ImmediateStylePainter.cs @@ -119,18 +119,18 @@ public void DrawBackground() { IStyle style = currentElement.style; - // The background color is embedded in the texture/background image - if (style.backgroundImage.value != null) + if (style.backgroundColor != Color.clear) { - var painterParams = TextureStylePainterParameters.GetDefault(currentElement); + var painterParams = RectStylePainterParameters.GetDefault(currentElement); painterParams.border.SetWidth(0.0f); - DrawTexture(painterParams); + DrawRect(painterParams); } - else if (style.backgroundColor != Color.clear) + + if (style.backgroundImage.value != null) { - var painterParams = RectStylePainterParameters.GetDefault(currentElement); + var painterParams = TextureStylePainterParameters.GetDefault(currentElement); painterParams.border.SetWidth(0.0f); - DrawRect(painterParams); + DrawTexture(painterParams); } } diff --git a/Modules/UIElements/ManipulatorActivationFilter.cs b/Modules/UIElements/ManipulatorActivationFilter.cs deleted file mode 100644 index 7ff53eac02..0000000000 --- a/Modules/UIElements/ManipulatorActivationFilter.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 - -namespace UnityEngine.Experimental.UIElements -{ - public struct ManipulatorActivationFilter - { - public MouseButton button; - public EventModifiers modifiers; - public int clickCount; - - public bool Matches(IMouseEvent e) - { - // Default clickCount field value is 0 since we're in a struct -- this case is covered if the user - // did not explicitly set clickCount - var minClickCount = (clickCount == 0 || (e.clickCount >= clickCount)); - return button == (MouseButton)e.button && HasModifiers(e) && minClickCount; - } - - private bool HasModifiers(IMouseEvent e) - { - if (((modifiers & EventModifiers.Alt) != 0 && !e.altKey) || - ((modifiers & EventModifiers.Alt) == 0 && e.altKey)) - { - return false; - } - - if (((modifiers & EventModifiers.Control) != 0 && !e.ctrlKey) || - ((modifiers & EventModifiers.Control) == 0 && e.ctrlKey)) - { - return false; - } - - if (((modifiers & EventModifiers.Shift) != 0 && !e.shiftKey) || - ((modifiers & EventModifiers.Shift) == 0 && e.shiftKey)) - { - return false; - } - - return ((modifiers & EventModifiers.Command) == 0 || e.commandKey) && - ((modifiers & EventModifiers.Command) != 0 || !e.commandKey); - } - } -} diff --git a/Modules/UIElements/Manipulators.cs b/Modules/UIElements/Manipulators.cs deleted file mode 100644 index 23a51d9914..0000000000 --- a/Modules/UIElements/Manipulators.cs +++ /dev/null @@ -1,37 +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.Collections.Generic; - -namespace UnityEngine.Experimental.UIElements -{ - public interface IManipulator - { - VisualElement target { get; set; } - } - - public abstract class Manipulator : IManipulator - { - protected abstract void RegisterCallbacksOnTarget(); - protected abstract void UnregisterCallbacksFromTarget(); - - VisualElement m_Target; - public VisualElement target - { - get { return m_Target; } - set - { - if (target != null) - { - UnregisterCallbacksFromTarget(); - } - m_Target = value; - if (target != null) - { - RegisterCallbacksOnTarget(); - } - } - } - } -} diff --git a/Modules/UIElements/MouseButton.cs b/Modules/UIElements/MouseButton.cs deleted file mode 100644 index e131526377..0000000000 --- a/Modules/UIElements/MouseButton.cs +++ /dev/null @@ -1,13 +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 UnityEngine.Experimental.UIElements -{ - public enum MouseButton - { - LeftMouse = 0, - RightMouse = 1, - MiddleMouse = 2 - } -} diff --git a/Modules/UIElements/Spacing.cs b/Modules/UIElements/Spacing.cs deleted file mode 100644 index 1b6b7e913e..0000000000 --- a/Modules/UIElements/Spacing.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 - -namespace UnityEngine.Experimental.UIElements -{ - public struct Spacing - { - public float left, top, right, bottom; - - public float horizontal - { - get - { - return left + right; - } - } - - public float vertical - { - get - { - return top + bottom; - } - } - - public Spacing(float left, float top, float right, float bottom) - { - this.left = left; - this.top = top; - this.right = right; - this.bottom = bottom; - } - - public static Rect operator+(Rect r, Spacing a) - { - r.x -= a.left; - r.y -= a.top; - r.width += a.horizontal; - r.height += a.vertical; - return r; - } - - public static Rect operator-(Rect r, Spacing a) - { - r.x += a.left; - r.y += a.top; - r.width -= a.horizontal; - r.height -= a.vertical; - return r; - } - } -} diff --git a/Modules/UIElements/StylePainter.cs b/Modules/UIElements/StylePainter.cs index 29c4cc0fe4..0bca9f788a 100644 --- a/Modules/UIElements/StylePainter.cs +++ b/Modules/UIElements/StylePainter.cs @@ -114,9 +114,7 @@ public static TextureStylePainterParameters GetDefault(VisualElement ve) { rect = GUIUtility.AlignRectToDevice(ve.rect), uv = new Rect(0, 0, 1, 1), - // When the background color is not clear, we have to embed it into the texture... - // whereas if the color is clear, the white color is used... - color = (style.backgroundColor != Color.clear) ? (Color)style.backgroundColor : (Color)Color.white, + color = (Color)Color.white, texture = style.backgroundImage, scaleMode = style.backgroundScaleMode, sliceLeft = style.sliceLeft, diff --git a/Modules/UIElements/StyleSheets/StyleComplexSelectorExtensions.cs b/Modules/UIElements/StyleSheets/StyleComplexSelectorExtensions.cs deleted file mode 100644 index 3478cf0994..0000000000 --- a/Modules/UIElements/StyleSheets/StyleComplexSelectorExtensions.cs +++ /dev/null @@ -1,77 +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.Collections.Generic; -using UnityEngine.StyleSheets; - -namespace UnityEngine.Experimental.UIElements.StyleSheets -{ - // extension methods because StyleSelector must not depend on UIElements types - internal static class StyleComplexSelectorExtensions - { - struct PseudoStateData - { - public readonly PseudoStates state; - public readonly bool negate; - - public PseudoStateData(PseudoStates state, bool negate) - { - this.state = state; - this.negate = negate; - } - } - static Dictionary s_PseudoStates; - - public static void CachePseudoStateMasks(this StyleComplexSelector complexSelector) - { - // If we have already cached data on this selector, skip it - if (complexSelector.selectors[0].pseudoStateMask != -1) - return; - - // lazily build a cache of pseudo state names - if (s_PseudoStates == null) - { - s_PseudoStates = new Dictionary(); - s_PseudoStates["active"] = new PseudoStateData(PseudoStates.Active, false); - s_PseudoStates["hover"] = new PseudoStateData(PseudoStates.Hover, false); - s_PseudoStates["checked"] = new PseudoStateData(PseudoStates.Checked, false); - s_PseudoStates["selected"] = new PseudoStateData(PseudoStates.Selected, false); - s_PseudoStates["disabled"] = new PseudoStateData(PseudoStates.Disabled, false); - s_PseudoStates["focus"] = new PseudoStateData(PseudoStates.Focus, false); - - // A few substates can be negated, meaning them match if the flag is not set - s_PseudoStates["inactive"] = new PseudoStateData(PseudoStates.Active, true); - s_PseudoStates["enabled"] = new PseudoStateData(PseudoStates.Disabled, true); - } - - for (int j = 0, subCount = complexSelector.selectors.Length; j < subCount; j++) - { - StyleSelector selector = complexSelector.selectors[j]; - StyleSelectorPart[] parts = selector.parts; - PseudoStates pseudoClassMask = 0; - PseudoStates negatedPseudoClassMask = 0; - for (int i = 0; i < selector.parts.Length; i++) - { - if (selector.parts[i].type == StyleSelectorType.PseudoClass) - { - PseudoStateData data; - if (s_PseudoStates.TryGetValue(parts[i].value, out data)) - { - if (!data.negate) - pseudoClassMask |= data.state; - else - negatedPseudoClassMask |= data.state; - } - else - { - Debug.LogWarningFormat("Unknown pseudo class \"{0}\"", parts[i].value); - } - } - } - selector.pseudoStateMask = (int)pseudoClassMask; - selector.negatedPseudoStateMask = (int)negatedPseudoClassMask; - } - } - } -} diff --git a/Modules/UIElements/UXML/TemplateAsset.cs b/Modules/UIElements/UXML/TemplateAsset.cs deleted file mode 100644 index e7021a6b1d..0000000000 --- a/Modules/UIElements/UXML/TemplateAsset.cs +++ /dev/null @@ -1,46 +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.Assertions; - -namespace UnityEngine.Experimental.UIElements -{ - [Serializable] - internal class TemplateAsset : VisualElementAsset // - { - [SerializeField] - private string m_TemplateAlias; - - public string templateAlias - { - get { return m_TemplateAlias; } - set { m_TemplateAlias = value; } - } - - [SerializeField] - private List m_SlotUsages; - - internal List slotUsages - { - get { return m_SlotUsages; } - set { m_SlotUsages = value; } - } - - public TemplateAsset(string templateAlias) - : base(typeof(TemplateContainer).FullName) - { - Assert.IsFalse(string.IsNullOrEmpty(templateAlias), "Template alias must not be null or empty"); - m_TemplateAlias = templateAlias; - } - - public void AddSlotUsage(string slotName, int resId) - { - if (m_SlotUsages == null) - m_SlotUsages = new List(); - m_SlotUsages.Add(new VisualTreeAsset.SlotUsageEntry(slotName, resId)); - } - } -} diff --git a/Modules/UIElements/VisualElement.cs b/Modules/UIElements/VisualElement.cs index 43ab959327..ccd739578f 100644 --- a/Modules/UIElements/VisualElement.cs +++ b/Modules/UIElements/VisualElement.cs @@ -620,9 +620,25 @@ internal void SetPanel(BaseVisualElementPanel p) elements.Add(this); GatherAllChildren(elements); - foreach (var e in elements) + EventDispatcher.Gate? pDispatcherGate = null; + if (p?.dispatcher != null) { - e.ChangePanel(p); + pDispatcherGate = new EventDispatcher.Gate(p.dispatcher); + } + + EventDispatcher.Gate? panelDispatcherGate = null; + if (panel?.dispatcher != null && panel.dispatcher != p?.dispatcher) + { + panelDispatcherGate = new EventDispatcher.Gate(panel.dispatcher); + } + + using (pDispatcherGate) + using (panelDispatcherGate) + { + foreach (var e in elements) + { + e.ChangePanel(p); + } } } finally @@ -655,7 +671,7 @@ void ChangePanel(BaseVisualElementPanel p) using (var e = AttachToPanelEvent.GetPooled(prevPanel, p)) { e.target = this; - elementPanel.SendEvent(e, DispatchMode.Immediate); + elementPanel.SendEvent(e, DispatchMode.Default); } } diff --git a/Modules/UIElements/VisualElementDataWatch.cs b/Modules/UIElements/VisualElementDataWatch.cs deleted file mode 100644 index 55c9241652..0000000000 --- a/Modules/UIElements/VisualElementDataWatch.cs +++ /dev/null @@ -1,98 +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 UnityEngine.Experimental.UIElements -{ - public interface IUIElementDataWatchRequest : IDisposable {} - - public interface IUIElementDataWatch - { - IUIElementDataWatchRequest RegisterWatch(Object toWatch, Action watchNotification); - void UnregisterWatch(IUIElementDataWatchRequest requested); - } - - public partial class VisualElement : IUIElementDataWatch - { - private class DataWatchRequest : IUIElementDataWatchRequest, IVisualElementPanelActivatable - { - public Action notification { get; set; } - public Object watchedObject { get; set; } - public IDataWatchHandle requestedHandle { get; set; } - - private VisualElementPanelActivator m_Activator; - public VisualElement element { get; set; } - public DataWatchRequest(VisualElement handler) - { - element = handler; - m_Activator = new VisualElementPanelActivator(this); - } - - public void Start() - { - m_Activator.SetActive(true); - } - - public void Stop() - { - m_Activator.SetActive(false); - } - - public bool CanBeActivated() - { - return element != null && element.elementPanel != null && element.elementPanel.dataWatch != null; - } - - public void OnPanelActivate() - { - if (requestedHandle == null) - { - requestedHandle = element.elementPanel.dataWatch.AddWatch(watchedObject, notification); - } - } - - public void OnPanelDeactivate() - { - if (requestedHandle != null) - { - element.elementPanel.dataWatch.RemoveWatch(requestedHandle); - requestedHandle = null; - } - } - - public void Dispose() - { - Stop(); - } - } - - // this allows us to not expose all datawatch accessors directly on VisualElement class - public IUIElementDataWatch dataWatch - { - get { return this; } - } - - IUIElementDataWatchRequest IUIElementDataWatch.RegisterWatch(Object toWatch, Action watchNotification) - { - var datawatchRequest = new DataWatchRequest(this) - { - notification = watchNotification, - watchedObject = toWatch - }; - - datawatchRequest.Start(); - return datawatchRequest; - } - - void IUIElementDataWatch.UnregisterWatch(IUIElementDataWatchRequest requested) - { - DataWatchRequest r = requested as DataWatchRequest; - if (r != null) - { - r.Stop(); - } - } - } -} diff --git a/Modules/UIElements/VisualElementUtils.cs b/Modules/UIElements/VisualElementUtils.cs deleted file mode 100644 index 4d8ca467b3..0000000000 --- a/Modules/UIElements/VisualElementUtils.cs +++ /dev/null @@ -1,26 +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.Collections.Generic; - -namespace UnityEngine.Experimental.UIElements -{ - internal sealed class VisualElementUtils - { - private static readonly HashSet s_usedNames = new HashSet(); - - public static string GetUniqueName(string nameBase) - { - string name = nameBase; - int counter = 2; - while (s_usedNames.Contains(name)) - { - name = nameBase + counter; - counter++; - } - s_usedNames.Add(name); - return name; - } - } -} diff --git a/Modules/UIElementsDebuggerEditor/PanelPickerWindow.cs b/Modules/UIElementsDebuggerEditor/PanelPickerWindow.cs deleted file mode 100644 index 9f52785c20..0000000000 --- a/Modules/UIElementsDebuggerEditor/PanelPickerWindow.cs +++ /dev/null @@ -1,42 +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.Experimental.UIElements.Debugger -{ - class PanelPickerWindow : EditorWindow - { - private Action m_Callback; - private PickingData m_Data; - - internal static PanelPickerWindow Show(PickingData data, Action callback) - { - var overlayWindow = CreateInstance(); - overlayWindow.m_Data = data; - - overlayWindow.m_Pos = data.screenRect; - overlayWindow.m_Callback = callback; - overlayWindow.ShowPopup(); - overlayWindow.Focus(); - return overlayWindow; - } - - public void OnGUI() - { - UIElementsDebugger.ViewPanel? p = null; - if (m_Data.Draw(ref p, m_Data.screenRect)) - { - Close(); - m_Callback(p); - } - else if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) - { - Close(); - m_Callback(null); - } - } - } -} diff --git a/Modules/UnityEditorAnalyticsEditor/EditorAnalytics.bindings.cs b/Modules/UnityEditorAnalyticsEditor/EditorAnalytics.bindings.cs index 5bd23f2bf8..56e7db50de 100644 --- a/Modules/UnityEditorAnalyticsEditor/EditorAnalytics.bindings.cs +++ b/Modules/UnityEditorAnalyticsEditor/EditorAnalytics.bindings.cs @@ -83,6 +83,8 @@ internal static bool SendCollabOperation(object parameters) return EditorAnalytics.SendEvent("collabOperation", parameters); } + internal extern static bool SendAssetDownloadEvent(object parameters); + public extern static bool enabled { get; diff --git a/Modules/UnityWebRequest/FriendAttributes.cs b/Modules/UnityWebRequest/FriendAttributes.cs deleted file mode 100644 index d54a7d27f7..0000000000 --- a/Modules/UnityWebRequest/FriendAttributes.cs +++ /dev/null @@ -1,13 +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.Runtime.CompilerServices; - -// needed for UnityEngine.Networking.DownloadHandler.DownloadHandler -[assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAssetBundleModule")] -[assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAudioModule")] -[assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestTextureModule")] - -// needed for UnityEngine.WWWTranscoder -[assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestWWWModule")] diff --git a/Modules/UnityWebRequest/Public/CertificateHandler/CertificateHandler.bindings.cs b/Modules/UnityWebRequest/Public/CertificateHandler/CertificateHandler.bindings.cs deleted file mode 100644 index 9982c363da..0000000000 --- a/Modules/UnityWebRequest/Public/CertificateHandler/CertificateHandler.bindings.cs +++ /dev/null @@ -1,55 +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.Runtime.InteropServices; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEngine.Networking -{ - [StructLayout(LayoutKind.Sequential)] - [NativeHeader("Modules/UnityWebRequest/Public/CertificateHandler/CertificateHandlerScript.h")] - public class CertificateHandler : IDisposable - { - [System.NonSerialized] - internal IntPtr m_Ptr; - - extern private static IntPtr Create(CertificateHandler obj); - - [NativeMethod(IsThreadSafe = true)] - extern private void Release(); - - protected CertificateHandler() - { - m_Ptr = Create(this); - } - - ~CertificateHandler() - { - Dispose(); - } - - protected virtual bool ValidateCertificate(byte[] certificateData) - { - return false; - } - - [RequiredByNativeCode] - internal bool ValidateCertificateNative(byte[] certificateData) - { - return ValidateCertificate(certificateData); - } - - public void Dispose() - { - if (m_Ptr != IntPtr.Zero) - { - Release(); - m_Ptr = IntPtr.Zero; - } - } - - } -} diff --git a/Modules/UnityWebRequest/Public/MultipartFormHelper.cs b/Modules/UnityWebRequest/Public/MultipartFormHelper.cs deleted file mode 100644 index f21e344681..0000000000 --- a/Modules/UnityWebRequest/Public/MultipartFormHelper.cs +++ /dev/null @@ -1,157 +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; - -namespace UnityEngine.Networking -{ - public interface IMultipartFormSection - { - string sectionName { get; } - byte[] sectionData { get; } - string fileName { get; } // return null if not a file section - string contentType { get; } - } - - public class MultipartFormDataSection : IMultipartFormSection - { - private string name; - private byte[] data; - private string content; - - public MultipartFormDataSection(string name, byte[] data, string contentType) - { - if (data == null || data.Length < 1) - { - throw new ArgumentException("Cannot create a multipart form data section without body data"); - } - - this.name = name; - this.data = data; - this.content = contentType; - } - - public MultipartFormDataSection(string name, byte[] data) : this(name, data, null) - {} - - public MultipartFormDataSection(byte[] data) : this(null, data) - {} - - public MultipartFormDataSection(string name, string data, System.Text.Encoding encoding, string contentType) - { - if (data == null || data.Length < 1) - { - throw new ArgumentException("Cannot create a multipart form data section without body data"); - } - - byte[] dataBytes = encoding.GetBytes(data); - - this.name = name; - this.data = dataBytes; - - if (contentType != null && !contentType.Contains("encoding=")) - { - contentType = contentType.Trim() + "; encoding=" + encoding.WebName; - } - - this.content = contentType; - } - - public MultipartFormDataSection(string name, string data, string contentType) : this(name, data, System.Text.Encoding.UTF8, contentType) - {} - - public MultipartFormDataSection(string name, string data) : this(name, data, "text/plain") - {} - - public MultipartFormDataSection(string data) : this(null, data) - {} - - public string sectionName { get { return this.name; } } - public byte[] sectionData { get { return this.data; } } - public string fileName { get { return null; } } - public string contentType { get { return this.content; } } - } - - public class MultipartFormFileSection : IMultipartFormSection - { - private string name; - private byte[] data; - private string file; - private string content; - - private void Init(string name, byte[] data, string fileName, string contentType) - { - this.name = name; - this.data = data; - this.file = fileName; - this.content = contentType; - } - - public MultipartFormFileSection(string name, byte[] data, string fileName, string contentType) - { - if (data == null || data.Length < 1) - { - throw new ArgumentException("Cannot create a multipart form file section without body data"); - } - - if (string.IsNullOrEmpty(fileName)) - { - fileName = "file.dat"; - } - - if (string.IsNullOrEmpty(contentType)) - { - contentType = "application/octet-stream"; - } - - Init(name, data, fileName, contentType); - } - - public MultipartFormFileSection(byte[] data) : this(null, data, null, null) - {} - - public MultipartFormFileSection(string fileName, byte[] data) : this(null, data, fileName, null) - {} - - // String upload functions, for convenience - public MultipartFormFileSection(string name, string data, System.Text.Encoding dataEncoding, string fileName) - { - if (data == null || data.Length < 1) - { - throw new ArgumentException("Cannot create a multipart form file section without body data"); - } - - if (dataEncoding == null) - { - dataEncoding = System.Text.Encoding.UTF8; - } - - byte[] dataBytes = dataEncoding.GetBytes(data); - - if (string.IsNullOrEmpty(fileName)) - { - fileName = "file.txt"; - } - - if (string.IsNullOrEmpty(this.content)) - { - this.content = "text/plain; charset=" + dataEncoding.WebName; - } - - Init(name, dataBytes, fileName, this.content); - } - - public MultipartFormFileSection(string data, System.Text.Encoding dataEncoding, string fileName) : this(null, data, dataEncoding, fileName) - {} - - public MultipartFormFileSection(string data, string fileName) : this(data, null, fileName) - {} - - public string sectionName { get { return this.name; } } - public byte[] sectionData { get { return this.data; } } - public string fileName { get { return this.file; } } - public string contentType { get { return this.content; } } - } -} diff --git a/Modules/UnityWebRequest/Public/UploadHandler/UploadHandler.bindings.cs b/Modules/UnityWebRequest/Public/UploadHandler/UploadHandler.bindings.cs deleted file mode 100644 index 190ab10188..0000000000 --- a/Modules/UnityWebRequest/Public/UploadHandler/UploadHandler.bindings.cs +++ /dev/null @@ -1,129 +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.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngineInternal; -using UnityEngine.Bindings; - -namespace UnityEngine.Networking -{ - [StructLayout(LayoutKind.Sequential)] - [NativeHeader("Modules/UnityWebRequest/Public/UploadHandler/UploadHandler.h")] - public class UploadHandler : IDisposable - { - [System.NonSerialized] - internal IntPtr m_Ptr; - - [NativeMethod(IsThreadSafe = true)] - private extern void Release(); - - internal UploadHandler() {} - - ~UploadHandler() - { - Dispose(); - } - - public void Dispose() - { - if (m_Ptr != IntPtr.Zero) - { - Release(); - m_Ptr = IntPtr.Zero; - } - } - - public byte[] data - { - get - { - return GetData(); - } - } - - public string contentType - { - get - { - return GetContentType(); - } - set - { - SetContentType(value); - } - } - - public float progress - { - get - { - return GetProgress(); - } - } - - internal virtual byte[] GetData() { return null; } - internal virtual string GetContentType() { return "text/plain"; } - internal virtual void SetContentType(string newContentType) {} - internal virtual float GetProgress() { return 0.5f; } - } - - [StructLayout(LayoutKind.Sequential)] - [NativeHeader("Modules/UnityWebRequest/Public/UploadHandler/UploadHandlerRaw.h")] - public sealed class UploadHandlerRaw : UploadHandler - { - private static extern IntPtr Create(UploadHandlerRaw self, byte[] data); - - public UploadHandlerRaw(byte[] data) - { - if (data != null && data.Length == 0) - throw new ArgumentException("Cannot create a data handler without payload data"); - m_Ptr = Create(this, data); - } - - [NativeMethod("GetContentType")] - private extern string InternalGetContentType(); - - [NativeMethod("SetContentType")] - private extern void InternalSetContentType(string newContentType); - - private extern byte[] InternalGetData(); - - [NativeMethod("GetProgress")] - private extern float InternalGetProgress(); - - internal override string GetContentType() { return InternalGetContentType(); } - - internal override void SetContentType(string newContentType) - { - InternalSetContentType(newContentType); - } - - internal override byte[] GetData() - { - return InternalGetData(); - } - - internal override float GetProgress() - { - return InternalGetProgress(); - } - - } - - [StructLayout(LayoutKind.Sequential)] - [NativeHeader("Modules/UnityWebRequest/Public/UploadHandler/UploadHandlerFile.h")] - public sealed class UploadHandlerFile : UploadHandler - { - [NativeThrows] - private static extern IntPtr Create(UploadHandlerFile self, string filePath); - - public UploadHandlerFile(string filePath) - { - m_Ptr = Create(this, filePath); - } - } -} diff --git a/Modules/UnityWebRequest/Public/WebRequest.deprecated.cs b/Modules/UnityWebRequest/Public/WebRequest.deprecated.cs deleted file mode 100644 index 9fe439a97b..0000000000 --- a/Modules/UnityWebRequest/Public/WebRequest.deprecated.cs +++ /dev/null @@ -1,16 +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 UnityEngine.Networking -{ - public partial class UnityWebRequest - { - [System.Obsolete("UnityWebRequest.isError has been renamed to isNetworkError for clarity. (UnityUpgradable) -> isNetworkError", false)] - public bool isError - { - get { return isNetworkError; } - } - } -} diff --git a/Modules/UnityWebRequestAudio/Public/DownloadHandlerAudio.bindings.cs b/Modules/UnityWebRequestAudio/Public/DownloadHandlerAudio.bindings.cs index dbc8c4accb..75c3447496 100644 --- a/Modules/UnityWebRequestAudio/Public/DownloadHandlerAudio.bindings.cs +++ b/Modules/UnityWebRequestAudio/Public/DownloadHandlerAudio.bindings.cs @@ -40,6 +40,7 @@ protected override string GetText() throw new System.NotSupportedException("String access is not supported for audio clips"); } + [NativeThrows] public extern AudioClip audioClip { get; } public extern bool streamAudio { get; set; } diff --git a/Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.bindings.cs b/Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.bindings.cs deleted file mode 100644 index 1771136c38..0000000000 --- a/Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.bindings.cs +++ /dev/null @@ -1,77 +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.Runtime.InteropServices; -using UnityEngine.Bindings; -using UnityEngineInternal; - -namespace UnityEngine.Networking -{ - [StructLayout(LayoutKind.Sequential)] - [NativeHeader("Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.h")] - public sealed class DownloadHandlerTexture : DownloadHandler - { - private Texture2D mTexture; - private bool mHasTexture; - private bool mNonReadable; - - private static extern IntPtr Create(DownloadHandlerTexture obj, bool readable); - - private void InternalCreateTexture(bool readable) - { - m_Ptr = Create(this, readable); - } - - public DownloadHandlerTexture() - { - InternalCreateTexture(true); - } - - public DownloadHandlerTexture(bool readable) - { - InternalCreateTexture(readable); - mNonReadable = !readable; - } - - protected override byte[] GetData() - { - return InternalGetByteArray(this); - } - - public Texture2D texture - { - get { return InternalGetTexture(); } - } - - private Texture2D InternalGetTexture() - { - if (mHasTexture) - { - if (mTexture == null) - { - // this is corner case when this DH survives scene reload, while texture does not - mTexture = new Texture2D(2, 2); - mTexture.LoadImage(GetData(), mNonReadable); - } - } - else if (mTexture == null) - { - mTexture = InternalGetTextureNative(); - mHasTexture = true; - } - - return mTexture; - } - - [NativeThrows] - private extern Texture2D InternalGetTextureNative(); - - public static Texture2D GetContent(UnityWebRequest www) - { - return GetCheckedDownloader(www).texture; - } - - } -} diff --git a/Modules/UnityWebRequestTexture/UnityWebRequestTexture.cs b/Modules/UnityWebRequestTexture/UnityWebRequestTexture.cs deleted file mode 100644 index 8a9a730010..0000000000 --- a/Modules/UnityWebRequestTexture/UnityWebRequestTexture.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 System; - -namespace UnityEngine.Networking -{ - public static class UnityWebRequestTexture - { - public static UnityWebRequest GetTexture(string uri) - { - return UnityWebRequestTexture.GetTexture(uri, false); - } - - public static UnityWebRequest GetTexture(Uri uri) - { - return UnityWebRequestTexture.GetTexture(uri, false); - } - - public static UnityWebRequest GetTexture(string uri, bool nonReadable) - { - return new UnityWebRequest(uri, UnityWebRequest.kHttpVerbGET, new DownloadHandlerTexture(!nonReadable), null); - } - - public static UnityWebRequest GetTexture(Uri uri, bool nonReadable) - { - return new UnityWebRequest(uri, UnityWebRequest.kHttpVerbGET, new DownloadHandlerTexture(!nonReadable), null); - } - - } -} diff --git a/Modules/VFX/Public/ScriptBindings/VFXEnums.bindings.cs b/Modules/VFX/Public/ScriptBindings/VFXEnums.bindings.cs index 998ba30d89..c1dc69eb80 100644 --- a/Modules/VFX/Public/ScriptBindings/VFXEnums.bindings.cs +++ b/Modules/VFX/Public/ScriptBindings/VFXEnums.bindings.cs @@ -63,7 +63,7 @@ internal enum VFXExpressionOperation // matrix operations TRSToMatrix, - InverseTRS, + InverseMatrix, ExtractPositionFromMatrix, ExtractAnglesFromMatrix, ExtractScaleFromMatrix, @@ -123,7 +123,10 @@ internal enum VFXExpressionOperation // Logical operations LogicalAnd, LogicalOr, - LogicalNot + LogicalNot, + + // This allows backward compatibility + InverseTRS = InverseMatrix, } internal enum VFXValueType diff --git a/Modules/VFX/Public/ScriptBindings/VisualEffect.bindings.cs b/Modules/VFX/Public/ScriptBindings/VisualEffect.bindings.cs index 2d107d7a9c..2401ade069 100644 --- a/Modules/VFX/Public/ScriptBindings/VisualEffect.bindings.cs +++ b/Modules/VFX/Public/ScriptBindings/VisualEffect.bindings.cs @@ -43,9 +43,29 @@ public VFXEventAttribute CreateVFXEventAttribute() return vfxEventAttribute; } - extern public void Play(VFXEventAttribute eventAttribute = null); - extern public void Stop(VFXEventAttribute eventAttribute = null); - extern public void SendEvent(string eventName, VFXEventAttribute eventAttribute = null); + extern public void Play(VFXEventAttribute eventAttribute); + + public void Play() + { + Play(null); + } + + extern public void Stop(VFXEventAttribute eventAttribute); + public void Stop() + { + Stop(null); + } + + extern public void SendEvent(int eventNameID, VFXEventAttribute eventAttribute); + public void SendEvent(string eventName) + { + SendEvent(Shader.PropertyToID(eventName), null); + } + + public void SendEvent(string eventName, VFXEventAttribute eventAttribute) + { + SendEvent(Shader.PropertyToID(eventName), null); + } extern public void Reinit(); extern public void AdvanceOneFrame(); diff --git a/Modules/VFXEditor/Public/ScriptBindings/VFXMemorySerializer.bindings.cs b/Modules/VFXEditor/Public/ScriptBindings/VFXMemorySerializer.bindings.cs index a5d4a5cf31..4773276ced 100644 --- a/Modules/VFXEditor/Public/ScriptBindings/VFXMemorySerializer.bindings.cs +++ b/Modules/VFXEditor/Public/ScriptBindings/VFXMemorySerializer.bindings.cs @@ -19,8 +19,23 @@ internal static class VFXMemorySerializer { extern public static string StoreObjects(ScriptableObject[] objects); - [FreeFunction(Name = "VFXMemorySerializerBindings::Internal_ExtractObjects")] - extern public static ScriptableObject[] ExtractObjects(string data, bool asACopy); + extern public static byte[] StoreObjectsToByteArray(ScriptableObject[] objects, CompressionLevel compressionLevel = CompressionLevel.None); + + [FreeFunction(Name = "VFXMemorySerializerBindings::Internal_ExtractObjects_FromString")] + extern private static ScriptableObject[] ExtractObjects_FromString(string data, bool asACopy); + + [FreeFunction(Name = "VFXMemorySerializerBindings::Internal_ExtractObjects_FromByteArray")] + extern private static ScriptableObject[] ExtractObjects_FromByteArray(byte[] data, bool asACopy); + + public static ScriptableObject[] ExtractObjects(string data, bool asACopy) + { + return ExtractObjects_FromString(data, asACopy); + } + + public static ScriptableObject[] ExtractObjects(byte[] data, bool asACopy) + { + return ExtractObjects_FromByteArray(data, asACopy); + } [FreeFunction(Name = "VFXMemorySerializerBindings::Internal_DuplicateObjects")] extern public static ScriptableObject[] DuplicateObjects(ScriptableObject[] objects); diff --git a/Modules/VFXEditor/Public/ScriptBindings/VisualEffectResource.bindings.cs b/Modules/VFXEditor/Public/ScriptBindings/VisualEffectResource.bindings.cs index 8b16ca9b96..10b9a80910 100644 --- a/Modules/VFXEditor/Public/ScriptBindings/VisualEffectResource.bindings.cs +++ b/Modules/VFXEditor/Public/ScriptBindings/VisualEffectResource.bindings.cs @@ -35,6 +35,7 @@ internal struct VFXRendererSettings public bool receiveShadows; public ReflectionProbeUsage reflectionProbeUsage; public LightProbeUsage lightProbeUsage; + public int transparencyPriority; } [UsedByNativeCode] diff --git a/Modules/XR/ScriptBindings/XRInput.bindings.cs b/Modules/XR/ScriptBindings/XRInput.bindings.cs index 461c5f7a68..b836986d97 100644 --- a/Modules/XR/ScriptBindings/XRInput.bindings.cs +++ b/Modules/XR/ScriptBindings/XRInput.bindings.cs @@ -20,13 +20,11 @@ public struct HapticCapabilities : IEquatable bool m_SupportsImpulse; bool m_SupportsBuffer; uint m_BufferFrequencyHz; - uint m_BufferMaxSize; public uint numChannels { get { return m_NumChannels; } internal set { m_NumChannels = value; } } public bool supportsImpulse { get { return m_SupportsImpulse; } internal set { m_SupportsImpulse = value; } } public bool supportsBuffer { get { return m_SupportsBuffer; } internal set { m_SupportsBuffer = value; } } public uint bufferFrequencyHz { get { return m_BufferFrequencyHz; } internal set { m_BufferFrequencyHz = value; } } - public uint bufferMaxSize { get { return m_BufferMaxSize; } internal set { m_BufferMaxSize = value; } } public override bool Equals(object obj) { @@ -41,8 +39,7 @@ public bool Equals(HapticCapabilities other) return numChannels == other.numChannels && supportsImpulse == other.supportsImpulse && supportsBuffer == other.supportsBuffer && - bufferFrequencyHz == other.bufferFrequencyHz && - bufferMaxSize == other.bufferMaxSize; + bufferFrequencyHz == other.bufferFrequencyHz; } public override int GetHashCode() @@ -50,68 +47,78 @@ public override int GetHashCode() return numChannels.GetHashCode() ^ (supportsImpulse.GetHashCode() << 1) ^ (supportsBuffer.GetHashCode() >> 1) ^ - (bufferFrequencyHz.GetHashCode() << 2) ^ - (bufferMaxSize.GetHashCode() >> 2); + (bufferFrequencyHz.GetHashCode() << 2); + } + + public static bool operator==(HapticCapabilities a, HapticCapabilities b) + { + return a.Equals(b); + } + + public static bool operator!=(HapticCapabilities a, HapticCapabilities b) + { + return !(a == b); } } + [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] [NativeConditional("ENABLE_VR")] - public struct HapticState : IEquatable + [NativeHeader("Modules/XR/Subsystems/Input/Public/XRInputTrackingFacade.h")] + public struct InputDevice : IEquatable { - uint m_SamplesQueued; - uint m_SamplesAvailable; + private UInt64 m_DeviceId; - public uint samplesQueued { get { return m_SamplesQueued; } internal set { m_SamplesQueued = value; } } - public uint samplesAvailable { get { return m_SamplesAvailable; } internal set { m_SamplesAvailable = value; } } + internal InputDevice(UInt64 deviceId) { m_DeviceId = deviceId; } + + public bool IsValid { get { return InputTracking.IsDeviceValid(m_DeviceId); } } + + // Haptics + public bool SendHapticImpulse(uint channel, float amplitude, float duration = 1.0f) { return InputTracking.SendHapticImpulse(m_DeviceId, channel, amplitude, duration); } + public bool SendHapticBuffer(uint channel, byte[] buffer) { return InputTracking.SendHapticBuffer(m_DeviceId, channel, buffer); } + public bool TryGetHapticCapabilities(out HapticCapabilities capabilities) { return InputTracking.TryGetHapticCapabilities(m_DeviceId, out capabilities); } + public void StopHaptics() { InputTracking.StopHaptics(m_DeviceId); } public override bool Equals(object obj) { - if (!(obj is HapticState)) + if (!(obj is InputDevice)) return false; - return Equals((HapticState)obj); + return Equals((InputDevice)obj); } - public bool Equals(HapticState other) + public bool Equals(InputDevice other) { - return samplesQueued == other.samplesQueued && - samplesAvailable == other.samplesAvailable; + return m_DeviceId == other.m_DeviceId; } public override int GetHashCode() { - return samplesQueued.GetHashCode() ^ (samplesAvailable.GetHashCode() << 2); + return m_DeviceId.GetHashCode(); + } + + public static bool operator==(InputDevice a, InputDevice b) + { + return a.Equals(b); + } + + public static bool operator!=(InputDevice a, InputDevice b) + { + return !(a == b); } } [NativeHeader("Modules/XR/Subsystems/Input/Public/XRInputTrackingFacade.h")] [NativeConditional("ENABLE_VR")] [StaticAccessor("XRInputTrackingFacade::Get()", StaticAccessorType.Dot)] - public partial class InputHaptic + public partial class InputDevices { - [NativeConditional("ENABLE_VR")] - bool SendImpulse(XRNode node, uint channel, float amplitude) { return SendImpulse(node, channel, amplitude, 1.0f); } - - [NativeConditional("ENABLE_VR")] - [NativeMethod("SendHapticImpulse")] - extern public static bool SendImpulse(XRNode node, uint channel, float amplitude, [UnityEngine.Internal.DefaultValue("1.0f")] float frequency); - - [NativeConditional("ENABLE_VR")] - [NativeMethod("SendHapticBuffer")] - extern public static bool SendBuffer(XRNode node, uint channel, byte[] buffer); - - [NativeConditional("ENABLE_VR", "false")] - [NativeMethod("TryGetHapticCapabilities")] - extern public static bool TryGetCapabilities(XRNode node, out HapticCapabilities capabilities); - - [NativeConditional("ENABLE_VR", "false")] - [NativeMethod("TryGetHapticState")] - extern public static bool TryGetState(XRNode node, out HapticState state); - - [NativeConditional("ENABLE_VR")] - [NativeMethod("StopHaptics")] - extern public static void Stop(XRNode node); + [NativeConditional("ENABLE_VR", "InputDevice::Identity")] + public static InputDevice GetDeviceAtXRNode(XRNode node) + { + UInt64 deviceId = InputTracking.GetDeviceIdAtXRNode(node); + return new InputDevice(deviceId); + } } [NativeHeader("Modules/XR/Subsystems/Input/Public/XRInputTrackingFacade.h")] @@ -156,5 +163,13 @@ extern public static bool disablePositionalTracking [NativeName("SetPositionalTrackingDisabled")] set; } + + internal static extern bool SendHapticImpulse(UInt64 deviceId, uint channel, float amplitude, float duration); + internal static extern bool SendHapticBuffer(UInt64 deviceId, uint channel, byte[] buffer); + internal static extern bool TryGetHapticCapabilities(UInt64 deviceId, out HapticCapabilities capabilities); + internal static extern void StopHaptics(UInt64 deviceId); + + internal static extern bool IsDeviceValid(UInt64 deviceId); + internal static extern UInt64 GetDeviceIdAtXRNode(XRNode node); } } diff --git a/Projects/CSharp/UnityEngine.csproj b/Projects/CSharp/UnityEngine.csproj index b285e968a3..953308b49b 100644 --- a/Projects/CSharp/UnityEngine.csproj +++ b/Projects/CSharp/UnityEngine.csproj @@ -792,6 +792,9 @@ Runtime\Export\Scripting\ExtensionOfNativeClassAttribute.cs + + Runtime\Export\Scripting\GarbageCollector.bindings.cs + Runtime\Export\Scripting\PreserveAttribute.cs @@ -1485,6 +1488,12 @@ Modules\Substance\SubstanceUtility.cs + + Modules\Terrain\Public\BrushTransform.cs + + + Modules\Terrain\Public\PaintContext.cs + Modules\Terrain\Public\Terrain.bindings.cs @@ -1503,12 +1512,18 @@ Modules\TextCore\Managed\AssemblyInfo.cs + + Modules\TextCore\Managed\FaceInfo.cs + Modules\TextCore\Managed\Glyph.cs Modules\TextCore\ScriptBindings\FontEngine.bindings.cs + + Modules\TextCore\ScriptBindings\GlyphMarshallingStruct.cs + Modules\TextRendering\FontStyle.cs diff --git a/Projects/CSharp/UnityReferenceSource.sln b/Projects/CSharp/UnityReferenceSource.sln deleted file mode 100644 index 81dd1fbc79..0000000000 --- a/Projects/CSharp/UnityReferenceSource.sln +++ /dev/null @@ -1,52 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 -MinimumVisualStudioVersion = 10.0.40219.1 - -Project("{840379C4-B6F5-7CA3-A826-FA675F01E79C}") = "DataContract", "..\..\Tools\PackageManager\DataContract\DataContract.csproj", "{A15E35A9-22E8-4A79-B6CE-C0984062DAC6}" -EndProject -Project("{840379C4-B6F5-7CA3-A826-FA675F01E79C}") = "Unity.CecilTools", "..\..\Tools\Unity.CecilTools\Unity.CecilTools.csproj", "{35FF4EBD-85F0-4727-8AC0-32AE4F3723D0}" -EndProject -Project("{840379C4-B6F5-7CA3-A826-FA675F01E79C}") = "Unity.SerializationLogic", "..\..\Tools\Unity.SerializationLogic\Unity.SerializationLogic.csproj", "{A6749DFF-E369-4FE6-9019-6B7C555E80EA}" -EndProject -Project("{840379C4-B6F5-7CA3-A826-FA675F01E79C}") = "UNetWeaver", "..\..\Extensions\Networking\Weaver\UNetWeaver.csproj", "{709222FD-15C2-497D-8B31-366ADCC074CD}" -EndProject -Project("{840379C4-B6F5-7CA3-A826-FA675F01E79C}") = "UnityEngine", "UnityEngine.csproj", "{F0499708-3EB6-4026-8362-97E6FFC4E7C8}" -EndProject -Project("{840379C4-B6F5-7CA3-A826-FA675F01E79C}") = "UnityEditor", "UnityEditor.csproj", "{016C8D73-3641-47FB-8D33-7A015A7EC7DB}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {A15E35A9-22E8-4A79-B6CE-C0984062DAC6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A15E35A9-22E8-4A79-B6CE-C0984062DAC6}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A15E35A9-22E8-4A79-B6CE-C0984062DAC6}.Release|Any CPU.ActiveCfg = Debug|Any CPU - {A15E35A9-22E8-4A79-B6CE-C0984062DAC6}.Release|Any CPU.Build.0 = Debug|Any CPU - {35FF4EBD-85F0-4727-8AC0-32AE4F3723D0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {35FF4EBD-85F0-4727-8AC0-32AE4F3723D0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {35FF4EBD-85F0-4727-8AC0-32AE4F3723D0}.Release|Any CPU.ActiveCfg = Debug|Any CPU - {35FF4EBD-85F0-4727-8AC0-32AE4F3723D0}.Release|Any CPU.Build.0 = Debug|Any CPU - {A6749DFF-E369-4FE6-9019-6B7C555E80EA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A6749DFF-E369-4FE6-9019-6B7C555E80EA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A6749DFF-E369-4FE6-9019-6B7C555E80EA}.Release|Any CPU.ActiveCfg = Debug|Any CPU - {A6749DFF-E369-4FE6-9019-6B7C555E80EA}.Release|Any CPU.Build.0 = Debug|Any CPU - {709222FD-15C2-497D-8B31-366ADCC074CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {709222FD-15C2-497D-8B31-366ADCC074CD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {709222FD-15C2-497D-8B31-366ADCC074CD}.Release|Any CPU.ActiveCfg = Debug|Any CPU - {709222FD-15C2-497D-8B31-366ADCC074CD}.Release|Any CPU.Build.0 = Debug|Any CPU - {F0499708-3EB6-4026-8362-97E6FFC4E7C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F0499708-3EB6-4026-8362-97E6FFC4E7C8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F0499708-3EB6-4026-8362-97E6FFC4E7C8}.Release|Any CPU.ActiveCfg = Debug|Any CPU - {F0499708-3EB6-4026-8362-97E6FFC4E7C8}.Release|Any CPU.Build.0 = Debug|Any CPU - {016C8D73-3641-47FB-8D33-7A015A7EC7DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {016C8D73-3641-47FB-8D33-7A015A7EC7DB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {016C8D73-3641-47FB-8D33-7A015A7EC7DB}.Release|Any CPU.ActiveCfg = Debug|Any CPU - {016C8D73-3641-47FB-8D33-7A015A7EC7DB}.Release|Any CPU.Build.0 = Debug|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/README.md b/README.md index b8559e74df..9d239fc5b0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -## Unity 2018.3.0a11 C# reference source code +## Unity 2018.3.0b6 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/2D/Common/ScriptBindings/SpriteDataAccess.bindings.cs b/Runtime/2D/Common/ScriptBindings/SpriteDataAccess.bindings.cs index feea57170f..7db928fc8d 100644 --- a/Runtime/2D/Common/ScriptBindings/SpriteDataAccess.bindings.cs +++ b/Runtime/2D/Common/ScriptBindings/SpriteDataAccess.bindings.cs @@ -185,7 +185,7 @@ public static void SetBones(this Sprite sprite, SpriteBone[] src) extern private static SpriteChannelInfo GetBoneWeightsInfo(Sprite sprite); unsafe extern private static void SetBoneWeightsData(Sprite sprite, void* src, int count); - extern private static AtomicSafetyHandle GetSafetyHandle(this Sprite sprite); + extern internal static AtomicSafetyHandle GetSafetyHandle(this Sprite sprite); } [NativeHeader("Runtime/2D/Common/SpriteDataAccess.h")] diff --git a/Runtime/2D/Sorting/ScriptBindings/SortingGroup.bindings.cs b/Runtime/2D/Sorting/ScriptBindings/SortingGroup.bindings.cs deleted file mode 100644 index 8ddb72d8f9..0000000000 --- a/Runtime/2D/Sorting/ScriptBindings/SortingGroup.bindings.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 System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEngine.Rendering -{ - [RequireComponent(typeof(Transform))] - [NativeType(Header = "Runtime/2D/Sorting/SortingGroup.h")] - public sealed partial class SortingGroup : Behaviour - { - public extern string sortingLayerName { get; set; } - public extern int sortingLayerID { get; set; } - public extern int sortingOrder { get; set; } - internal extern int sortingGroupID { get; } - internal extern int sortingGroupOrder { get; } - internal extern int index { get; } - } -} diff --git a/Runtime/AR/Tango/ScriptBindings/Tango.bindings.cs b/Runtime/AR/Tango/ScriptBindings/Tango.bindings.cs index d075d899e2..9a40d7718b 100644 --- a/Runtime/AR/Tango/ScriptBindings/Tango.bindings.cs +++ b/Runtime/AR/Tango/ScriptBindings/Tango.bindings.cs @@ -13,24 +13,6 @@ namespace UnityEngine.XR.Tango { - // This must correspond to Tango::CoordinateFrame in TangoTypes.h - internal enum CoordinateFrame - { - GlobalWGS84 = 0, - AreaDescription, - StartOfService, - PreviousDevicePose, - Device, - IMU, - Display, - CameraColor, - CameraDepth, - CameraFisheye, - UUID, - Invalid, - MaxCoordinateFrameType - } - internal enum PoseStatus { Initializing = 0, @@ -41,31 +23,16 @@ internal enum PoseStatus [UsedByNativeCode] [NativeHeader("ARScriptingClasses.h")] - [StructLayout(LayoutKind.Explicit, Size = 8)] - internal struct CoordinateFramePair - { - [FieldOffset(0)] public CoordinateFrame baseFrame; - [FieldOffset(4)] public CoordinateFrame targetFrame; - } - - [UsedByNativeCode] - [NativeHeader("ARScriptingClasses.h")] - [StructLayout(LayoutKind.Explicit, Size = 92)] internal struct PoseData { - [FieldOffset(0)] public uint version; - [FieldOffset(8)] public double timestamp; - [FieldOffset(16)] public double orientation_x; - [FieldOffset(24)] public double orientation_y; - [FieldOffset(32)] public double orientation_z; - [FieldOffset(40)] public double orientation_w; - [FieldOffset(48)] public double translation_x; - [FieldOffset(56)] public double translation_y; - [FieldOffset(64)] public double translation_z; - [FieldOffset(72)] public PoseStatus statusCode; - [FieldOffset(76)] public CoordinateFramePair frame; - [FieldOffset(84)] public uint confidence; - [FieldOffset(88)] public float accuracy; + public double orientation_x; + public double orientation_y; + public double orientation_z; + public double orientation_w; + public double translation_x; + public double translation_y; + public double translation_z; + public PoseStatus statusCode; public Quaternion rotation { @@ -78,24 +45,15 @@ public Vector3 position } } - [NativeHeader("Runtime/AR/Tango/TangoScriptApi.h")] [NativeConditional("PLATFORM_ANDROID")] internal static partial class TangoInputTracking { - extern private static bool Internal_TryGetPoseAtTime(double time, ScreenOrientation screenOrientation, - CoordinateFrame baseFrame, CoordinateFrame targetFrame, out PoseData pose); - - internal static bool TryGetPoseAtTime(out PoseData pose, CoordinateFrame baseFrame, CoordinateFrame targetFrame, - double time, ScreenOrientation screenOrientation) - { - return Internal_TryGetPoseAtTime(time, screenOrientation, baseFrame, targetFrame, out pose); - } + extern private static bool Internal_TryGetPoseAtTime(out PoseData pose); - internal static bool TryGetPoseAtTime(out PoseData pose, CoordinateFrame baseFrame, CoordinateFrame targetFrame, - double time = 0.0) + internal static bool TryGetPoseAtTime(out PoseData pose) { - return Internal_TryGetPoseAtTime(time, Screen.orientation, baseFrame, targetFrame, out pose); + return Internal_TryGetPoseAtTime(out pose); } } } diff --git a/Runtime/Animation/Managed/Animation.deprecated.cs b/Runtime/Animation/Managed/Animation.deprecated.cs deleted file mode 100644 index 63eb49250c..0000000000 --- a/Runtime/Animation/Managed/Animation.deprecated.cs +++ /dev/null @@ -1,132 +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; - -// This file is only used by the ScriptUpdater - -namespace UnityEditorInternal -{ - [System.Obsolete("Transition is obsolete. Use UnityEditor.Animations.AnimatorTransition instead (UnityUpgradable) -> UnityEditor.Animations.AnimatorTransition", true)] - [NativeClass(null)] - public partial class Transition : Object - { - /* - ----------------------------------------------------------------------------------------------------------------- - The following members have been moved to base classes in the target class (which by itself is a breaking change - but since those types were *internal* it does not worth the work to fix updater/validation/configure more updates) - ----------------------------------------------------------------------------------------------------------------- - public string uniqueName { get { return string.Empty; } } - public int uniqueNameHash { get { return -1; } } - public int conditionCount { get { return -1; } } - - public float duration { get { return -1.0f; } set {} } - public float offset { get { return -1.0f; } set {} } - - public bool atomic { get { return false; } set {} } - public bool solo { get { return false; } set {} } - public bool mute { get { return false; } set {} } - public bool canTransitionToSelf { get { return false; } set {} } - - public State srcState { get { return default(State); } } - public State dstState { get { return default(State); } } - public AnimatorCondition GetCondition(int index) { return default(AnimatorCondition); } - public AnimatorCondition AddCondition() { return default(AnimatorCondition); } - - public GUIContent GetTransitionContentForRect(Rect rect) { return default(GUIContent); } - */ - } - - [System.Obsolete("StateMachine is obsolete. Use UnityEditor.Animations.AnimatorStateMachine instead (UnityUpgradable) -> UnityEditor.Animations.AnimatorStateMachine", true)] - [NativeClass(null)] - public partial class StateMachine : Object - { - /* - ----------------------------------------------------------------------------------------------------------------- - The following members have been moved to base classes in the target class (which by itself is a breaking change - but since those types were *internal* it does not worth the work to fix updater/validation/configure more updates) - ----------------------------------------------------------------------------------------------------------------- - public int stateCount { get { return -1; } } - public int stateMachineCount { get { return -1; } } - public int motionSetCount { get { return -1; } } - */ - - public State defaultState { get { return default(State); } set {} } - public Vector3 anyStatePosition { get { return default(Vector3); } set {} } - public Vector3 parentStateMachinePosition { get { return default(Vector3); } set {} } - public State GetState(int index) { return default(State); } - public State AddState(string stateName) { return default(State); } - public StateMachine GetStateMachine(int index) { return default(StateMachine); } - public StateMachine AddStateMachine(string stateMachineName) { return default(StateMachine); } - public Transition AddTransition(State src, State dst) { return default(Transition); } - public Transition AddAnyStateTransition(State dst) { return default(Transition); } - public Vector3 GetStateMachinePosition(int i) { return default(Vector3); } - public Transition[] GetTransitionsFromState(State srcState) { return null; } - } - - [System.Obsolete("State is obsolete. Use UnityEditor.Animations.AnimatorState instead (UnityUpgradable) -> UnityEditor.Animations.AnimatorState", true)] - [NativeClass(null)] - public partial class State : Object - { - /* - ----------------------------------------------------------------------------------------------------------------- - The following members have been moved to base classes in the target class (which by itself is a breaking change - but since those types were *internal* it does not worth the work to fix updater/validation/configure more updates) - ----------------------------------------------------------------------------------------------------------------- - public StateMachine stateMachine { get { return default(StateMachine); } } - public Vector3 position { get { return default(Vector3); } set {} } - */ - - public string uniqueName { get { return string.Empty; } } - public int uniqueNameHash { get { return -1; } } - public float speed { get { return -1.0f; } set {} } - public bool mirror { get { return false; } set {} } - public bool iKOnFeet { get { return false; } set {} } - public string tag { get { return string.Empty; } set {} } - public Motion GetMotion() { return default(Motion); } - public Motion GetMotion(AnimatorControllerLayer layer) { return default(Motion); } - public BlendTree CreateBlendTree() { return default(BlendTree); } - public BlendTree CreateBlendTree(AnimatorControllerLayer layer) { return default(BlendTree); } - } - - // removed this until scripting team can find proper solution to having API moved from one namespace to another - [System.Obsolete("AnimatorController is obsolete. Use UnityEditor.Animations.AnimatorController instead (UnityUpgradable) -> UnityEditor.Animations.AnimatorController", true)] - [NativeClass(null)] - public class AnimatorController : RuntimeAnimatorController - { - } - - [System.Obsolete("BlendTree is obsolete. Use UnityEditor.Animations.BlendTree instead (UnityUpgradable) -> UnityEditor.Animations.BlendTree", true)] - [NativeClass(null)] - public partial class BlendTree : Motion - { - } - - [System.Obsolete("AnimatorControllerLayer is obsolete. Use UnityEditor.Animations.AnimatorControllerLayer instead (UnityUpgradable) -> UnityEditor.Animations.AnimatorControllerLayer", true)] - public partial class AnimatorControllerLayer - { - } - - [System.Obsolete("AnimatorControllerParameter is obsolete. Use UnityEngine.AnimatorControllerParameter instead (UnityUpgradable) -> [UnityEngine] UnityEngine.AnimatorControllerParameter", true)] - public partial class AnimatorControllerParameter - { - } - - [System.Obsolete("AnimatorControllerParameterType is obsolete. Use UnityEngine.AnimatorControllerParameterType instead (UnityUpgradable) -> [UnityEngine] UnityEngine.AnimatorControllerParameterType", true)] - public enum AnimatorControllerParameterType - { - // members need to be declared only to avoid resolution failures. They cannot (and are not) used at runtime - Float = -1, - Int = -1, - Bool = -1, - Trigger = -1 - } - - [System.Obsolete("AnimatorLayerBlendingMode is obsolete. Use UnityEditor.Animations.AnimatorLayerBlendingMode instead (UnityUpgradable) -> UnityEditor.Animations.AnimatorLayerBlendingMode", true)] - public enum AnimatorLayerBlendingMode - { - Override = -1, - Additive = -1 - } -} diff --git a/Runtime/Animation/Managed/Animator.deprecated.cs b/Runtime/Animation/Managed/Animator.deprecated.cs deleted file mode 100644 index 28cfdc0984..0000000000 --- a/Runtime/Animation/Managed/Animator.deprecated.cs +++ /dev/null @@ -1,31 +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 UnityEngine -{ - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Use AnimatorClipInfo instead (UnityUpgradable) -> AnimatorClipInfo", true)] - public struct AnimationInfo - { - public AnimationClip clip { get { return default(AnimationClip); } } - public float weight { get { return 0.0f; } } - } - - partial class Animator - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("GetCurrentAnimationClipState is obsolete. Use GetCurrentAnimatorClipInfo instead (UnityUpgradable) -> GetCurrentAnimatorClipInfo(*)", true)] - public AnimationInfo[] GetCurrentAnimationClipState(int layerIndex) { return null; } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("GetNextAnimationClipState is obsolete. Use GetNextAnimatorClipInfo instead (UnityUpgradable) -> GetNextAnimatorClipInfo(*)", true)] - public AnimationInfo[] GetNextAnimationClipState(int layerIndex) { return null; } - - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Stop is obsolete. Use Animator.enabled = false instead", true)] - public void Stop() {} - } -} diff --git a/Runtime/Animation/Managed/StateMachineBehaviour.cs b/Runtime/Animation/Managed/StateMachineBehaviour.cs deleted file mode 100644 index 065760eef5..0000000000 --- a/Runtime/Animation/Managed/StateMachineBehaviour.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.Scripting; - -namespace UnityEngine -{ - [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] - [RequiredByNativeCode] - public sealed partial class SharedBetweenAnimatorsAttribute : Attribute - { - } - - [RequiredByNativeCode] - public abstract class StateMachineBehaviour : ScriptableObject - { - // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state - virtual public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) - { - } - - // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks - virtual public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) - { - } - - // OnStateExit is called when a transition ends and the state machine finishes evaluating this state - virtual public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) - { - } - - // OnStateMove is called right after Animator.OnAnimatorMove(). Code that processes and affects root motion should be implemented here - virtual public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) - { - } - - // OnStateIK is called right after Animator.OnAnimatorIK(). Code that sets up animation IK (inverse kinematics) should be implemented here. - virtual public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) - { - } - - // OnStateMachineEnter is called when entering a statemachine via its Entry Node - virtual public void OnStateMachineEnter(Animator animator, int stateMachinePathHash) - { - } - - // OnStateMachineExit is called when exiting a statemachine via its Exit Node - virtual public void OnStateMachineExit(Animator animator, int stateMachinePathHash) - { - } - - // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state - virtual public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - - // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks - virtual public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - - // OnStateExit is called when a transition ends and the state machine finishes evaluating this state - virtual public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - - // OnStateMove is called right after Animator.OnAnimatorMove(). Code that processes and affects root motion should be implemented here - virtual public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - - // OnStateIK is called right after Animator.OnAnimatorIK(). Code that sets up animation IK (inverse kinematics) should be implemented here. - virtual public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - - // OnStateMachineEnter is called when entering a statemachine via its Entry Node - virtual public void OnStateMachineEnter(Animator animator, int stateMachinePathHash, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - - // OnStateMachineExit is called when exiting a statemachine via its Exit Node - virtual public void OnStateMachineExit(Animator animator, int stateMachinePathHash, UnityEngine.Animations.AnimatorControllerPlayable controller) - { - } - } -} diff --git a/Runtime/Animation/ScriptBindings/AnimatorControllerParameter.bindings.cs b/Runtime/Animation/ScriptBindings/AnimatorControllerParameter.bindings.cs deleted file mode 100644 index 77fbca4d3c..0000000000 --- a/Runtime/Animation/ScriptBindings/AnimatorControllerParameter.bindings.cs +++ /dev/null @@ -1,55 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Animation/ScriptBindings/AnimatorControllerParameter.bindings.h")] - [NativeHeader("Runtime/Animation/AnimatorControllerParameter.h")] - [NativeAsStruct] - [StructLayout(LayoutKind.Sequential)] - [UsedByNativeCode] - [NativeType(CodegenOptions.Custom, "MonoAnimatorControllerParameter")] - public class AnimatorControllerParameter - { - public string name - { - get { return m_Name; } - set { m_Name = value; } - } - - public int nameHash - { - get { return Animator.StringToHash(m_Name); } - } - - public AnimatorControllerParameterType type { get { return m_Type; } set { m_Type = value; } } - public float defaultFloat { get { return m_DefaultFloat; } set { m_DefaultFloat = value; } } - public int defaultInt { get { return m_DefaultInt; } set { m_DefaultInt = value; } } - public bool defaultBool { get { return m_DefaultBool; } set { m_DefaultBool = value; } } - - internal string m_Name = ""; - internal AnimatorControllerParameterType m_Type; - internal float m_DefaultFloat; - internal int m_DefaultInt; - internal bool m_DefaultBool; - - public override bool Equals(object o) - { - AnimatorControllerParameter other = o as AnimatorControllerParameter; - return other != null && m_Name == other.m_Name && m_Type == other.m_Type && m_DefaultFloat == other.m_DefaultFloat && m_DefaultInt == other.m_DefaultInt && m_DefaultBool == other.m_DefaultBool; - } - - public override int GetHashCode() - { - return name.GetHashCode(); - } - } -} diff --git a/Runtime/Animation/ScriptBindings/AnimatorOverrideController.bindings.cs b/Runtime/Animation/ScriptBindings/AnimatorOverrideController.bindings.cs deleted file mode 100644 index 8e045d9405..0000000000 --- a/Runtime/Animation/ScriptBindings/AnimatorOverrideController.bindings.cs +++ /dev/null @@ -1,157 +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.Bindings; -using UnityEngine.Scripting; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEngine -{ - [Obsolete("This class is not used anymore. See AnimatorOverrideController.GetOverrides() and AnimatorOverrideController.ApplyOverrides()")] - [Serializable] - [StructLayout(LayoutKind.Sequential)] - public class AnimationClipPair - { - public AnimationClip originalClip; - public AnimationClip overrideClip; - } - - [NativeHeader("Runtime/Animation/AnimatorOverrideController.h")] - [NativeHeader("Runtime/Animation/ScriptBindings/Animation.bindings.h")] - [UsedByNativeCode] - public class AnimatorOverrideController : RuntimeAnimatorController - { - public AnimatorOverrideController() - { - Internal_Create(this, null); - OnOverrideControllerDirty = null; - } - - public AnimatorOverrideController(RuntimeAnimatorController controller) - { - Internal_Create(this, controller); - OnOverrideControllerDirty = null; - } - - [FreeFunction("AnimationBindings::CreateAnimatorOverrideController")] - extern private static void Internal_Create([Writable] AnimatorOverrideController self, RuntimeAnimatorController controller); - - // The runtime representation of AnimatorController that controls the Animator - extern public RuntimeAnimatorController runtimeAnimatorController - { - [NativeMethod("GetAnimatorController")] - get; - [NativeMethod("SetAnimatorController")] - set; - } - - // Returns the animation clip named /name/. - public AnimationClip this[string name] - { - get { return Internal_GetClipByName(name, true); } - set { Internal_SetClipByName(name, value); } - } - - [NativeMethod("GetClip")] - extern private AnimationClip Internal_GetClipByName(string name, bool returnEffectiveClip); - - [NativeMethod("SetClip")] - extern private void Internal_SetClipByName(string name, AnimationClip clip); - - // Returns the animation clip named /name/. - public AnimationClip this[AnimationClip clip] - { - get { return GetClip(clip, true); } - set { SetClip(clip, value, true); } - } - - extern private AnimationClip GetClip(AnimationClip originalClip, bool returnEffectiveClip); - - extern private void SetClip(AnimationClip originalClip, AnimationClip overrideClip, bool notify); - - extern private void SendNotification(); - - extern private AnimationClip GetOriginalClip(int index); - extern private AnimationClip GetOverrideClip(AnimationClip originalClip); - - extern public int overridesCount - { - [NativeMethod("GetOriginalClipsCount")] - get; - } - - public void GetOverrides(List> overrides) - { - if (overrides == null) - throw new System.ArgumentNullException("overrides"); - - int count = overridesCount; - if (overrides.Capacity < count) - overrides.Capacity = count; - - overrides.Clear(); - for (int i = 0; i < count; ++i) - { - AnimationClip originalClip = GetOriginalClip(i); - overrides.Add(new KeyValuePair(originalClip, GetOverrideClip(originalClip))); - } - } - - public void ApplyOverrides(IList> overrides) - { - if (overrides == null) - throw new System.ArgumentNullException("overrides"); - - for (int i = 0; i < overrides.Count; i++) - SetClip(overrides[i].Key, overrides[i].Value, false); - - SendNotification(); - } - - [Obsolete("AnimatorOverrideController.clips property is deprecated. Use AnimatorOverrideController.GetOverrides and AnimatorOverrideController.ApplyOverrides instead.")] - public AnimationClipPair[] clips - { - get - { - int count = overridesCount; - - AnimationClipPair[] clipPair = new AnimationClipPair[count]; - for (int i = 0; i < count; i++) - { - clipPair[i] = new AnimationClipPair(); - clipPair[i].originalClip = GetOriginalClip(i); - clipPair[i].overrideClip = GetOverrideClip(clipPair[i].originalClip); - } - - return clipPair; - } - set - { - for (int i = 0; i < value.Length; i++) - SetClip(value[i].originalClip, value[i].overrideClip, false); - - SendNotification(); - } - } - - [NativeConditional("UNITY_EDITOR")] - extern internal void PerformOverrideClipListCleanup(); - - internal delegate void OnOverrideControllerDirtyCallback(); - - internal OnOverrideControllerDirtyCallback OnOverrideControllerDirty; - - [NativeConditional("UNITY_EDITOR")] - [RequiredByNativeCode] - internal static void OnInvalidateOverrideController(AnimatorOverrideController controller) - { - if (controller.OnOverrideControllerDirty != null) - controller.OnOverrideControllerDirty(); - } - } -} diff --git a/Runtime/Animation/ScriptBindings/AnimatorUtility.bindings.cs b/Runtime/Animation/ScriptBindings/AnimatorUtility.bindings.cs deleted file mode 100644 index eb5051970a..0000000000 --- a/Runtime/Animation/ScriptBindings/AnimatorUtility.bindings.cs +++ /dev/null @@ -1,20 +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.Bindings; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Animation/OptimizeTransformHierarchy.h")] - public class AnimatorUtility - { - [FreeFunction] - extern public static void OptimizeTransformHierarchy(GameObject go, string[] exposedTransforms); - - [FreeFunction] - extern public static void DeoptimizeTransformHierarchy(GameObject go); - } -} diff --git a/Runtime/Animation/ScriptBindings/AvatarMask.bindings.cs b/Runtime/Animation/ScriptBindings/AvatarMask.bindings.cs deleted file mode 100644 index b4065022b8..0000000000 --- a/Runtime/Animation/ScriptBindings/AvatarMask.bindings.cs +++ /dev/null @@ -1,92 +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.Bindings; -using UnityEngine.Scripting; -using UnityEngine.Playables; -using UnityEngine.Scripting.APIUpdating; -using UnityEngine.Internal; - -namespace UnityEngine -{ - [MovedFrom("UnityEditor.Animations", true)] - public enum AvatarMaskBodyPart - { - Root = 0, - Body = 1, - Head = 2, - LeftLeg = 3, - RightLeg = 4, - LeftArm = 5, - RightArm = 6, - LeftFingers = 7, - RightFingers = 8, - LeftFootIK = 9, - RightFootIK = 10, - LeftHandIK = 11, - RightHandIK = 12, - LastBodyPart = 13 - } - - [MovedFrom("UnityEditor.Animations", true)] - [NativeHeader("Runtime/Animation/AvatarMask.h")] - [NativeHeader("Runtime/Animation/ScriptBindings/Animation.bindings.h")] - [UsedByNativeCode] - public sealed partial class AvatarMask : Object - { - public AvatarMask() - { - Internal_Create(this); - } - - [FreeFunction("AnimationBindings::CreateAvatarMask")] - extern private static void Internal_Create([Writable] AvatarMask self); - - [Obsolete("AvatarMask.humanoidBodyPartCount is deprecated, use AvatarMaskBodyPart.LastBodyPart instead.")] - public int humanoidBodyPartCount - { - get { return (int)AvatarMaskBodyPart.LastBodyPart; } - } - - [NativeMethod("GetBodyPart")] - extern public bool GetHumanoidBodyPartActive(AvatarMaskBodyPart index); - - [NativeMethod("SetBodyPart")] - extern public void SetHumanoidBodyPartActive(AvatarMaskBodyPart index, bool value); - - extern public int transformCount { get; set; } - - public void AddTransformPath(Transform transform) { AddTransformPath(transform, true); } - extern public void AddTransformPath([NotNull] Transform transform, [DefaultValue("true")] bool recursive); - - public void RemoveTransformPath(Transform transform) { RemoveTransformPath(transform, true); } - extern public void RemoveTransformPath([NotNull] Transform transform, [DefaultValue("true")] bool recursive); - - extern public string GetTransformPath(int index); - extern public void SetTransformPath(int index, string path); - - extern private float GetTransformWeight(int index); - extern private void SetTransformWeight(int index, float weight); - - public bool GetTransformActive(int index) { return GetTransformWeight(index) > 0.5F; } - public void SetTransformActive(int index, bool value) { SetTransformWeight(index, value ? 1.0F : 0.0F); } - - extern internal bool hasFeetIK { get; } - - internal void Copy(AvatarMask other) - { - for (AvatarMaskBodyPart i = 0; i < AvatarMaskBodyPart.LastBodyPart; i++) - SetHumanoidBodyPartActive(i, other.GetHumanoidBodyPartActive(i)); - - transformCount = other.transformCount; - - for (int i = 0; i < other.transformCount; i++) - { - SetTransformPath(i, other.GetTransformPath(i)); - SetTransformActive(i, other.GetTransformActive(i)); - } - } - } -} diff --git a/Runtime/Animation/ScriptBindings/HumanPoseHandler.bindings.cs b/Runtime/Animation/ScriptBindings/HumanPoseHandler.bindings.cs deleted file mode 100644 index 8c735f6d71..0000000000 --- a/Runtime/Animation/ScriptBindings/HumanPoseHandler.bindings.cs +++ /dev/null @@ -1,105 +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.Bindings; -using UnityEngine.Internal; -using UnityEngine.Scripting; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -namespace UnityEngine -{ - public struct HumanPose - { - public Vector3 bodyPosition; - public Quaternion bodyRotation; - public float[] muscles; - - internal void Init() - { - if (muscles != null) - { - if (muscles.Length != HumanTrait.MuscleCount) - { - throw new InvalidOperationException("Bad array size for HumanPose.muscles. Size must equal HumanTrait.MuscleCount"); - } - } - - if (muscles == null) - { - muscles = new float[HumanTrait.MuscleCount]; - - if (bodyRotation.x == 0 && bodyRotation.y == 0 && bodyRotation.z == 0 && bodyRotation.w == 0) - { - bodyRotation.w = 1; - } - } - } - } - - [NativeHeader("Runtime/Animation/HumanPoseHandler.h")] - [NativeHeader("Runtime/Animation/ScriptBindings/Animation.bindings.h")] - public class HumanPoseHandler : IDisposable - { - internal IntPtr m_Ptr; - - [FreeFunction("AnimationBindings::CreateHumanPoseHandler")] - extern private static IntPtr Internal_Create(Avatar avatar, Transform root); - - [FreeFunction("AnimationBindings::DestroyHumanPoseHandler")] - extern private static void Internal_Destroy(IntPtr ptr); - - extern private void GetHumanPose(out Vector3 bodyPosition, out Quaternion bodyRotation, [Out] float[] muscles); - extern private void SetHumanPose(ref Vector3 bodyPosition, ref Quaternion bodyRotation, float[] muscles); - - public void Dispose() - { - if (m_Ptr != IntPtr.Zero) - { - Internal_Destroy(m_Ptr); - m_Ptr = IntPtr.Zero; - } - - GC.SuppressFinalize(this); - } - - public HumanPoseHandler(Avatar avatar, Transform root) - { - m_Ptr = IntPtr.Zero; - - if (root == null) - throw new ArgumentNullException("HumanPoseHandler root Transform is null"); - - if (avatar == null) - throw new ArgumentNullException("HumanPoseHandler avatar is null"); - - if (!avatar.isValid) - throw new ArgumentException("HumanPoseHandler avatar is invalid"); - - if (!avatar.isHuman) - throw new ArgumentException("HumanPoseHandler avatar is not human"); - - m_Ptr = Internal_Create(avatar, root); - } - - public void GetHumanPose(ref HumanPose humanPose) - { - if (m_Ptr == IntPtr.Zero) - throw new NullReferenceException("HumanPoseHandler is not initialized properly"); - - humanPose.Init(); - GetHumanPose(out humanPose.bodyPosition, out humanPose.bodyRotation, humanPose.muscles); - } - - public void SetHumanPose(ref HumanPose humanPose) - { - if (m_Ptr == IntPtr.Zero) - throw new NullReferenceException("HumanPoseHandler is not initialized properly"); - - humanPose.Init(); - SetHumanPose(ref humanPose.bodyPosition, ref humanPose.bodyRotation, humanPose.muscles); - } - } -} diff --git a/Runtime/Animation/ScriptBindings/RuntimeAnimatorController.bindings.cs b/Runtime/Animation/ScriptBindings/RuntimeAnimatorController.bindings.cs deleted file mode 100644 index 329a158447..0000000000 --- a/Runtime/Animation/ScriptBindings/RuntimeAnimatorController.bindings.cs +++ /dev/null @@ -1,20 +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.Bindings; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Animation/RuntimeAnimatorController.h")] - [UsedByNativeCode] - [ExcludeFromObjectFactory] - public partial class RuntimeAnimatorController : Object - { - protected RuntimeAnimatorController() {} - - extern public AnimationClip[] animationClips { get; } - } -} diff --git a/Runtime/Cloth/Cloth.bindings.cs b/Runtime/Cloth/Cloth.bindings.cs deleted file mode 100644 index c7dd2130b9..0000000000 --- a/Runtime/Cloth/Cloth.bindings.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.Bindings; -namespace UnityEngine -{ - [NativeHeader("Runtime/Cloth/Cloth.h")] - public partial class Cloth - { - extern public float sleepThreshold { get; set; } - - // Bending stiffness of the cloth. - extern public float bendingStiffness { get; set; } - - // Stretching stiffness of the cloth. - extern public float stretchingStiffness { get; set; } - - // Damp cloth motion. - extern public float damping { get; set; } - - // A constant, external acceleration applied to the cloth. - extern public Vector3 externalAcceleration { get; set; } - - // A random, external acceleration applied to the cloth. - extern public Vector3 randomAcceleration { get; set; } - - // Should gravity affect the cloth simulation? - extern public bool useGravity { get; set; } - - // Is this cloth enabled? - extern public bool enabled { get; set; } - - // The friction of the cloth when colliding with the character. - extern public float friction { get; set; } - - // How much to increase mass of colliding particles - extern public float collisionMassScale { get; set; } - - // Enable continuous collision to improve collision stability - extern public bool enableContinuousCollision { get; set; } - - // Add 1 virtual particle per triangle to improve collision stability - extern public float useVirtualParticles { get; set; } - - // How much world-space movement of the character will affect cloth vertices. - extern public float worldVelocityScale { get; set; } - - // How much world-space acceleration of the character will affect cloth vertices. - extern public float worldAccelerationScale { get; set; } - - extern public float clothSolverFrequency { get; set; } - - extern public bool useTethers { get; set; } - - extern public float stiffnessFrequency { get; set; } - - extern public float selfCollisionDistance { get; set; } - - extern public float selfCollisionStiffness { get; set; } - } -} diff --git a/Runtime/Cloth/Cloth.cs b/Runtime/Cloth/Cloth.cs deleted file mode 100644 index 1db022e85d..0000000000 --- a/Runtime/Cloth/Cloth.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 System; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - // The ClothSkinningCoefficient struct is used to set up how a [[Cloth]] component is allowed to move with respect to the [[SkinnedMeshRenderer]] it is attached to. - [UsedByNativeCode] - public struct ClothSkinningCoefficient - { - //Distance a vertex is allowed to travel from the skinned mesh vertex position. - public float maxDistance; - - //Definition of a sphere a vertex is not allowed to enter. This allows collision against the animated cloth. - public float collisionSphereDistance; - } - - public partial class Cloth - { - public void GetVirtualParticleIndices(List indices) - { - if (indices == null) - throw new ArgumentNullException("indices"); - - GetVirtualParticleIndicesMono(indices); - } - - public void SetVirtualParticleIndices(List indices) - { - if (indices == null) - throw new ArgumentNullException("indices"); - - SetVirtualParticleIndicesMono(indices); - } - - public void GetVirtualParticleWeights(List weights) - { - if (weights == null) - throw new ArgumentNullException("weights"); - - GetVirtualParticleWeightsMono(weights); - } - - public void SetVirtualParticleWeights(List weights) - { - if (weights == null) - throw new ArgumentNullException("weights"); - - SetVirtualParticleWeightsMono(weights); - } - - public void GetSelfAndInterCollisionIndices(List indices) - { - if (indices == null) - throw new ArgumentNullException("indices"); - - GetSelfAndInterCollisionIndicesMono(indices); - } - - public void SetSelfAndInterCollisionIndices(List indices) - { - if (indices == null) - throw new ArgumentNullException("indices"); - - SetSelfAndInterCollisionIndicesMono(indices); - } - } -} // namespace - diff --git a/Runtime/Export/AnimationCurve.bindings.cs b/Runtime/Export/AnimationCurve.bindings.cs index e8f0051e65..9262cff54b 100644 --- a/Runtime/Export/AnimationCurve.bindings.cs +++ b/Runtime/Export/AnimationCurve.bindings.cs @@ -227,6 +227,12 @@ public static AnimationCurve Constant(float timeStart, float timeEnd, float valu // A straight Line starting at /timeStart/, /valueStart/ and ending at /timeEnd/, /valueEnd/ public static AnimationCurve Linear(float timeStart, float valueStart, float timeEnd, float valueEnd) { + if (timeStart == timeEnd) + { + Keyframe key = new Keyframe(timeStart, valueStart); + return new AnimationCurve(new Keyframe[] {key}); + } + float tangent = (valueEnd - valueStart) / (timeEnd - timeStart); Keyframe[] keys = { new Keyframe(timeStart, valueStart, 0.0F, tangent), new Keyframe(timeEnd, valueEnd, tangent, 0.0F) }; return new AnimationCurve(keys); @@ -235,6 +241,12 @@ public static AnimationCurve Linear(float timeStart, float valueStart, float tim // An ease-in and out curve starting at /timeStart/, /valueStart/ and ending at /timeEnd/, /valueEnd/. public static AnimationCurve EaseInOut(float timeStart, float valueStart, float timeEnd, float valueEnd) { + if (timeStart == timeEnd) + { + Keyframe key = new Keyframe(timeStart, valueStart); + return new AnimationCurve(new Keyframe[] {key}); + } + Keyframe[] keys = { new Keyframe(timeStart, valueStart, 0.0F, 0.0F), new Keyframe(timeEnd, valueEnd, 0.0F, 0.0F) }; return new AnimationCurve(keys); } diff --git a/Runtime/Export/ArrayUtils.cs b/Runtime/Export/ArrayUtils.cs deleted file mode 100644 index 9c51995c1c..0000000000 --- a/Runtime/Export/ArrayUtils.cs +++ /dev/null @@ -1,13 +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; - -namespace UnityEngine -{ - internal static class ArrayUtils - { - } -} diff --git a/Runtime/Export/Assertions/Assert/AssertFloat.cs b/Runtime/Export/Assertions/Assert/AssertFloat.cs deleted file mode 100644 index 8d48f83d65..0000000000 --- a/Runtime/Export/Assertions/Assert/AssertFloat.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 System.Diagnostics; -using UnityEngine; -using UnityEngine.Assertions.Comparers; - -namespace UnityEngine.Assertions -{ - public static partial class Assert - { - [Conditional(UNITY_ASSERTIONS)] - public static void AreApproximatelyEqual(float expected, float actual) - { - AreEqual(expected, actual, null, FloatComparer.s_ComparerWithDefaultTolerance); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreApproximatelyEqual(float expected, float actual, string message) - { - AreEqual(expected, actual, message, FloatComparer.s_ComparerWithDefaultTolerance); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreApproximatelyEqual(float expected, float actual, float tolerance) - { - AreApproximatelyEqual(expected, actual, tolerance, null); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreApproximatelyEqual(float expected, float actual, float tolerance, string message) - { - AreEqual(expected, actual, message, new FloatComparer(tolerance)); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotApproximatelyEqual(float expected, float actual) - { - AreNotEqual(expected, actual, null, FloatComparer.s_ComparerWithDefaultTolerance); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotApproximatelyEqual(float expected, float actual, string message) - { - AreNotEqual(expected, actual, message, FloatComparer.s_ComparerWithDefaultTolerance); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotApproximatelyEqual(float expected, float actual, float tolerance) - { - AreNotApproximatelyEqual(expected, actual, tolerance, null); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotApproximatelyEqual(float expected, float actual, float tolerance, string message) - { - AreNotEqual(expected, actual, message, new FloatComparer(tolerance)); - } - } -} diff --git a/Runtime/Export/Assertions/Assert/AssertGeneric.cs b/Runtime/Export/Assertions/Assert/AssertGeneric.cs deleted file mode 100644 index 0ad58c009a..0000000000 --- a/Runtime/Export/Assertions/Assert/AssertGeneric.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 System; -using System.Collections.Generic; -using System.Diagnostics; -using UnityEngine; - -namespace UnityEngine.Assertions -{ - public static partial class Assert - { - [Conditional(UNITY_ASSERTIONS)] - public static void AreEqual(T expected, T actual) - { - AreEqual(expected, actual, null); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreEqual(T expected, T actual, string message) - { - AreEqual(expected, actual, message, EqualityComparer.Default); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreEqual(T expected, T actual, string message, IEqualityComparer comparer) - { - if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(T))) - { - AreEqual(expected as UnityEngine.Object, actual as UnityEngine.Object, message); - return; - } - if (!comparer.Equals(actual, expected)) - Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, true), message); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreEqual(UnityEngine.Object expected, UnityEngine.Object actual, string message) - { - if (actual != expected) - Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, true), message); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotEqual(T expected, T actual) - { - AreNotEqual(expected, actual, null); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotEqual(T expected, T actual, string message) - { - AreNotEqual(expected, actual, message, EqualityComparer.Default); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotEqual(T expected, T actual, string message, IEqualityComparer comparer) - { - if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(T))) - { - AreNotEqual(expected as UnityEngine.Object, actual as UnityEngine.Object, message); - return; - } - if (comparer.Equals(actual, expected)) - Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, false), message); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void AreNotEqual(UnityEngine.Object expected, UnityEngine.Object actual, string message) - { - if (actual == expected) - Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, false), message); - } - } -} diff --git a/Runtime/Export/Assertions/Assert/AssertNull.cs b/Runtime/Export/Assertions/Assert/AssertNull.cs deleted file mode 100644 index 1388d7ddb4..0000000000 --- a/Runtime/Export/Assertions/Assert/AssertNull.cs +++ /dev/null @@ -1,65 +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.Diagnostics; -using UnityEngine; - -namespace UnityEngine.Assertions -{ - public static partial class Assert - { - [Conditional(UNITY_ASSERTIONS)] - public static void IsNull(T value) where T : class - { - IsNull(value, null); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void IsNull(T value, string message) where T : class - { - if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(T))) - { - IsNull(value as UnityEngine.Object, message); - } - else if (value != null) - { - Fail(AssertionMessageUtil.NullFailureMessage(value, true), message); - } - } - - [Conditional(UNITY_ASSERTIONS)] - public static void IsNull(UnityEngine.Object value, string message) - { - if (value != null) - Fail(AssertionMessageUtil.NullFailureMessage(value, true), message); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void IsNotNull(T value) where T : class - { - IsNotNull(value, null); - } - - [Conditional(UNITY_ASSERTIONS)] - public static void IsNotNull(T value, string message) where T : class - { - if (typeof(UnityEngine.Object).IsAssignableFrom(typeof(T))) - { - IsNotNull(value as UnityEngine.Object, message); - } - else if (value == null) - { - Fail(AssertionMessageUtil.NullFailureMessage(value, false), message); - } - } - - [Conditional(UNITY_ASSERTIONS)] - public static void IsNotNull(UnityEngine.Object value, string message) - { - if (value == null) - Fail(AssertionMessageUtil.NullFailureMessage(value, false), message); - } - } -} diff --git a/Runtime/Export/Assertions/Assert/AssertionException.cs b/Runtime/Export/Assertions/Assert/AssertionException.cs deleted file mode 100644 index bf0019949d..0000000000 --- a/Runtime/Export/Assertions/Assert/AssertionException.cs +++ /dev/null @@ -1,31 +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 UnityEngine.Assertions -{ - public class AssertionException : Exception - { - string m_UserMessage; - - public AssertionException(string message, string userMessage) - : base(message) - { - m_UserMessage = userMessage; - } - - public override string Message - { - get - { - var message = base.Message; - if (m_UserMessage != null) - message += '\n' + m_UserMessage; - return message; - } - } - } -} diff --git a/Runtime/Export/Assertions/Assert/AssertionMessageUtil.cs b/Runtime/Export/Assertions/Assert/AssertionMessageUtil.cs deleted file mode 100644 index c1a621d643..0000000000 --- a/Runtime/Export/Assertions/Assert/AssertionMessageUtil.cs +++ /dev/null @@ -1,44 +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 System.Text; - -namespace UnityEngine.Assertions -{ - internal class AssertionMessageUtil - { - const string k_Expected = "Expected:"; - const string k_AssertionFailed = "Assertion failure."; - - public static string GetMessage(string failureMessage) - { - return UnityString.Format("{0} {1}", k_AssertionFailed, failureMessage); - } - - public static string GetMessage(string failureMessage, string expected) - { - return GetMessage(UnityString.Format("{0}{1}{2} {3}", failureMessage, Environment.NewLine, k_Expected, expected)); - } - - public static string GetEqualityMessage(object actual, object expected, bool expectEqual) - { - return GetMessage(UnityString.Format("Values are {0}equal.", expectEqual ? "not " : ""), - UnityString.Format("{0} {2} {1}", actual, expected, expectEqual ? "==" : "!=")); - } - - public static string NullFailureMessage(object value, bool expectNull) - { - return GetMessage(UnityString.Format("Value was {0}Null", expectNull ? "not " : ""), - UnityString.Format("Value was {0}Null", expectNull ? "" : "not ")); - } - - public static string BooleanFailureMessage(bool expected) - { - return GetMessage("Value was " + !expected, expected.ToString()); - } - } -} diff --git a/Runtime/Export/Assertions/Assert/Comparers/FloatComparer.cs b/Runtime/Export/Assertions/Assert/Comparers/FloatComparer.cs deleted file mode 100644 index fda7698171..0000000000 --- a/Runtime/Export/Assertions/Assert/Comparers/FloatComparer.cs +++ /dev/null @@ -1,66 +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; - -namespace UnityEngine.Assertions.Comparers -{ - public class FloatComparer : IEqualityComparer - { - readonly float m_Error; - readonly bool m_Relative; - public static readonly FloatComparer s_ComparerWithDefaultTolerance = new FloatComparer(kEpsilon); - - public const float kEpsilon = 0.00001f; - - public FloatComparer() - : this(kEpsilon, false) - { - } - - public FloatComparer(bool relative) - : this(kEpsilon, relative) - { - } - - public FloatComparer(float error) - : this(error, false) - { - } - - public FloatComparer(float error, bool relative) - { - m_Error = error; - m_Relative = relative; - } - - public bool Equals(float a, float b) - { - return m_Relative ? AreEqualRelative(a, b, m_Error) : AreEqual(a, b, m_Error); - } - - public int GetHashCode(float obj) - { - return base.GetHashCode(); - } - - public static bool AreEqual(Single expected, Single actual, Single error) - { - return Math.Abs(actual - expected) <= error; - } - - public static bool AreEqualRelative(Single expected, Single actual, Single error) - { - if (expected == actual) return true; - - var absExpected = Math.Abs(expected); - var absActual = Math.Abs(actual); - var relativeError = Math.Abs((actual - expected) / (absExpected > absActual ? absExpected : absActual)); - - return relativeError <= error; - } - } -} diff --git a/Runtime/Export/Assertions/Must/MustBool.cs b/Runtime/Export/Assertions/Must/MustBool.cs deleted file mode 100644 index fcb9a3b353..0000000000 --- a/Runtime/Export/Assertions/Must/MustBool.cs +++ /dev/null @@ -1,41 +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.Diagnostics; -using UnityEngine; - -namespace UnityEngine.Assertions.Must -{ - public static partial class MustExtensions - { - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeTrue(this bool value) - { - Assert.IsTrue(value); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeTrue(this bool value, string message) - { - Assert.IsTrue(value, message); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeFalse(this bool value) - { - Assert.IsFalse(value); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeFalse(this bool value, string message) - { - Assert.IsFalse(value, message); - } - } -} diff --git a/Runtime/Export/Assertions/Must/MustFloat.cs b/Runtime/Export/Assertions/Must/MustFloat.cs deleted file mode 100644 index ea0f7d4aef..0000000000 --- a/Runtime/Export/Assertions/Must/MustFloat.cs +++ /dev/null @@ -1,69 +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.Diagnostics; -using UnityEngine; - -namespace UnityEngine.Assertions.Must -{ - public static partial class MustExtensions - { - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeApproximatelyEqual(this float actual, float expected) - { - Assert.AreApproximatelyEqual(actual, expected); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeApproximatelyEqual(this float actual, float expected, string message) - { - Assert.AreApproximatelyEqual(actual, expected, message); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeApproximatelyEqual(this float actual, float expected, float tolerance) - { - Assert.AreApproximatelyEqual(actual, expected, tolerance); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeApproximatelyEqual(this float actual, float expected, float tolerance, string message) - { - Assert.AreApproximatelyEqual(expected, actual, tolerance, message); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeApproximatelyEqual(this float actual, float expected) - { - Assert.AreNotApproximatelyEqual(expected, actual); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeApproximatelyEqual(this float actual, float expected, string message) - { - Assert.AreNotApproximatelyEqual(expected, actual, message); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeApproximatelyEqual(this float actual, float expected, float tolerance) - { - Assert.AreNotApproximatelyEqual(expected, actual, tolerance); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeApproximatelyEqual(this float actual, float expected, float tolerance, string message) - { - Assert.AreNotApproximatelyEqual(expected, actual, tolerance, message); - } - } -} diff --git a/Runtime/Export/Assertions/Must/MustGeneric.cs b/Runtime/Export/Assertions/Must/MustGeneric.cs deleted file mode 100644 index c56528b3f7..0000000000 --- a/Runtime/Export/Assertions/Must/MustGeneric.cs +++ /dev/null @@ -1,43 +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.Diagnostics; -using UnityEngine; - -namespace UnityEngine.Assertions.Must -{ - [DebuggerStepThrough] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static partial class MustExtensions - { - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeEqual(this T actual, T expected) - { - Assert.AreEqual(actual, expected); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeEqual(this T actual, T expected, string message) - { - Assert.AreEqual(expected, actual, message); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeEqual(this T actual, T expected) - { - Assert.AreNotEqual(actual, expected); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeEqual(this T actual, T expected, string message) - { - Assert.AreNotEqual(expected, actual, message); - } - } -} diff --git a/Runtime/Export/Assertions/Must/MustNull.cs b/Runtime/Export/Assertions/Must/MustNull.cs deleted file mode 100644 index 7ecab90969..0000000000 --- a/Runtime/Export/Assertions/Must/MustNull.cs +++ /dev/null @@ -1,41 +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.Diagnostics; -using UnityEngine; - -namespace UnityEngine.Assertions.Must -{ - public static partial class MustExtensions - { - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeNull(this T expected) where T : class - { - Assert.IsNull(expected); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustBeNull(this T expected, string message) where T : class - { - Assert.IsNull(expected, message); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeNull(this T expected) where T : class - { - Assert.IsNotNull(expected); - } - - [Conditional(Assert.UNITY_ASSERTIONS)] - [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] - public static void MustNotBeNull(this T expected, string message) where T : class - { - Assert.IsNotNull(expected, message); - } - } -} diff --git a/Runtime/Export/AudioType.cs b/Runtime/Export/AudioType.cs deleted file mode 100644 index 73d9c87dcc..0000000000 --- a/Runtime/Export/AudioType.cs +++ /dev/null @@ -1,57 +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 UnityEngine -{ - // Not used by new AudioClip, but still reguired for WWW.getAudioClip - // Type of the imported(native) data - public enum AudioType - { - // 3rd party / unknown plugin format. - UNKNOWN = 0, - //acc - not supported - ACC = 1, /* [Unity] Not supported/used. But kept here to keep the order of the enum in sync. */ - //aiff - AIFF = 2, - // ASF = 3, /* Microsoft Advanced Systems Format (ie WMA/ASF/WMV). */ - // AT3 = 4, /* Sony ATRAC 3 format */ - // CDDA = 5, /* Digital CD audio. */ - // DLS = 6, /* Sound font / downloadable sound bank. */ - // FLAC = 7, /* FLAC lossless codec. */ - // FSB = 8, /* FMOD Sample Bank. */ - //game cube ADPCM - // GCADPCM = 9, - //impulse tracker - IT = 10, - // MIDI = 11, /* MIDI. */ - //Protracker / Fasttracker MOD. - MOD = 12, - //MP2/MP3 MPEG. - MPEG = 13, - //ogg vorbis - OGGVORBIS = 14, - // PLAYLIST = 15, /* Information only from ASX/PLS/M3U/WAX playlists */ - // RAW = 16, /* Raw PCM data. */ - // ScreamTracker 3. - S3M = 17, - // SF2 = 18, /* Sound font 2 format. */ - // USER = 19, /* User created sound. */ - //Microsoft WAV. - WAV = 20, - // FastTracker 2 XM. - XM = 21, - // XboxOne XMA(2) - XMA = 22, - VAG = 23, /* PlayStation 2 / PlayStation Portable adpcm VAG format. */ - //iPhone hardware decoder, supports AAC, ALAC and MP3. Extracodecdata is a pointer to an FMOD_AUDIOQUEUE_EXTRACODECDATA structure. - AUDIOQUEUE = 24, - // XWMA = 25, /* Xbox360 XWMA */ - // BCWAV = 26, /* 3DS BCWAV container format for DSP ADPCM and PCM */ - // AT9 = 27, /* NGP ATRAC 9 format */ - - // XBONE TODO: these are supported on xbone in hardware, do we care? XMA and XWMA are above and supported in hardware by xbone - //PCM = 28, - //ADPCM = 29, - } -} diff --git a/Runtime/Export/BeforeRenderHelper.cs b/Runtime/Export/BeforeRenderHelper.cs deleted file mode 100644 index 53ca5f75ed..0000000000 --- a/Runtime/Export/BeforeRenderHelper.cs +++ /dev/null @@ -1,102 +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.Collections.Generic; -using System.Reflection; -using System; -using UnityEngine.Events; - -namespace UnityEngine -{ - [AttributeUsage(System.AttributeTargets.Method)] - public class BeforeRenderOrderAttribute : Attribute - { - public int order { get; private set; } - public BeforeRenderOrderAttribute(int order) - { - this.order = order; - } - } - static class BeforeRenderHelper - { - struct OrderBlock - { - internal int order; - internal UnityAction callback; - } - - static List s_OrderBlocks = new List(); - - static int GetUpdateOrder(UnityAction callback) - { - object[] attributes = callback.Method.GetCustomAttributes(typeof(BeforeRenderOrderAttribute), true); - BeforeRenderOrderAttribute updateOrder = (attributes != null && attributes.Length > 0) ? attributes[0] as BeforeRenderOrderAttribute : null; - - return updateOrder != null ? updateOrder.order : 0; - } - - public static void RegisterCallback(UnityAction callback) - { - int order = GetUpdateOrder(callback); - - lock (s_OrderBlocks) - { - int i = 0; - for (; i < s_OrderBlocks.Count && (s_OrderBlocks[i].order <= order); i++) - { - if (s_OrderBlocks[i].order == order) - { - OrderBlock element = s_OrderBlocks[i]; - element.callback += callback; - s_OrderBlocks[i] = element; - return; - } - } - - var newElement = new OrderBlock(); - newElement.order = order; - newElement.callback += callback; - - s_OrderBlocks.Insert(i, newElement); - } - } - - public static void UnregisterCallback(UnityAction callback) - { - int order = GetUpdateOrder(callback); - - lock (s_OrderBlocks) - { - for (int i = 0; i < s_OrderBlocks.Count && (s_OrderBlocks[i].order <= order); i++) - { - if (s_OrderBlocks[i].order == order) - { - OrderBlock element = s_OrderBlocks[i]; - element.callback -= callback; - s_OrderBlocks[i] = element; - - if (element.callback == null) - { - s_OrderBlocks.RemoveAt(i); - } - return; - } - } - } - } - - public static void Invoke() - { - lock (s_OrderBlocks) - { - for (int i = 0; i < s_OrderBlocks.Count; i++) - { - UnityAction callback = s_OrderBlocks[i].callback; - if (callback != null) - callback(); - } - } - } - } -} diff --git a/Runtime/Export/BootConfig.bindings.cs b/Runtime/Export/BootConfig.bindings.cs deleted file mode 100644 index c08f3df781..0000000000 --- a/Runtime/Export/BootConfig.bindings.cs +++ /dev/null @@ -1,51 +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.Runtime.InteropServices; -using UnityEngine.Bindings; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Export/BootConfig.bindings.h")] - internal class BootConfigData - { - #pragma warning disable 0414 - private IntPtr m_Ptr; - #pragma warning restore 0414 - - public void AddKey(string key) - { - Append(key, null); - } - - public string Get(string key) - { - return GetValue(key, 0); - } - - public string Get(string key, int index) - { - return GetValue(key, index); - } - - extern public void Append(string key, string value); - extern public void Set(string key, string value); - extern private string GetValue(string key, int index); - - [RequiredByNativeCode] - static BootConfigData WrapBootConfigData(IntPtr nativeHandle) - { - return new BootConfigData(nativeHandle); - } - - private BootConfigData(IntPtr nativeHandle) - { - if (nativeHandle == IntPtr.Zero) - throw new ArgumentException("native handle can not be null"); - m_Ptr = nativeHandle; - } - } -} diff --git a/Runtime/Export/Caching.deprecated.cs b/Runtime/Export/Caching.deprecated.cs deleted file mode 100644 index 3c1390debd..0000000000 --- a/Runtime/Export/Caching.deprecated.cs +++ /dev/null @@ -1,18 +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 UnityEngine -{ - - public partial class Caching - { - [System.Obsolete("This function is obsolete. Please use ClearCache. (UnityUpgradable) -> ClearCache()")] - public static bool CleanCache() - { - return ClearCache(); - } - } -} diff --git a/Runtime/Export/Camera.bindings.cs b/Runtime/Export/Camera.bindings.cs index a34e8b2ccf..9620d45454 100644 --- a/Runtime/Export/Camera.bindings.cs +++ b/Runtime/Export/Camera.bindings.cs @@ -232,6 +232,9 @@ public static Camera[] allCameras } public static int GetAllCameras(Camera[] cameras) { + if (cameras == null) + throw new NullReferenceException(); + if (cameras.Length < allCamerasCount) throw new ArgumentException("Passed in array to fill with cameras is to small to hold the number of cameras. Use Camera.allCamerasCount to get the needed size."); return GetAllCamerasImpl(cameras); @@ -274,7 +277,7 @@ public bool RenderToCubemap(RenderTexture cubemap, int faceMask, MonoOrStereosco public void AddCommandBuffer(CameraEvent evt, CommandBuffer buffer) { - if (!Enum.IsDefined(typeof(CameraEvent), evt)) + if (!Rendering.CameraEventUtils.IsValid(evt)) throw new ArgumentException(string.Format(@"Invalid CameraEvent value ""{0}"".", (int)evt), "evt"); if (buffer == null) throw new NullReferenceException("buffer is null"); AddCommandBufferImpl(evt, buffer); @@ -282,7 +285,7 @@ public void AddCommandBuffer(CameraEvent evt, CommandBuffer buffer) public void AddCommandBufferAsync(CameraEvent evt, CommandBuffer buffer, ComputeQueueType queueType) { - if (!Enum.IsDefined(typeof(CameraEvent), evt)) + if (!Rendering.CameraEventUtils.IsValid(evt)) throw new ArgumentException(string.Format(@"Invalid CameraEvent value ""{0}"".", (int)evt), "evt"); if (buffer == null) throw new NullReferenceException("buffer is null"); AddCommandBufferAsyncImpl(evt, buffer, queueType); @@ -290,7 +293,7 @@ public void AddCommandBufferAsync(CameraEvent evt, CommandBuffer buffer, Compute public void RemoveCommandBuffer(CameraEvent evt, CommandBuffer buffer) { - if (!Enum.IsDefined(typeof(CameraEvent), evt)) + if (!Rendering.CameraEventUtils.IsValid(evt)) throw new ArgumentException(string.Format(@"Invalid CameraEvent value ""{0}"".", (int)evt), "evt"); if (buffer == null) throw new NullReferenceException("buffer is null"); RemoveCommandBufferImpl(evt, buffer); diff --git a/Runtime/Export/Camera.deprecated.cs b/Runtime/Export/Camera.deprecated.cs deleted file mode 100644 index 9a96d4589f..0000000000 --- a/Runtime/Export/Camera.deprecated.cs +++ /dev/null @@ -1,86 +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 UnityEngine -{ - partial class Camera - { - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property isOrthoGraphic has been deprecated. Use orthographic (UnityUpgradable) -> orthographic", true)] - public bool isOrthoGraphic { get { return false; } set {} } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.GetScreenWidth has been deprecated. Use Screen.width instead (UnityUpgradable) -> Screen.width", true)] - public float GetScreenWidth() { return 0.0f; } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.GetScreenHeight has been deprecated. Use Screen.height instead (UnityUpgradable) -> Screen.height", true)] - public float GetScreenHeight() { return 0.0f; } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property mainCamera has been deprecated. Use Camera.main instead (UnityUpgradable) -> main", true)] - public static Camera mainCamera { get { return null; } } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.DoClear has been deprecated (UnityUpgradable).", true)] - public void DoClear() {} - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property near has been deprecated. Use Camera.nearClipPlane instead (UnityUpgradable) -> UnityEngine.Camera.nearClipPlane", false)] - public float near { get { return nearClipPlane; } set { nearClipPlane = value; } } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property far has been deprecated. Use Camera.farClipPlane instead (UnityUpgradable) -> UnityEngine.Camera.farClipPlane", false)] - public float far { get { return farClipPlane; } set { farClipPlane = value; } } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property fov has been deprecated. Use Camera.fieldOfView instead (UnityUpgradable) -> UnityEngine.Camera.fieldOfView", false)] - public float fov { get { return fieldOfView; } set { fieldOfView = value; } } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.ResetFieldOfView has been deprecated in Unity 5.6 and will be removed in the future. Please replace it by explicitly setting the camera's FOV to 60 degrees.", false)] - // for some weird reason cpp ResetFieldOfView was doing much less than SetFOV. Now we explicitly call SetFOV(60) - public void ResetFieldOfView() { fieldOfView = 60; } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property hdr has been deprecated. Use Camera.allowHDR instead (UnityUpgradable) -> UnityEngine.Camera.allowHDR", false)] - public bool hdr { get { return allowHDR; } set { allowHDR = value; } } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Property stereoMirrorMode is no longer supported. Please use single pass stereo rendering instead.", true)] - public bool stereoMirrorMode { get { return false; } set {} } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.SetStereoViewMatrices has been deprecated. Use SetStereoViewMatrix(StereoscopicEye eye) instead.", false)] - public void SetStereoViewMatrices(Matrix4x4 leftMatrix, Matrix4x4 rightMatrix) - { - SetStereoViewMatrix(StereoscopicEye.Left, leftMatrix); - SetStereoViewMatrix(StereoscopicEye.Right, rightMatrix); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.SetStereoProjectionMatrices has been deprecated. Use SetStereoProjectionMatrix(StereoscopicEye eye) instead.", false)] - public void SetStereoProjectionMatrices(Matrix4x4 leftMatrix, Matrix4x4 rightMatrix) - { - SetStereoProjectionMatrix(StereoscopicEye.Left, leftMatrix); - SetStereoProjectionMatrix(StereoscopicEye.Right, rightMatrix); - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.GetStereoViewMatrices has been deprecated. Use GetStereoViewMatrix(StereoscopicEye eye) instead.", false)] - public Matrix4x4[] GetStereoViewMatrices() - { - return new Matrix4x4[] { GetStereoViewMatrix(StereoscopicEye.Left), GetStereoViewMatrix(StereoscopicEye.Right) }; - } - - [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] - [Obsolete("Camera.GetStereoProjectionMatrices has been deprecated. Use GetStereoProjectionMatrix(StereoscopicEye eye) instead.", false)] - public Matrix4x4[] GetStereoProjectionMatrices() - { - return new Matrix4x4[] { GetStereoProjectionMatrix(StereoscopicEye.Left), GetStereoProjectionMatrix(StereoscopicEye.Right) }; - } - } -} diff --git a/Runtime/Export/CastHelper.cs b/Runtime/Export/CastHelper.cs deleted file mode 100644 index 1c987fa22c..0000000000 --- a/Runtime/Export/CastHelper.cs +++ /dev/null @@ -1,17 +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.Runtime.InteropServices; - -namespace UnityEngine -{ - //generic casts in our mono carry a uncomfortable performance penalty. in some cases, we are sure the cast will succeed. we use the - //trick with the struct below to get a cast done without any checks in that case, which gets us a performance increase. - internal struct CastHelper - { - public T t; - public System.IntPtr onePointerFurtherThanT; - } -} diff --git a/Runtime/Export/ClassLibraryInitializer.cs b/Runtime/Export/ClassLibraryInitializer.cs deleted file mode 100644 index 93172981b9..0000000000 --- a/Runtime/Export/ClassLibraryInitializer.cs +++ /dev/null @@ -1,17 +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.Scripting; - -namespace UnityEngine -{ - internal static class ClassLibraryInitializer - { - [RequiredByNativeCode] - static void Init() - { - UnityLogWriter.Init(); - } - } -} diff --git a/Runtime/Export/Collections/NativeCollectionEnums.bindings.cs b/Runtime/Export/Collections/NativeCollectionEnums.bindings.cs deleted file mode 100644 index af17182066..0000000000 --- a/Runtime/Export/Collections/NativeCollectionEnums.bindings.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 UnityEngine.Scripting; - -namespace Unity.Collections -{ - [UsedByNativeCode] - public enum Allocator - { - // NOTE: The items must be kept in sync with Runtime/Export/Collections/NativeCollectionAllocator.h - - Invalid = 0, - // NOTE: this is important to let Invalid = 0 so that new NativeArray() will lead to an invalid allocation by default. - - None = 1, - Temp = 2, - TempJob = 3, - Persistent = 4 - } -} diff --git a/Runtime/Export/Coroutine.bindings.cs b/Runtime/Export/Coroutine.bindings.cs deleted file mode 100644 index 0c4c6dee48..0000000000 --- a/Runtime/Export/Coroutine.bindings.cs +++ /dev/null @@ -1,29 +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.Runtime.InteropServices; -using UnityEngine.Scripting; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - // MonoBehaviour.StartCoroutine returns a Coroutine. Instances of this class are only used to reference these coroutines and do not hold any exposed properties or functions. - [NativeHeader("Runtime/Mono/Coroutine.h")] - [StructLayout(LayoutKind.Sequential)] - [RequiredByNativeCode] - public sealed class Coroutine : YieldInstruction - { - internal IntPtr m_Ptr; - Coroutine() {} - - ~Coroutine() - { - ReleaseCoroutine(m_Ptr); - } - - [FreeFunction("Coroutine::CleanupCoroutineGC", true)] - extern static void ReleaseCoroutine(IntPtr ptr); - } -} diff --git a/Runtime/Export/Coroutines.cs b/Runtime/Export/Coroutines.cs deleted file mode 100644 index b1beac6229..0000000000 --- a/Runtime/Export/Coroutines.cs +++ /dev/null @@ -1,48 +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.Reflection; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - [RequiredByNativeCode] - internal class SetupCoroutine - { - [RequiredByNativeCode] - [System.Security.SecuritySafeCritical] - unsafe static public void InvokeMoveNext(IEnumerator enumerator, IntPtr returnValueAddress) - { - if (returnValueAddress == IntPtr.Zero) - throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); - (*(bool*)returnValueAddress) = enumerator.MoveNext(); - } - - [RequiredByNativeCode] - static public object InvokeMember(object behaviour, string name, object variable) - { - // We need these stubs because methods marked with [RequiredByNativeCode] must match between scripting backends - object[] args = null; - if (variable != null) - { - args = new System.Object[1]; - args[0] = variable; - } - return behaviour.GetType().InvokeMember(name, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, behaviour, args, null, null, null); - } - - static public object InvokeStatic(Type klass, string name, object variable) - { - object[] args = null; - if (variable != null) - { - args = new System.Object[1]; - args[0] = variable; - } - return klass.InvokeMember(name, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, null, args, null, null, null); - } - } -} diff --git a/Runtime/Export/CustomYieldInstruction.cs b/Runtime/Export/CustomYieldInstruction.cs deleted file mode 100644 index ee7d8e2ad0..0000000000 --- a/Runtime/Export/CustomYieldInstruction.cs +++ /dev/null @@ -1,26 +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.Collections; - -namespace UnityEngine -{ - public abstract class CustomYieldInstruction : IEnumerator - { - public abstract bool keepWaiting - { - get; - } - - public object Current - { - get - { - return null; - } - } - public bool MoveNext() { return keepWaiting; } - public void Reset() {} - } -} diff --git a/Runtime/Export/Debug.bindings.cs b/Runtime/Export/Debug.bindings.cs deleted file mode 100644 index 5a4cf3a170..0000000000 --- a/Runtime/Export/Debug.bindings.cs +++ /dev/null @@ -1,220 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using UnityEngine.Internal; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Export/Debug.bindings.h")] - internal sealed partial class DebugLogHandler - { - [ThreadAndSerializationSafe] - internal static extern void Internal_Log(LogType level, string msg, Object obj); - [ThreadAndSerializationSafe] - internal static extern void Internal_LogException(Exception exception, Object obj); - } - - [NativeHeader("Runtime/Export/Debug.bindings.h")] - // Class containing methods to ease debugging while developing a game. - public partial class Debug - { - internal static ILogger s_Logger = new Logger(new DebugLogHandler()); - public static ILogger unityLogger - { - get { return s_Logger; } - } - - - [ExcludeFromDocs] - public static void DrawLine(Vector3 start, Vector3 end, Color color , float duration) - { - bool depthTest = true; - DrawLine(start, end, color, duration, depthTest); - } - - [ExcludeFromDocs] - public static void DrawLine(Vector3 start, Vector3 end, Color color) - { - bool depthTest = true; - float duration = 0.0f; - DrawLine(start, end, color, duration, depthTest); - } - - [ExcludeFromDocs] - public static void DrawLine(Vector3 start, Vector3 end) - { - bool depthTest = true; - float duration = 0.0f; - Color color = Color.white; - DrawLine(start, end, color, duration, depthTest); - } - - // Draws a line from the /point/ start to /end/ with color for a duration of time and with or without depth testing. If duration is 0 then the line is rendered 1 frame. - [FreeFunction("DebugDrawLine")] - public static extern void DrawLine(Vector3 start, Vector3 end, [DefaultValue("Color.white")] Color color, [DefaultValue("0.0f")] float duration, [DefaultValue("true")] bool depthTest); - - [ExcludeFromDocs] - public static void DrawRay(Vector3 start, Vector3 dir, Color color , float duration) - { - bool depthTest = true; - DrawRay(start, dir, color, duration, depthTest); - } - - [ExcludeFromDocs] - public static void DrawRay(Vector3 start, Vector3 dir, Color color) - { - bool depthTest = true; - float duration = 0.0f; - DrawRay(start, dir, color, duration, depthTest); - } - - [ExcludeFromDocs] - public static void DrawRay(Vector3 start, Vector3 dir) - { - bool depthTest = true; - float duration = 0.0f; - Color color = Color.white; - DrawRay(start, dir, color, duration, depthTest); - } - - // Draws a line from /start/ to /start/ + /dir/ with color for a duration of time and with or without depth testing. If duration is 0 then the line is rendered 1 frame. - public static void DrawRay(Vector3 start, Vector3 dir, [DefaultValue("Color.white")] Color color , [DefaultValue("0.0f")] float duration , [DefaultValue("true")] bool depthTest) - { - DrawLine(start, start + dir, color, duration, depthTest); - } - - // Pauses the editor. - [FreeFunction("PauseEditor")] - public static extern void Break(); - - // Breaks into the attached debugger, if present - public static extern void DebugBreak(); - - // Logs /message/ to the Unity Console. - public static void Log(object message) { unityLogger.Log(LogType.Log, message); } - - // Logs /message/ to the Unity Console. - public static void Log(object message, Object context) - { - unityLogger.Log(LogType.Log, message, context); - } - - public static void LogFormat(string format, params object[] args) - { - unityLogger.LogFormat(LogType.Log, format, args); - } - - public static void LogFormat(UnityEngine.Object context, string format, params object[] args) - { - unityLogger.LogFormat(LogType.Log, context, format, args); - } - - // A variant of Debug.Log that logs an error message to the console. - public static void LogError(object message) { unityLogger.Log(LogType.Error, message); } - - // A variant of Debug.Log that logs an error message to the console. - public static void LogError(object message, Object context) { unityLogger.Log(LogType.Error, message, context); } - - public static void LogErrorFormat(string format, params object[] args) - { - unityLogger.LogFormat(LogType.Error, format, args); - } - - public static void LogErrorFormat(UnityEngine.Object context, string format, params object[] args) - { - unityLogger.LogFormat(LogType.Error, context, format, args); - } - - // Clears errors from the developer console. - public static extern void ClearDeveloperConsole(); - - // Opens or closes developer console. - public static extern bool developerConsoleVisible { get; set; } - - // A variant of Debug.Log that logs an error message from an exception to the console. - public static void LogException(Exception exception) { unityLogger.LogException(exception, null); } - - // A variant of Debug.Log that logs an error message to the console. - public static void LogException(Exception exception, Object context) { unityLogger.LogException(exception, context); } - - internal static extern void LogPlayerBuildError(string message, string file, int line, int column); - - // A variant of Debug.Log that logs a warning message to the console. - public static void LogWarning(object message) { unityLogger.Log(LogType.Warning, message); } - - // A variant of Debug.Log that logs a warning message to the console. - public static void LogWarning(object message, Object context) { unityLogger.Log(LogType.Warning, message, context); } - - public static void LogWarningFormat(string format, params object[] args) - { - unityLogger.LogFormat(LogType.Warning, format, args); - } - - public static void LogWarningFormat(UnityEngine.Object context, string format, params object[] args) - { - unityLogger.LogFormat(LogType.Warning, context, format, args); - } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void Assert(bool condition) { if (!condition) unityLogger.Log(LogType.Assert, (object)"Assertion failed"); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void Assert(bool condition, Object context) { if (!condition) unityLogger.Log(LogType.Assert, (object)"Assertion failed", context); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void Assert(bool condition, object message) { if (!condition) unityLogger.Log(LogType.Assert, message); } - - //Same as Assert (bool, object) but can't deprecate because the script updater won't work - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void Assert(bool condition, string message) { if (!condition) unityLogger.Log(LogType.Assert, (object)message); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void Assert(bool condition, object message, Object context) { if (!condition) unityLogger.Log(LogType.Assert, message, context); } - - //Same as Assert (bool, object, Object) but can't deprecate because the script updater won't work - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void Assert(bool condition, string message, Object context) { if (!condition) unityLogger.Log(LogType.Assert, (object)message, context); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void AssertFormat(bool condition, string format, params object[] args) { if (!condition) unityLogger.LogFormat(LogType.Assert, format, args); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void AssertFormat(bool condition, Object context, string format, params object[] args) { if (!condition) unityLogger.LogFormat(LogType.Assert, context, format, args); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void LogAssertion(object message) { unityLogger.Log(LogType.Assert, message); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void LogAssertion(object message, Object context) { unityLogger.Log(LogType.Assert, message, context); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void LogAssertionFormat(string format, params object[] args) { unityLogger.LogFormat(LogType.Assert, format, args); } - - [Conditional(Assertions.Assert.UNITY_ASSERTIONS)] - public static void LogAssertionFormat(Object context, string format, params object[] args) { unityLogger.LogFormat(LogType.Assert, context, format, args); } - - // In the Build Settings dialog there is a check box called "Development Build". - [StaticAccessor("GetBuildSettings()", StaticAccessorType.Dot)] - [NativeProperty(TargetType = TargetType.Field)] - public static extern bool isDebugBuild { get; } - - [FreeFunction("DeveloperConsole_OpenConsoleFile")] - internal static extern void OpenConsoleFile(); - - internal static extern void GetDiagnosticSwitches(List results); - - [NativeThrows] - internal static extern object GetDiagnosticSwitch(string name); - - [NativeThrows] - internal static extern void SetDiagnosticSwitch(string name, object value, bool setPersistent); - } -} diff --git a/Runtime/Export/DiagnosticSwitch.cs b/Runtime/Export/DiagnosticSwitch.cs deleted file mode 100644 index 0257f17784..0000000000 --- a/Runtime/Export/DiagnosticSwitch.cs +++ /dev/null @@ -1,50 +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.Runtime.InteropServices; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine -{ - // Keep this in sync with DiagnosticSwitch::SwitchFlags in C++ - [Flags] - internal enum DiagnosticSwitchFlags - { - None = 0, - CanChangeAfterEngineStart = (1 << 0) - } - - [StructLayout(LayoutKind.Sequential)] - [UsedByNativeCode] - internal struct DiagnosticSwitch - { - public string name; - public string description; - public DiagnosticSwitchFlags flags; - public object value; - public object minValue; - public object maxValue; - public object persistentValue; - public EnumInfo enumInfo; - - [UsedByNativeCode] - private static void AppendDiagnosticSwitchToList(List list, string name, string description, - DiagnosticSwitchFlags flags, object value, object minValue, object maxValue, object persistentValue, EnumInfo enumInfo) - { - list.Add(new DiagnosticSwitch - { - name = name, - description = description, - flags = flags, - value = value, - minValue = minValue, - maxValue = maxValue, - persistentValue = persistentValue, - enumInfo = enumInfo - }); - } - } -} diff --git a/Runtime/Export/Director/IPlayable.cs b/Runtime/Export/Director/IPlayable.cs deleted file mode 100644 index 5c32d39917..0000000000 --- a/Runtime/Export/Director/IPlayable.cs +++ /dev/null @@ -1,14 +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 UnityEngine.Playables -{ - public interface IPlayable - { - PlayableHandle GetHandle(); - } -} diff --git a/Runtime/Export/Director/IPlayableBehaviour.cs b/Runtime/Export/Director/IPlayableBehaviour.cs deleted file mode 100644 index b38a4bc4a4..0000000000 --- a/Runtime/Export/Director/IPlayableBehaviour.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.Reflection; -using UnityEngine; -using UnityEngineInternal; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEngine.Playables -{ - public interface IPlayableBehaviour - { - void OnGraphStart(Playable playable); - void OnGraphStop(Playable playable); - - void OnPlayableCreate(Playable playable); - void OnPlayableDestroy(Playable playable); - - void OnBehaviourPlay(Playable playable, FrameData info); - void OnBehaviourPause(Playable playable, FrameData info); - - void PrepareFrame(Playable playable, FrameData info); - void ProcessFrame(Playable playable, FrameData info, object playerData); - } -} diff --git a/Runtime/Export/Director/IPlayableOutput.cs b/Runtime/Export/Director/IPlayableOutput.cs deleted file mode 100644 index ed0eb76d3e..0000000000 --- a/Runtime/Export/Director/IPlayableOutput.cs +++ /dev/null @@ -1,14 +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 UnityEngine.Playables -{ - public interface IPlayableOutput - { - PlayableOutputHandle GetHandle(); - } -} diff --git a/Runtime/Export/Director/PlayableBehaviour.cs b/Runtime/Export/Director/PlayableBehaviour.cs deleted file mode 100644 index 816f25004f..0000000000 --- a/Runtime/Export/Director/PlayableBehaviour.cs +++ /dev/null @@ -1,38 +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.Reflection; -using UnityEngine; -using UnityEngineInternal; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEngine.Playables -{ - [Serializable] - [RequiredByNativeCode] - public abstract class PlayableBehaviour : IPlayableBehaviour, ICloneable - { - public PlayableBehaviour() {} - - public virtual void OnGraphStart(Playable playable) {} - public virtual void OnGraphStop(Playable playable) {} - - public virtual void OnPlayableCreate(Playable playable) {} - public virtual void OnPlayableDestroy(Playable playable) {} - - public virtual void OnBehaviourDelay(Playable playable, FrameData info) {} - public virtual void OnBehaviourPlay(Playable playable, FrameData info) {} - public virtual void OnBehaviourPause(Playable playable, FrameData info) {} - - public virtual void PrepareData(Playable playable, FrameData info) {} - public virtual void PrepareFrame(Playable playable, FrameData info) {} - public virtual void ProcessFrame(Playable playable, FrameData info, object playerData) {} - - public virtual object Clone() - { - return MemberwiseClone(); - } - } -} diff --git a/Runtime/Export/Director/PlayableOutput.cs b/Runtime/Export/Director/PlayableOutput.cs deleted file mode 100644 index a6ddce4551..0000000000 --- a/Runtime/Export/Director/PlayableOutput.cs +++ /dev/null @@ -1,48 +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.Scripting; -using UnityEngine.Bindings; -using System.Collections.Generic; - -namespace UnityEngine.Playables -{ - [RequiredByNativeCode] - public struct PlayableOutput : IPlayableOutput, IEquatable - { - PlayableOutputHandle m_Handle; - - static readonly PlayableOutput m_NullPlayableOutput = new PlayableOutput(PlayableOutputHandle.Null); - public static PlayableOutput Null { get { return m_NullPlayableOutput; } } - - [VisibleToOtherModules] - internal PlayableOutput(PlayableOutputHandle handle) - { - m_Handle = handle; - } - - public PlayableOutputHandle GetHandle() - { - return m_Handle; - } - - public bool IsPlayableOutputOfType() - where T : struct, IPlayableOutput - { - return GetHandle().IsPlayableOutputOfType(); - } - - public Type GetPlayableOutputType() - { - return GetHandle().GetPlayableOutputType(); - } - - public bool Equals(PlayableOutput other) - { - return GetHandle() == other.GetHandle(); - } - } -} diff --git a/Runtime/Export/Director/ScriptPlayable.cs b/Runtime/Export/Director/ScriptPlayable.cs deleted file mode 100644 index 5fa669989f..0000000000 --- a/Runtime/Export/Director/ScriptPlayable.cs +++ /dev/null @@ -1,146 +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.Reflection; -using UnityEngine; -using UnityEngineInternal; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEngine.Playables -{ - public struct ScriptPlayable : IPlayable, IEquatable> - where T : class, IPlayableBehaviour, new() - { - private PlayableHandle m_Handle; - - static readonly ScriptPlayable m_NullPlayable = new ScriptPlayable(PlayableHandle.Null); - public static ScriptPlayable Null { get { return m_NullPlayable; } } - - public static ScriptPlayable Create(PlayableGraph graph, int inputCount = 0) - { - var handle = CreateHandle(graph, null, inputCount); - return new ScriptPlayable(handle); - } - - public static ScriptPlayable Create(PlayableGraph graph, T template, int inputCount = 0) - { - var handle = CreateHandle(graph, template, inputCount); - return new ScriptPlayable(handle); - } - - private static PlayableHandle CreateHandle(PlayableGraph graph, T template, int inputCount) - { - object scriptInstance = null; - - if (template == null) - { - // We are creating a new script instance. - scriptInstance = CreateScriptInstance(); - } - else - { - // We are not creating from scratch, we are creating from a template. - scriptInstance = CloneScriptInstance(template); - } - - if (scriptInstance == null) - { - Debug.LogError("Could not create a ScriptPlayable of Type " + typeof(T).ToString()); - return PlayableHandle.Null; - } - - PlayableHandle handle = graph.CreatePlayableHandle(); - if (!handle.IsValid()) - return PlayableHandle.Null; - - handle.SetInputCount(inputCount); - - // This line should be the last one because it eventually calls - // IPlayableBehaviour.OnPlayableCreate() on scriptInstance. - handle.SetScriptInstance(scriptInstance); - - return handle; - } - - private static object CreateScriptInstance() - { - IPlayableBehaviour data = null; - - if (typeof(UnityEngine.ScriptableObject).IsAssignableFrom(typeof(T))) - data = ScriptableObject.CreateInstance(typeof(T)) as T; - else - data = new T(); - - return data; - } - - private static object CloneScriptInstance(IPlayableBehaviour source) - { - UnityEngine.Object engineObject = source as UnityEngine.Object; - if (engineObject != null) - return CloneScriptInstanceFromEngineObject(engineObject); - - ICloneable cloneableObject = source as ICloneable; - if (cloneableObject != null) - return CloneScriptInstanceFromIClonable(cloneableObject); - - return null; - } - - private static object CloneScriptInstanceFromEngineObject(UnityEngine.Object source) - { - var scriptPlayable = Object.Instantiate(source); - if (scriptPlayable != null) - { - scriptPlayable.hideFlags |= HideFlags.DontSave; - } - return scriptPlayable; - } - - private static object CloneScriptInstanceFromIClonable(ICloneable source) - { - return source.Clone(); - } - - internal ScriptPlayable(PlayableHandle handle) - { - if (handle.IsValid()) - { - if (!typeof(T).IsAssignableFrom(handle.GetPlayableType())) - throw new InvalidCastException( - String.Format( - "Incompatible handle: Trying to assign a playable data of type `{0}` that is not compatible with the PlayableBehaviour of type `{1}`.", - handle.GetPlayableType(), typeof(T))); - } - - m_Handle = handle; - } - - public PlayableHandle GetHandle() - { - return m_Handle; - } - - public T GetBehaviour() - { - return m_Handle.GetObject(); - } - - public static implicit operator Playable(ScriptPlayable playable) - { - return new Playable(playable.GetHandle()); - } - - public static explicit operator ScriptPlayable(Playable playable) - { - return new ScriptPlayable(playable.GetHandle()); - } - - public bool Equals(ScriptPlayable other) - { - return GetHandle() == other.GetHandle(); - } - } -} diff --git a/Runtime/Export/Director/ScriptPlayableOutput.cs b/Runtime/Export/Director/ScriptPlayableOutput.cs deleted file mode 100644 index 3c479564be..0000000000 --- a/Runtime/Export/Director/ScriptPlayableOutput.cs +++ /dev/null @@ -1,57 +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.Reflection; -using UnityEngine; -using UnityEngineInternal; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; - -namespace UnityEngine.Playables -{ - [RequiredByNativeCode] - public partial struct ScriptPlayableOutput : IPlayableOutput - { - private PlayableOutputHandle m_Handle; - - public static ScriptPlayableOutput Create(PlayableGraph graph, string name) - { - PlayableOutputHandle handle; - if (!graph.CreateScriptOutputInternal(name, out handle)) - return ScriptPlayableOutput.Null; - return new ScriptPlayableOutput(handle); - } - - internal ScriptPlayableOutput(PlayableOutputHandle handle) - { - if (handle.IsValid()) - { - if (!handle.IsPlayableOutputOfType()) - throw new InvalidCastException("Can't set handle: the playable is not a ScriptPlayableOutput."); - } - - m_Handle = handle; - } - - public static ScriptPlayableOutput Null - { - get { return new ScriptPlayableOutput(PlayableOutputHandle.Null); } - } - - public PlayableOutputHandle GetHandle() - { - return m_Handle; - } - - public static implicit operator PlayableOutput(ScriptPlayableOutput output) - { - return new PlayableOutput(output.GetHandle()); - } - - public static explicit operator ScriptPlayableOutput(PlayableOutput output) - { - return new ScriptPlayableOutput(output.GetHandle()); - } - } -} diff --git a/Runtime/Export/DrivenPropertyManager.bindings.cs b/Runtime/Export/DrivenPropertyManager.bindings.cs deleted file mode 100644 index 57ec8b17a3..0000000000 --- a/Runtime/Export/DrivenPropertyManager.bindings.cs +++ /dev/null @@ -1,46 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Diagnostics; -using UnityEngine; -using UnityEngine.Bindings; - -using Object = UnityEngine.Object; - -namespace UnityEngine -{ - // NOTE: internal until further notice. Used by tests - [NativeHeader("Editor/Src/Properties/DrivenPropertyManager.h")] - internal class DrivenPropertyManager - { - [Conditional("UNITY_EDITOR")] - public static void RegisterProperty(Object driver, Object target, string propertyPath) - { - RegisterPropertyPartial(driver, target, propertyPath); - } - - [Conditional("UNITY_EDITOR")] - public static void UnregisterProperty(Object driver, Object target, string propertyPath) - { - UnregisterPropertyPartial(driver, target, propertyPath); - } - - [Conditional("UNITY_EDITOR")] - [NativeConditional("UNITY_EDITOR")] - [StaticAccessor("GetDrivenPropertyManager()", StaticAccessorType.Dot)] - extern public static void UnregisterProperties([NotNull] Object driver); - - [NativeConditional("UNITY_EDITOR")] - [StaticAccessor("GetDrivenPropertyManager()", StaticAccessorType.Dot)] - extern private static void RegisterPropertyPartial([NotNull] Object driver, [NotNull] Object target, [NotNull] string propertyPath); - - [NativeConditional("UNITY_EDITOR")] - [StaticAccessor("GetDrivenPropertyManager()", StaticAccessorType.Dot)] - extern private static void UnregisterPropertyPartial([NotNull] Object driver, [NotNull] Object target, [NotNull] string propertyPath); - } -} diff --git a/Runtime/Export/EnumInfo.cs b/Runtime/Export/EnumInfo.cs deleted file mode 100644 index 0a6b1933de..0000000000 --- a/Runtime/Export/EnumInfo.cs +++ /dev/null @@ -1,29 +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.Scripting; - -namespace UnityEngine -{ - internal class EnumInfo - { - public string[] names; - public int[] values; - public string[] annotations; - public bool isFlags; - - [UsedByNativeCode] - internal static EnumInfo CreateEnumInfoFromNativeEnum(string[] names, int[] values, string[] annotations, bool isFlags) - { - EnumInfo result = new EnumInfo(); - - result.names = names; - result.values = values; - result.annotations = annotations; - result.isFlags = isFlags; - - return result; - } - } -} diff --git a/Runtime/Export/ExcludeFromObjectFactoryAttribute.cs b/Runtime/Export/ExcludeFromObjectFactoryAttribute.cs deleted file mode 100644 index d70b596b52..0000000000 --- a/Runtime/Export/ExcludeFromObjectFactoryAttribute.cs +++ /dev/null @@ -1,13 +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.Scripting; - -namespace UnityEngine -{ - [AttributeUsage(AttributeTargets.Class)] - [UsedByNativeCode] - public class ExcludeFromObjectFactoryAttribute : Attribute {} -} diff --git a/Runtime/Export/ExposedPropertyTable.bindings.cs b/Runtime/Export/ExposedPropertyTable.bindings.cs deleted file mode 100644 index a8036df110..0000000000 --- a/Runtime/Export/ExposedPropertyTable.bindings.cs +++ /dev/null @@ -1,29 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Director/Core/ExposedPropertyTable.bindings.h")] - [NativeHeader("Runtime/Utilities/PropertyName.h")] - public struct ExposedPropertyResolver - { - internal IntPtr table; - - internal static Object ResolveReferenceInternal(IntPtr ptr, PropertyName name, out bool isValid) - { - if (ptr == IntPtr.Zero) - throw new ArgumentNullException("Argument \"ptr\" can't be null."); - - return ResolveReferenceBindingsInternal(ptr, name, out isValid); - } - - [FreeFunction("ExposedPropertyTableBindings::ResolveReferenceInternal")] - extern private static Object ResolveReferenceBindingsInternal(IntPtr ptr, PropertyName name, out bool isValid); - } -} diff --git a/Runtime/Export/ExposedReference.cs b/Runtime/Export/ExposedReference.cs deleted file mode 100644 index 1ce22a5cbb..0000000000 --- a/Runtime/Export/ExposedReference.cs +++ /dev/null @@ -1,35 +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.Runtime.InteropServices; -using UnityEngine.Scripting; -using UnityEngine; - -namespace UnityEngine -{ - [System.Serializable] - [UsedByNativeCode(Name = "ExposedReference")] - [StructLayout(LayoutKind.Sequential)] - public struct ExposedReference where T : UnityEngine.Object - { - [SerializeField] - public PropertyName exposedName; - - [SerializeField] - public UnityEngine.Object defaultValue; - - public T Resolve(IExposedPropertyTable resolver) - { - if (resolver != null) - { - bool isValid; - Object result = resolver.GetReferenceValue(exposedName, out isValid); - if (isValid) - return result as T; - } - - return defaultValue as T; - } - } -} diff --git a/Runtime/Export/GI/DynamicGI.bindings.cs b/Runtime/Export/GI/DynamicGI.bindings.cs index 04a31065e6..b4e134a2a3 100644 --- a/Runtime/Export/GI/DynamicGI.bindings.cs +++ b/Runtime/Export/GI/DynamicGI.bindings.cs @@ -12,10 +12,13 @@ public sealed partial class DynamicGI { public static float indirectScale { get { return 0.0f; } set {} } public static float updateThreshold { get { return 0.0f; } set {} } + public static int materialUpdateTimeSlice { get { return 0; } set {} } public static void SetEmissive(Renderer renderer, Color color) {} public static void SetEnvironmentData(float[] input) {} public static bool synchronousMode { get { return false; } set {} } public static bool isConverged { get { return false; } } + + internal static int scheduledMaterialUpdatesCount { get { return 0; } } public static extern void UpdateEnvironment(); [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] diff --git a/Runtime/Export/GPUFence.bindings.cs b/Runtime/Export/GPUFence.bindings.cs deleted file mode 100644 index 1320852747..0000000000 --- a/Runtime/Export/GPUFence.bindings.cs +++ /dev/null @@ -1,87 +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 ShadowCastingMode = UnityEngine.Rendering.ShadowCastingMode; -using UnityEngine.Scripting; -using UnityEngine.Bindings; -using uei = UnityEngine.Internal; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - - -namespace UnityEngine.Rendering -{ - public enum SynchronisationStage - { - VertexProcessing = 0, - PixelProcessing = 1 - } - - [NativeHeader("Runtime/Graphics/GPUFence.h")] - [UsedByNativeCode] - public struct GPUFence - { - internal IntPtr m_Ptr; - internal int m_Version; - - public bool passed - { - get - { - Validate(); - - if (!SystemInfo.supportsGPUFence) - throw new System.NotSupportedException("Cannot determine if this GPUFence has passed as this platform has not implemented GPUFences."); - - if (!IsFencePending()) - return true; - - return HasFencePassed_Internal(m_Ptr); - } - } - - [FreeFunction("GPUFenceInternals::HasFencePassed_Internal")] - extern private static bool HasFencePassed_Internal(IntPtr fencePtr); - - internal void InitPostAllocation() - { - if (m_Ptr == IntPtr.Zero) - { - if (SystemInfo.supportsGPUFence) - { - throw new System.NullReferenceException("The internal fence ptr is null, this should not be possible for fences that have been correctly constructed using Graphics.CreateGPUFence() or CommandBuffer.CreateGPUFence()"); - } - m_Version = GetPlatformNotSupportedVersion(); - return; - } - - m_Version = GetVersionNumber(m_Ptr); - } - - internal bool IsFencePending() - { - if (m_Ptr == IntPtr.Zero) - return false; - - return m_Version == GetVersionNumber(m_Ptr); - } - - internal void Validate() - { - if (m_Version == 0 || (SystemInfo.supportsGPUFence && m_Version == GetPlatformNotSupportedVersion())) - throw new System.InvalidOperationException("This GPUFence object has not been correctly constructed see Graphics.CreateGPUFence() or CommandBuffer.CreateGPUFence()"); - } - - private int GetPlatformNotSupportedVersion() - { - return -1; - } - - [NativeThrows] - [FreeFunction("GPUFenceInternals::GetVersionNumber")] - extern private static int GetVersionNumber(IntPtr fencePtr); - } -} diff --git a/Runtime/Export/GeometryUtility.cs b/Runtime/Export/GeometryUtility.cs deleted file mode 100644 index c858353b73..0000000000 --- a/Runtime/Export/GeometryUtility.cs +++ /dev/null @@ -1,89 +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 UnityEngine -{ - public sealed partial class GeometryUtility - { - public static Plane[] CalculateFrustumPlanes(Camera camera) - { - Plane[] planes = new Plane[6]; - CalculateFrustumPlanes(camera, planes); - return planes; - } - - public static Plane[] CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix) - { - Plane[] planes = new Plane[6]; - CalculateFrustumPlanes(worldToProjectionMatrix, planes); - return planes; - } - - public static void CalculateFrustumPlanes(Camera camera, Plane[] planes) - { - CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix, planes); - } - - public static void CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix, Plane[] planes) - { - if (planes == null) throw new ArgumentNullException("planes"); - if (planes.Length != 6) throw new ArgumentException("Planes array must be of length 6.", "planes"); - Internal_ExtractPlanes(planes, worldToProjectionMatrix); - } - - public static Bounds CalculateBounds(Vector3[] positions, Matrix4x4 transform) - { - if (positions == null) throw new ArgumentNullException("positions"); - if (positions.Length == 0) throw new ArgumentException("Zero-sized array is not allowed.", "positions"); - return Internal_CalculateBounds(positions, transform); - } - - // Creates a plane for a polygon that's defined by an array of vertices. Works for concave polygons, polygons containing colinear vertices as well as non-planar polygons. - // Returns false if it's not possible to determine a plane for the given vertices. - // This can happen for certain self-intersecting polygons or when all vertices are all aligned in a line or a single point. - public static bool TryCreatePlaneFromPolygon(Vector3[] vertices, out Plane plane) - { - if (vertices == null || vertices.Length < 3) - { - plane = new Plane(Vector3.up, 0); - return false; - } - if (vertices.Length == 3) - { - var v0 = vertices[0]; - var v1 = vertices[1]; - var v2 = vertices[2]; - plane = new Plane(v0, v1, v2); - return plane.normal.sqrMagnitude > 0; - } - - Vector3 normal = Vector3.zero; - int prev_index = vertices.Length - 1; - Vector3 prev_vertex = vertices[prev_index]; - for (int e = 0; e < vertices.Length; e++) - { - Vector3 curr_vertex = vertices[e]; - normal.x = normal.x + ((prev_vertex.y - curr_vertex.y) * (prev_vertex.z + curr_vertex.z)); - normal.y = normal.y + ((prev_vertex.z - curr_vertex.z) * (prev_vertex.x + curr_vertex.x)); - normal.z = normal.z + ((prev_vertex.x - curr_vertex.x) * (prev_vertex.y + curr_vertex.y)); - - prev_vertex = curr_vertex; - } - normal.Normalize(); - - float d = 0; - for (int e = 0; e < vertices.Length; e++) - { - Vector3 curr_vertex = vertices[e]; - d -= Vector3.Dot(normal, curr_vertex); - } - d /= vertices.Length; - - plane = new Plane(normal, d); - return plane.normal.sqrMagnitude > 0; - } - } -} diff --git a/Runtime/Export/GraphicsEnums.cs b/Runtime/Export/GraphicsEnums.cs index 1546184f20..b1ac63f5e6 100644 --- a/Runtime/Export/GraphicsEnums.cs +++ b/Runtime/Export/GraphicsEnums.cs @@ -961,6 +961,17 @@ public enum CameraEvent AfterHaloAndLensFlares } + internal static class CameraEventUtils + { + const CameraEvent k_MinimumValue = CameraEvent.BeforeDepthTexture; + const CameraEvent k_MaximumValue = CameraEvent.AfterHaloAndLensFlares; + + public static bool IsValid(CameraEvent value) + { + return value >= k_MinimumValue && value <= k_MaximumValue; + } + } + // Keep in sync with RenderLightEventType in Runtime/Graphics/CommandBuffer/RenderingEvents.h public enum LightEvent { diff --git a/Runtime/Export/GraphicsManagers.bindings.cs b/Runtime/Export/GraphicsManagers.bindings.cs index d5315d7c90..0e85526478 100644 --- a/Runtime/Export/GraphicsManagers.bindings.cs +++ b/Runtime/Export/GraphicsManagers.bindings.cs @@ -84,6 +84,8 @@ private QualitySettings() {} extern public static int antiAliasing { get; set; } extern public static int asyncUploadTimeSlice { get; set; } extern public static int asyncUploadBufferSize { get; set; } + extern public static bool asyncUploadPersistentBuffer { get; set; } + extern public static bool realtimeReflectionProbes { get; set; } extern public static bool billboardsFaceCameraPosition { get; set; } diff --git a/Runtime/Export/Handheld.cs b/Runtime/Export/Handheld.cs deleted file mode 100644 index 0ba5ec9ae6..0000000000 --- a/Runtime/Export/Handheld.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 System; - -namespace UnityEngine -{ - public partial class TouchScreenKeyboard - { - // The status of the on-screen keyboard - public enum Status - { - // The on-screen keyboard is open. - Visible = 0, - // The on-screen keyboard was closed with ok / done buttons. - Done = 1, - // The on-screen keyboard was closed with a back button. - Canceled = 2, - // The on-screen keyboard was closed by touching outside of the keyboard. - LostFocus = 3, - }; - } -} diff --git a/Runtime/Export/IExposedPropertyTable.cs b/Runtime/Export/IExposedPropertyTable.cs deleted file mode 100644 index fe31a84336..0000000000 --- a/Runtime/Export/IExposedPropertyTable.cs +++ /dev/null @@ -1,17 +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.Runtime.InteropServices; -using UnityEngine.Scripting; -using UnityEngine; - -namespace UnityEngine -{ - public interface IExposedPropertyTable - { - void SetReferenceValue(PropertyName id, UnityEngine.Object value); - UnityEngine.Object GetReferenceValue(PropertyName id, out bool idValid); - void ClearReferenceValue(PropertyName id); - } -} diff --git a/Runtime/Export/Internal/DefaultValueAttribute.cs b/Runtime/Export/Internal/DefaultValueAttribute.cs deleted file mode 100644 index fbbaa32f61..0000000000 --- a/Runtime/Export/Internal/DefaultValueAttribute.cs +++ /dev/null @@ -1,47 +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 UnityEngine.Internal -{ - /// - /// Adds default value information for optional parameters - /// - [Serializable] - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)] - public class DefaultValueAttribute : Attribute - { - private object DefaultValue; - - public DefaultValueAttribute(string value) - { - DefaultValue = value; - } - - public object Value - { - get { return DefaultValue; } - } - - public override bool Equals(object obj) - { - DefaultValueAttribute dva = (obj as DefaultValueAttribute); - if (dva == null) - return false; - - if (DefaultValue == null) - return (dva.Value == null); - - return DefaultValue.Equals(dva.Value); - } - - public override int GetHashCode() - { - if (DefaultValue == null) - return base.GetHashCode(); - return DefaultValue.GetHashCode(); - } - } -} diff --git a/Runtime/Export/Internal/ExcludeFromDocs.cs b/Runtime/Export/Internal/ExcludeFromDocs.cs deleted file mode 100644 index d7506807ca..0000000000 --- a/Runtime/Export/Internal/ExcludeFromDocs.cs +++ /dev/null @@ -1,19 +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 UnityEngine.Internal -{ - /// - /// Adds default value information for optional parameters - /// - [Serializable] - public class ExcludeFromDocsAttribute : Attribute - { - public ExcludeFromDocsAttribute() - { - } - } -} diff --git a/Runtime/Export/Light.deprecated.cs b/Runtime/Export/Light.deprecated.cs deleted file mode 100644 index e0a18a2c7d..0000000000 --- a/Runtime/Export/Light.deprecated.cs +++ /dev/null @@ -1,52 +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 UnityEngine -{ - [System.Obsolete("LightmappingMode has been deprecated. Use LightmapBakeType instead (UnityUpgradable) -> LightmapBakeType", true)] - public enum LightmappingMode - { - [System.Obsolete("LightmappingMode.Realtime has been deprecated. Use LightmapBakeType.Realtime instead (UnityUpgradable) -> LightmapBakeType.Realtime", true)] - Realtime = 4, - [System.Obsolete("LightmappingMode.Baked has been deprecated. Use LightmapBakeType.Baked instead (UnityUpgradable) -> LightmapBakeType.Baked", true)] - Baked = 2, - [System.Obsolete("LightmappingMode.Mixed has been deprecated. Use LightmapBakeType.Mixed instead (UnityUpgradable) -> LightmapBakeType.Mixed", true)] - Mixed = 1 - } - - public partial class Light - { - [System.Obsolete("Light.lightmappingMode has been deprecated. Use Light.lightmapBakeType instead (UnityUpgradable) -> lightmapBakeType", true)] - public LightmappingMode lightmappingMode - { - get { return LightmappingMode.Realtime; } - set {} - } - - [System.Obsolete("Light.isBaked is no longer supported. Use Light.bakingOutput.isBaked (and other members of Light.bakingOutput) instead.", false)] - public bool isBaked - { - get { return bakingOutput.isBaked; } - } - - [System.Obsolete("Light.alreadyLightmapped is no longer supported. Use Light.bakingOutput instead. Allowing to describe mixed light on top of realtime and baked ones.", false)] - public bool alreadyLightmapped - { - get { return bakingOutput.isBaked; } - set - { - var lightBakingOutput = new LightBakingOutput - { - probeOcclusionLightIndex = -1, - occlusionMaskChannel = -1, - lightmapBakeType = (value) ? LightmapBakeType.Baked : LightmapBakeType.Realtime, - isBaked = value - }; - bakingOutput = lightBakingOutput; - } - } - } -} - diff --git a/Runtime/Export/LineUtility.cs b/Runtime/Export/LineUtility.cs deleted file mode 100644 index 457dd03daa..0000000000 --- a/Runtime/Export/LineUtility.cs +++ /dev/null @@ -1,52 +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; - -namespace UnityEngine -{ - public partial class LineUtility - { - public static void Simplify(List points, float tolerance, List pointsToKeep) - { - if (points == null) - throw new ArgumentNullException("points"); - if (pointsToKeep == null) - throw new ArgumentNullException("pointsToKeep"); - - GeneratePointsToKeep3D(points, tolerance, pointsToKeep); - } - - public static void Simplify(List points, float tolerance, List simplifiedPoints) - { - if (points == null) - throw new ArgumentNullException("points"); - if (simplifiedPoints == null) - throw new ArgumentNullException("simplifiedPoints"); - - GenerateSimplifiedPoints3D(points, tolerance, simplifiedPoints); - } - - public static void Simplify(List points, float tolerance, List pointsToKeep) - { - if (points == null) - throw new ArgumentNullException("points"); - if (pointsToKeep == null) - throw new ArgumentNullException("pointsToKeep"); - - GeneratePointsToKeep2D(points, tolerance, pointsToKeep); - } - - public static void Simplify(List points, float tolerance, List simplifiedPoints) - { - if (points == null) - throw new ArgumentNullException("points"); - if (simplifiedPoints == null) - throw new ArgumentNullException("simplifiedPoints"); - - GenerateSimplifiedPoints2D(points, tolerance, simplifiedPoints); - } - } -} diff --git a/Runtime/Export/Logger/DebugLogHandler.cs b/Runtime/Export/Logger/DebugLogHandler.cs deleted file mode 100644 index c60c63622a..0000000000 --- a/Runtime/Export/Logger/DebugLogHandler.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 UnityEngine -{ - internal partial class DebugLogHandler : ILogHandler - { - public void LogFormat(LogType logType, Object context, string format, params object[] args) - { - Internal_Log(logType, string.Format(format, args), context); - } - - public void LogException(Exception exception, Object context) - { - Internal_LogException(exception, context); - } - } -} diff --git a/Runtime/Export/Logger/ILogHandler.cs b/Runtime/Export/Logger/ILogHandler.cs deleted file mode 100644 index 015be767a5..0000000000 --- a/Runtime/Export/Logger/ILogHandler.cs +++ /dev/null @@ -1,15 +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 UnityEngine -{ - public interface ILogHandler - { - void LogFormat(LogType logType, Object context, string format, params object[] args); - - void LogException(Exception exception, Object context); - } -} diff --git a/Runtime/Export/Logger/ILogger.cs b/Runtime/Export/Logger/ILogger.cs deleted file mode 100644 index d11a9bba72..0000000000 --- a/Runtime/Export/Logger/ILogger.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 System; - -namespace UnityEngine -{ - public interface ILogger : ILogHandler - { - ILogHandler logHandler { get; set; } - - bool logEnabled { get; set; } - - LogType filterLogType { get; set; } - - bool IsLogTypeAllowed(LogType logType); - - void Log(LogType logType, object message); - - void Log(LogType logType, object message, Object context); - - void Log(LogType logType, string tag, object message); - - void Log(LogType logType, string tag, object message, Object context); - - void Log(object message); - - void Log(string tag, object message); - - void Log(string tag, object message, Object context); - - void LogWarning(string tag, object message); - - void LogWarning(string tag, object message, Object context); - - void LogError(string tag, object message); - - void LogError(string tag, object message, Object context); - - void LogFormat(LogType logType, string format, params object[] args); - - void LogException(Exception exception); - } -} diff --git a/Runtime/Export/Logger/Logger.cs b/Runtime/Export/Logger/Logger.cs deleted file mode 100644 index f5172b59a7..0000000000 --- a/Runtime/Export/Logger/Logger.cs +++ /dev/null @@ -1,138 +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 UnityEngine -{ - public class Logger : ILogger - { - private const string kNoTagFormat = "{0}"; - private const string kTagFormat = "{0}: {1}"; - - private Logger() - {} - - public Logger(ILogHandler logHandler) - { - this.logHandler = logHandler; - this.logEnabled = true; - this.filterLogType = LogType.Log; - } - - public ILogHandler logHandler { get; set; } - - public bool logEnabled { get; set; } - - public LogType filterLogType { get; set; } - - public bool IsLogTypeAllowed(LogType logType) - { - if (logEnabled) - { - if (logType == LogType.Exception) - return true; - - if (filterLogType != LogType.Exception) - return (logType <= filterLogType); - } - return false; - } - - private static string GetString(object message) - { - return message != null ? message.ToString() : "Null"; - } - - public void Log(LogType logType, object message) - { - if (IsLogTypeAllowed(logType)) - logHandler.LogFormat(logType, null, kNoTagFormat, new object[] {GetString(message)}); - } - - public void Log(LogType logType, object message, Object context) - { - if (IsLogTypeAllowed(logType)) - logHandler.LogFormat(logType, context, kNoTagFormat, new object[] {GetString(message)}); - } - - public void Log(LogType logType, string tag, object message) - { - if (IsLogTypeAllowed(logType)) - logHandler.LogFormat(logType, null, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void Log(LogType logType, string tag, object message, Object context) - { - if (IsLogTypeAllowed(logType)) - logHandler.LogFormat(logType, context, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void Log(object message) - { - if (IsLogTypeAllowed(LogType.Log)) - logHandler.LogFormat(LogType.Log, null, kNoTagFormat, new object[] {GetString(message)}); - } - - public void Log(string tag, object message) - { - if (IsLogTypeAllowed(LogType.Log)) - logHandler.LogFormat(LogType.Log, null, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void Log(string tag, object message, Object context) - { - if (IsLogTypeAllowed(LogType.Log)) - logHandler.LogFormat(LogType.Log, context, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void LogWarning(string tag, object message) - { - if (IsLogTypeAllowed(LogType.Warning)) - logHandler.LogFormat(LogType.Warning, null, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void LogWarning(string tag, object message, Object context) - { - if (IsLogTypeAllowed(LogType.Warning)) - logHandler.LogFormat(LogType.Warning, context, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void LogError(string tag, object message) - { - if (IsLogTypeAllowed(LogType.Error)) - logHandler.LogFormat(LogType.Error, null, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void LogError(string tag, object message, Object context) - { - if (IsLogTypeAllowed(LogType.Error)) - logHandler.LogFormat(LogType.Error, context, kTagFormat, new object[] {tag, GetString(message)}); - } - - public void LogFormat(LogType logType, string format, params object[] args) - { - if (IsLogTypeAllowed(logType)) - logHandler.LogFormat(logType, null, format, args); - } - - public void LogException(Exception exception) - { - if (logEnabled) - logHandler.LogException(exception, null); - } - - public void LogFormat(LogType logType, Object context, string format, params object[] args) - { - if (IsLogTypeAllowed(logType)) - logHandler.LogFormat(logType, context, format, args); - } - - public void LogException(Exception exception, Object context) - { - if (logEnabled) - logHandler.LogException(exception, context); - } - } -} diff --git a/Runtime/Export/ManagedStreamHelpers.cs b/Runtime/Export/ManagedStreamHelpers.cs deleted file mode 100644 index 75eadad933..0000000000 --- a/Runtime/Export/ManagedStreamHelpers.cs +++ /dev/null @@ -1,49 +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.Scripting; - -namespace UnityEngine -{ - internal static class ManagedStreamHelpers - { - internal static void ValidateLoadFromStream(System.IO.Stream stream) - { - if (stream == null) - throw new System.ArgumentNullException("ManagedStream object must be non-null", "stream"); - if (!stream.CanRead) - throw new System.ArgumentException("ManagedStream object must be readable (stream.CanRead must return true)", "stream"); - if (!stream.CanSeek) - throw new System.ArgumentException("ManagedStream object must be seekable (stream.CanSeek must return true)", "stream"); - } - - [RequiredByNativeCode] - unsafe internal static void ManagedStreamRead(byte[] buffer, int offset, int count, System.IO.Stream stream, IntPtr returnValueAddress) - { - if (returnValueAddress == IntPtr.Zero) - throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); - ValidateLoadFromStream(stream); - (*(int*)returnValueAddress) = stream.Read(buffer, offset, count); - } - - [RequiredByNativeCode] - unsafe internal static void ManagedStreamSeek(long offset, uint origin, System.IO.Stream stream, IntPtr returnValueAddress) - { - if (returnValueAddress == IntPtr.Zero) - throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); - ValidateLoadFromStream(stream); - (*(long*)returnValueAddress) = stream.Seek(offset, (System.IO.SeekOrigin)origin); - } - - [RequiredByNativeCode] - unsafe internal static void ManagedStreamLength(System.IO.Stream stream, IntPtr returnValueAddress) - { - if (returnValueAddress == IntPtr.Zero) - throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); - ValidateLoadFromStream(stream); - (*(long*)returnValueAddress) = stream.Length; - } - } -} diff --git a/Runtime/Export/Mathf.cs b/Runtime/Export/Mathf.cs deleted file mode 100644 index 75aa355d76..0000000000 --- a/Runtime/Export/Mathf.cs +++ /dev/null @@ -1,441 +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.Threading; -using uei = UnityEngine.Internal; - -namespace UnityEngineInternal -{ - public partial struct MathfInternal - { - public static volatile float FloatMinNormal = 1.17549435E-38f; - public static volatile float FloatMinDenormal = Single.Epsilon; - - public static bool IsFlushToZeroEnabled = (FloatMinDenormal == 0); - } -} - -namespace UnityEngine -{ - // A collection of common math functions. - public partial struct Mathf - { - // Returns the sine of angle /f/ in radians. - public static float Sin(float f) { return (float)Math.Sin(f); } - - // Returns the cosine of angle /f/ in radians. - public static float Cos(float f) { return (float)Math.Cos(f); } - - // Returns the tangent of angle /f/ in radians. - public static float Tan(float f) { return (float)Math.Tan(f); } - - // Returns the arc-sine of /f/ - the angle in radians whose sine is /f/. - public static float Asin(float f) { return (float)Math.Asin(f); } - - // Returns the arc-cosine of /f/ - the angle in radians whose cosine is /f/. - public static float Acos(float f) { return (float)Math.Acos(f); } - - // Returns the arc-tangent of /f/ - the angle in radians whose tangent is /f/. - public static float Atan(float f) { return (float)Math.Atan(f); } - - // Returns the angle in radians whose ::ref::Tan is @@y/x@@. - public static float Atan2(float y, float x) { return (float)Math.Atan2(y, x); } - - // Returns square root of /f/. - public static float Sqrt(float f) { return (float)Math.Sqrt(f); } - - // Returns the absolute value of /f/. - public static float Abs(float f) { return (float)Math.Abs(f); } - - // Returns the absolute value of /value/. - public static int Abs(int value) { return Math.Abs(value); } - - /// *listonly* - public static float Min(float a, float b) { return a < b ? a : b; } - // Returns the smallest of two or more values. - public static float Min(params float[] values) - { - int len = values.Length; - if (len == 0) - return 0; - float m = values[0]; - for (int i = 1; i < len; i++) - { - if (values[i] < m) - m = values[i]; - } - return m; - } - - /// *listonly* - public static int Min(int a, int b) { return a < b ? a : b; } - // Returns the smallest of two or more values. - public static int Min(params int[] values) - { - int len = values.Length; - if (len == 0) - return 0; - int m = values[0]; - for (int i = 1; i < len; i++) - { - if (values[i] < m) - m = values[i]; - } - return m; - } - - /// *listonly* - public static float Max(float a, float b) { return a > b ? a : b; } - // Returns largest of two or more values. - public static float Max(params float[] values) - { - int len = values.Length; - if (len == 0) - return 0; - float m = values[0]; - for (int i = 1; i < len; i++) - { - if (values[i] > m) - m = values[i]; - } - return m; - } - - /// *listonly* - public static int Max(int a, int b) { return a > b ? a : b; } - // Returns the largest of two or more values. - public static int Max(params int[] values) - { - int len = values.Length; - if (len == 0) - return 0; - int m = values[0]; - for (int i = 1; i < len; i++) - { - if (values[i] > m) - m = values[i]; - } - return m; - } - - // Returns /f/ raised to power /p/. - public static float Pow(float f, float p) { return (float)Math.Pow(f, p); } - - // Returns e raised to the specified power. - public static float Exp(float power) { return (float)Math.Exp(power); } - - // Returns the logarithm of a specified number in a specified base. - public static float Log(float f, float p) { return (float)Math.Log(f, p); } - - // Returns the natural (base e) logarithm of a specified number. - public static float Log(float f) { return (float)Math.Log(f); } - - // Returns the base 10 logarithm of a specified number. - public static float Log10(float f) { return (float)Math.Log10(f); } - - // Returns the smallest integer greater to or equal to /f/. - public static float Ceil(float f) { return (float)Math.Ceiling(f); } - - // Returns the largest integer smaller to or equal to /f/. - public static float Floor(float f) { return (float)Math.Floor(f); } - - // Returns /f/ rounded to the nearest integer. - public static float Round(float f) { return (float)Math.Round(f); } - - // Returns the smallest integer greater to or equal to /f/. - public static int CeilToInt(float f) { return (int)Math.Ceiling(f); } - - // Returns the largest integer smaller to or equal to /f/. - public static int FloorToInt(float f) { return (int)Math.Floor(f); } - - // Returns /f/ rounded to the nearest integer. - public static int RoundToInt(float f) { return (int)Math.Round(f); } - - // Returns the sign of /f/. - public static float Sign(float f) { return f >= 0F ? 1F : -1F; } - - // The infamous ''3.14159265358979...'' value (RO). - public const float PI = (float)Math.PI; - - // A representation of positive infinity (RO). - public const float Infinity = Single.PositiveInfinity; - - // A representation of negative infinity (RO). - public const float NegativeInfinity = Single.NegativeInfinity; - - // Degrees-to-radians conversion constant (RO). - public const float Deg2Rad = PI * 2F / 360F; - - // Radians-to-degrees conversion constant (RO). - public const float Rad2Deg = 1F / Deg2Rad; - - // A tiny floating point value (RO). - public static readonly float Epsilon = - UnityEngineInternal.MathfInternal.IsFlushToZeroEnabled ? UnityEngineInternal.MathfInternal.FloatMinNormal - : UnityEngineInternal.MathfInternal.FloatMinDenormal; - - // Clamps a value between a minimum float and maximum float value. - public static float Clamp(float value, float min, float max) - { - if (value < min) - value = min; - else if (value > max) - value = max; - return value; - } - - // Clamps value between min and max and returns value. - // Set the position of the transform to be that of the time - // but never less than 1 or more than 3 - // - public static int Clamp(int value, int min, int max) - { - if (value < min) - value = min; - else if (value > max) - value = max; - return value; - } - - // Clamps value between 0 and 1 and returns value - public static float Clamp01(float value) - { - if (value < 0F) - return 0F; - else if (value > 1F) - return 1F; - else - return value; - } - - // Interpolates between /a/ and /b/ by /t/. /t/ is clamped between 0 and 1. - public static float Lerp(float a, float b, float t) - { - return a + (b - a) * Clamp01(t); - } - - // Interpolates between /a/ and /b/ by /t/ without clamping the interpolant. - public static float LerpUnclamped(float a, float b, float t) - { - return a + (b - a) * t; - } - - // Same as ::ref::Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees. - public static float LerpAngle(float a, float b, float t) - { - float delta = Repeat((b - a), 360); - if (delta > 180) - delta -= 360; - return a + delta * Clamp01(t); - } - - // Moves a value /current/ towards /target/. - static public float MoveTowards(float current, float target, float maxDelta) - { - if (Mathf.Abs(target - current) <= maxDelta) - return target; - return current + Mathf.Sign(target - current) * maxDelta; - } - - // Same as ::ref::MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees. - static public float MoveTowardsAngle(float current, float target, float maxDelta) - { - float deltaAngle = DeltaAngle(current, target); - if (-maxDelta < deltaAngle && deltaAngle < maxDelta) - return target; - target = current + deltaAngle; - return MoveTowards(current, target, maxDelta); - } - - // Interpolates between /min/ and /max/ with smoothing at the limits. - public static float SmoothStep(float from, float to, float t) - { - t = Mathf.Clamp01(t); - t = -2.0F * t * t * t + 3.0F * t * t; - return to * t + from * (1F - t); - } - - //*undocumented - public static float Gamma(float value, float absmax, float gamma) - { - bool negative = false; - if (value < 0F) - negative = true; - float absval = Abs(value); - if (absval > absmax) - return negative ? -absval : absval; - - float result = Pow(absval / absmax, gamma) * absmax; - return negative ? -result : result; - } - - // Compares two floating point values if they are similar. - public static bool Approximately(float a, float b) - { - // If a or b is zero, compare that the other is less or equal to epsilon. - // If neither a or b are 0, then find an epsilon that is good for - // comparing numbers at the maximum magnitude of a and b. - // Floating points have about 7 significant digits, so - // 1.000001f can be represented while 1.0000001f is rounded to zero, - // thus we could use an epsilon of 0.000001f for comparing values close to 1. - // We multiply this epsilon by the biggest magnitude of a and b. - return Abs(b - a) < Max(0.000001f * Max(Abs(a), Abs(b)), Epsilon * 8); - } - - [uei.ExcludeFromDocs] - public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) - { - float deltaTime = Time.deltaTime; - return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); - } - - [uei.ExcludeFromDocs] - public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime) - { - float deltaTime = Time.deltaTime; - float maxSpeed = Mathf.Infinity; - return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); - } - - // Gradually changes a value towards a desired goal over time. - public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, [uei.DefaultValue("Mathf.Infinity")] float maxSpeed, [uei.DefaultValue("Time.deltaTime")] float deltaTime) - { - // Based on Game Programming Gems 4 Chapter 1.10 - smoothTime = Mathf.Max(0.0001F, smoothTime); - float omega = 2F / smoothTime; - - float x = omega * deltaTime; - float exp = 1F / (1F + x + 0.48F * x * x + 0.235F * x * x * x); - float change = current - target; - float originalTo = target; - - // Clamp maximum speed - float maxChange = maxSpeed * smoothTime; - change = Mathf.Clamp(change, -maxChange, maxChange); - target = current - change; - - float temp = (currentVelocity + omega * change) * deltaTime; - currentVelocity = (currentVelocity - omega * temp) * exp; - float output = target + (change + temp) * exp; - - // Prevent overshooting - if (originalTo - current > 0.0F == output > originalTo) - { - output = originalTo; - currentVelocity = (output - originalTo) / deltaTime; - } - - return output; - } - - [uei.ExcludeFromDocs] - public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) - { - float deltaTime = Time.deltaTime; - return SmoothDampAngle(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); - } - - [uei.ExcludeFromDocs] - public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime) - { - float deltaTime = Time.deltaTime; - float maxSpeed = Mathf.Infinity; - return SmoothDampAngle(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); - } - - // Gradually changes an angle given in degrees towards a desired goal angle over time. - public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime, [uei.DefaultValue("Mathf.Infinity")] float maxSpeed, [uei.DefaultValue("Time.deltaTime")] float deltaTime) - { - target = current + DeltaAngle(current, target); - return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); - } - - // Loops the value t, so that it is never larger than length and never smaller than 0. - public static float Repeat(float t, float length) - { - return Clamp(t - Mathf.Floor(t / length) * length, 0.0f, length); - } - - // PingPongs the value t, so that it is never larger than length and never smaller than 0. - public static float PingPong(float t, float length) - { - t = Repeat(t, length * 2F); - return length - Mathf.Abs(t - length); - } - - // Calculates the ::ref::Lerp parameter between of two values. - public static float InverseLerp(float a, float b, float value) - { - if (a != b) - return Clamp01((value - a) / (b - a)); - else - return 0.0f; - } - - // Calculates the shortest difference between two given angles. - public static float DeltaAngle(float current, float target) - { - float delta = Mathf.Repeat((target - current), 360.0F); - if (delta > 180.0F) - delta -= 360.0F; - return delta; - } - - // Infinite Line Intersection (line1 is p1-p2 and line2 is p3-p4) - internal static bool LineIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, ref Vector2 result) - { - float bx = p2.x - p1.x; - float by = p2.y - p1.y; - float dx = p4.x - p3.x; - float dy = p4.y - p3.y; - float bDotDPerp = bx * dy - by * dx; - if (bDotDPerp == 0) - { - return false; - } - float cx = p3.x - p1.x; - float cy = p3.y - p1.y; - float t = (cx * dy - cy * dx) / bDotDPerp; - - result = new Vector2(p1.x + t * bx, p1.y + t * by); - return true; - } - - // Line Segment Intersection (line1 is p1-p2 and line2 is p3-p4) - internal static bool LineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, ref Vector2 result) - { - float bx = p2.x - p1.x; - float by = p2.y - p1.y; - float dx = p4.x - p3.x; - float dy = p4.y - p3.y; - float bDotDPerp = bx * dy - by * dx; - if (bDotDPerp == 0) - { - return false; - } - float cx = p3.x - p1.x; - float cy = p3.y - p1.y; - float t = (cx * dy - cy * dx) / bDotDPerp; - if (t < 0 || t > 1) - { - return false; - } - float u = (cx * by - cy * bx) / bDotDPerp; - if (u < 0 || u > 1) - { - return false; - } - result = new Vector2(p1.x + t * bx, p1.y + t * by); - return true; - } - - static internal long RandomToLong(System.Random r) - { - var buffer = new byte[8]; - r.NextBytes(buffer); - return (long)(System.BitConverter.ToUInt64(buffer, 0) & System.Int64.MaxValue); - } - } -} diff --git a/Runtime/Export/Metro.cs b/Runtime/Export/Metro.cs deleted file mode 100644 index a4290ed40c..0000000000 --- a/Runtime/Export/Metro.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 System; -using System.Diagnostics; -using System.Reflection; - -namespace UnityEngineInternal -{ - using UnityEngine; - - public delegate void FastCallExceptionHandler(Exception ex); - public delegate MethodInfo GetMethodDelegate(Type classType, string methodName, bool searchBaseTypes, bool instanceMethod, Type[] methodParamTypes); - - public partial class ScriptingUtils - { - - public static Delegate CreateDelegate(Type type, MethodInfo methodInfo) - { - return Delegate.CreateDelegate(type, methodInfo); - } - } -} diff --git a/Runtime/Export/Networking/PlayerConnection/PlayerEditorConnectionEvents.cs b/Runtime/Export/Networking/PlayerConnection/PlayerEditorConnectionEvents.cs deleted file mode 100644 index 4b2d36605b..0000000000 --- a/Runtime/Export/Networking/PlayerConnection/PlayerEditorConnectionEvents.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 System.Collections.Generic; -using System.Linq; -using UnityEngine.Events; - -namespace UnityEngine.Networking.PlayerConnection -{ - [Serializable] - internal class PlayerEditorConnectionEvents - { - [SerializeField] - public List messageTypeSubscribers = new List(); - - [SerializeField] - public ConnectionChangeEvent connectionEvent = new ConnectionChangeEvent(); - - [SerializeField] - public ConnectionChangeEvent disconnectionEvent = new ConnectionChangeEvent(); - - [Serializable] - public class MessageEvent : UnityEvent {} - - [Serializable] - public class ConnectionChangeEvent : UnityEvent {} - - [Serializable] - public class MessageTypeSubscribers - { - [SerializeField] - private string m_messageTypeId; - - public Guid MessageTypeId - { - get - { - return new Guid(m_messageTypeId); - } - set - { - m_messageTypeId = value.ToString(); - } - } - - public int subscriberCount = 0; - - public MessageEvent messageCallback = new MessageEvent(); - } - - public void InvokeMessageIdSubscribers(Guid messageId, byte[] data, int playerId) - { - IEnumerable messageSubscribers = messageTypeSubscribers.Where(x => x.MessageTypeId == messageId); - if (!messageSubscribers.Any()) - { - Debug.LogError("No actions found for messageId: " + messageId); - return; - } - - var messageEventArg = new MessageEventArgs - { - playerId = playerId, - data = data, - }; - - foreach (var eventSubscriber in messageSubscribers) - { - eventSubscriber.messageCallback.Invoke(messageEventArg); - } - } - - public UnityEvent AddAndCreate(Guid messageId) - { - var MessageTypeSubscriber = messageTypeSubscribers.SingleOrDefault(x => x.MessageTypeId == messageId); - if (MessageTypeSubscriber == null) - { - MessageTypeSubscriber = new MessageTypeSubscribers - { - MessageTypeId = messageId, - messageCallback = new MessageEvent() - }; - - messageTypeSubscribers.Add(MessageTypeSubscriber); - } - MessageTypeSubscriber.subscriberCount++; - return MessageTypeSubscriber.messageCallback; - } - - public void UnregisterManagedCallback(Guid messageId, UnityAction callback) - { - var messageTypeSubscriber = messageTypeSubscribers.SingleOrDefault(x => x.MessageTypeId == messageId); - - if (messageTypeSubscriber == null) - { - return; - } - messageTypeSubscriber.subscriberCount--; - messageTypeSubscriber.messageCallback.RemoveListener(callback); - if (messageTypeSubscriber.subscriberCount <= 0) - { - messageTypeSubscribers.Remove(messageTypeSubscriber); - } - } - } -} diff --git a/Runtime/Export/Plane.cs b/Runtime/Export/Plane.cs deleted file mode 100644 index 27e399b6a0..0000000000 --- a/Runtime/Export/Plane.cs +++ /dev/null @@ -1,128 +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.Runtime.InteropServices; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - // Representation of planes. Uses the formula Ax + By + Cz + D = 0. - [UsedByNativeCode] - [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] - public partial struct Plane - { - Vector3 m_Normal; - float m_Distance; - - // Normal vector of the plane. - public Vector3 normal - { - get { return m_Normal; } - set { m_Normal = value; } - } - // Distance from the origin to the plane. - public float distance - { - get { return m_Distance; } - set { m_Distance = value; } - } - - // Creates a plane. - public Plane(Vector3 inNormal, Vector3 inPoint) - { - m_Normal = Vector3.Normalize(inNormal); - m_Distance = -Vector3.Dot(m_Normal, inPoint); - } - - // Creates a plane. - public Plane(Vector3 inNormal, float d) - { - m_Normal = Vector3.Normalize(inNormal); - m_Distance = d; - } - - // Creates a plane. - public Plane(Vector3 a, Vector3 b, Vector3 c) - { - m_Normal = Vector3.Normalize(Vector3.Cross(b - a, c - a)); - m_Distance = -Vector3.Dot(m_Normal, a); - } - - // Sets a plane using a point that lies within it plus a normal to orient it (note that the normal must be a normalized vector). - public void SetNormalAndPosition(Vector3 inNormal, Vector3 inPoint) - { - m_Normal = Vector3.Normalize(inNormal); - m_Distance = -Vector3.Dot(inNormal, inPoint); - } - - // Sets a plane using three points that lie within it. The points go around clockwise as you look down on the top surface of the plane. - public void Set3Points(Vector3 a, Vector3 b, Vector3 c) - { - m_Normal = Vector3.Normalize(Vector3.Cross(b - a, c - a)); - m_Distance = -Vector3.Dot(m_Normal, a); - } - - // Make the plane face the opposite direction - public void Flip() { m_Normal = -m_Normal; m_Distance = -m_Distance; } - - // Return a version of the plane that faces the opposite direction - public Plane flipped { get { return new Plane(-m_Normal, -m_Distance); } } - - // Translates the plane into a given direction - public void Translate(Vector3 translation) { m_Distance += Vector3.Dot(m_Normal, translation); } - - // Creates a plane that's translated into a given direction - public static Plane Translate(Plane plane, Vector3 translation) { return new Plane(plane.m_Normal, plane.m_Distance += Vector3.Dot(plane.m_Normal, translation)); } - - // Calculates the closest point on the plane. - public Vector3 ClosestPointOnPlane(Vector3 point) - { - var pointToPlaneDistance = Vector3.Dot(m_Normal, point) + m_Distance; - return point - (m_Normal * pointToPlaneDistance); - } - - // Returns a signed distance from plane to point. - public float GetDistanceToPoint(Vector3 point) { return Vector3.Dot(m_Normal, point) + m_Distance; } - - // Is a point on the positive side of the plane? - public bool GetSide(Vector3 point) { return Vector3.Dot(m_Normal, point) + m_Distance > 0.0F; } - - // Are two points on the same side of the plane? - public bool SameSide(Vector3 inPt0, Vector3 inPt1) - { - float d0 = GetDistanceToPoint(inPt0); - float d1 = GetDistanceToPoint(inPt1); - return (d0 > 0.0f && d1 > 0.0f) || - (d0 <= 0.0f && d1 <= 0.0f); - } - - // Intersects a ray with the plane. - public bool Raycast(Ray ray, out float enter) - { - float vdot = Vector3.Dot(ray.direction, m_Normal); - float ndot = -Vector3.Dot(ray.origin, m_Normal) - m_Distance; - - if (Mathf.Approximately(vdot, 0.0f)) - { - enter = 0.0F; - return false; - } - - enter = ndot / vdot; - - return enter > 0.0F; - } - - public override string ToString() - { - return UnityString.Format("(normal:({0:F1}, {1:F1}, {2:F1}), distance:{3:F1})", m_Normal.x, m_Normal.y, m_Normal.z, m_Distance); - } - - public string ToString(string format) - { - return UnityString.Format("(normal:({0}, {1}, {2}), distance:{3})", m_Normal.x.ToString(format), m_Normal.y.ToString(format), m_Normal.z.ToString(format), m_Distance.ToString(format)); - } - } -} diff --git a/Runtime/Export/PropertyName.bindings.cs b/Runtime/Export/PropertyName.bindings.cs deleted file mode 100644 index 9eb6869f2a..0000000000 --- a/Runtime/Export/PropertyName.bindings.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.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Utilities/PropertyName.h")] - class PropertyNameUtils - { - [FreeFunction] - public extern static PropertyName PropertyNameFromString([Unmarshalled] string name); - [FreeFunction] - public extern static string StringFromPropertyName(PropertyName propertyName); - /// - /// Returns the number of conflicts for the given id. - /// Returns 0 if the id is unregistered or it has been mapped to only a single string. - /// Otherwise returns the number of unique strings mapped to the given id. - /// - [FreeFunction] - public extern static int ConflictCountForID(int id); - } -} diff --git a/Runtime/Export/Random.bindings.cs b/Runtime/Export/Random.bindings.cs deleted file mode 100644 index 2d0fa94b5d..0000000000 --- a/Runtime/Export/Random.bindings.cs +++ /dev/null @@ -1,105 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEngineInternal; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - // Class for generating random data. - [NativeHeader("Runtime/Export/Random.bindings.h")] - public sealed partial class Random - { - // Random number generator engine state struct - [System.Serializable] - public struct State - { -#pragma warning disable 0169 - [SerializeField] - private int s0; - [SerializeField] - private int s1; - [SerializeField] - private int s2; - [SerializeField] - private int s3; - } - - // Gets/Sets the seed for the random number generator. - [StaticAccessor("GetScriptingRand()", StaticAccessorType.Dot)] - [Obsolete("Deprecated. Use InitState() function or Random.state property instead.")] - extern public static int seed { get; set; } - - // Initializes the RNG state with a 32 bit seed - [StaticAccessor("GetScriptingRand()", StaticAccessorType.Dot)] - [NativeMethod("SetSeed")] - extern public static void InitState(int seed); - - // Gets/Sets the state of the random number generator. - [StaticAccessor("GetScriptingRand()", StaticAccessorType.Dot)] - extern public static Random.State state { get; set; } - - // Returns a random float number between and /min/ [inclusive] and /max/ [inclusive] (RO). - [FreeFunction] - extern public static float Range(float min, float max); - - // Returns a random integer number between /min/ [inclusive] and /max/ [exclusive] (RO). - public static int Range(int min, int max) { return RandomRangeInt(min, max); } - - [FreeFunction] - extern private static int RandomRangeInt(int min, int max); - - // Returns a random number between 0.0 [inclusive] and 1.0 [inclusive] (RO). - extern public static float value - { - [FreeFunction] - get; - } - - // Returns a random point inside a sphere with radius 1 (RO). - extern public static Vector3 insideUnitSphere - { - [FreeFunction] - get; - } - - // Workaround for gcc/msvc where passing small mono structures by value does not work - [FreeFunction] - extern private static void GetRandomUnitCircle(out Vector2 output); - - // Returns a random point inside a circle with radius 1 (RO). - public static Vector2 insideUnitCircle { get { Vector2 r; GetRandomUnitCircle(out r); return r; } } - - // Returns a random point on the surface of a sphere with radius 1 (RO). - extern public static Vector3 onUnitSphere - { - [FreeFunction] - get; - } - - // Returns a random rotation (RO). - extern public static Quaternion rotation - { - [FreeFunction] - get; - } - - // Returns a random rotation with uniform distribution(RO). - extern public static Quaternion rotationUniform - { - [FreeFunction] - get; - } - - [Obsolete("Use Random.Range instead")] - public static float RandomRange(float min, float max) { return Range(min, max); } - - [Obsolete("Use Random.Range instead")] - public static int RandomRange(int min, int max) { return Range(min, max); } - } -} diff --git a/Runtime/Export/Random.cs b/Runtime/Export/Random.cs deleted file mode 100644 index 9e828b73a3..0000000000 --- a/Runtime/Export/Random.cs +++ /dev/null @@ -1,39 +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 UnityEngine -{ - public sealed partial class Random - { - public static Color ColorHSV() - { - return ColorHSV(0f, 1f, 0f, 1f, 0f, 1f, 1f, 1f); - } - - public static Color ColorHSV(float hueMin, float hueMax) - { - return ColorHSV(hueMin, hueMax, 0f, 1f, 0f, 1f, 1f, 1f); - } - - public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax) - { - return ColorHSV(hueMin, hueMax, saturationMin, saturationMax, 0f, 1f, 1f, 1f); - } - - public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax, float valueMin, float valueMax) - { - return ColorHSV(hueMin, hueMax, saturationMin, saturationMax, valueMin, valueMax, 1f, 1f); - } - - public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax, float valueMin, float valueMax, float alphaMin, float alphaMax) - { - var h = Mathf.Lerp(hueMin, hueMax, Random.value); - var s = Mathf.Lerp(saturationMin, saturationMax, Random.value); - var v = Mathf.Lerp(valueMin, valueMax, Random.value); - var color = Color.HSVToRGB(h, s, v, true); - color.a = Mathf.Lerp(alphaMin, alphaMax, Random.value); - return color; - } - } -} diff --git a/Runtime/Export/RangeInt.cs b/Runtime/Export/RangeInt.cs deleted file mode 100644 index 9ec67addbe..0000000000 --- a/Runtime/Export/RangeInt.cs +++ /dev/null @@ -1,20 +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 UnityEngine -{ - public struct RangeInt - { - public int start; - public int length; - - public int end { get { return start + length; } } - - public RangeInt(int start, int length) - { - this.start = start; - this.length = length; - } - } -} diff --git a/Runtime/Export/Ray.cs b/Runtime/Export/Ray.cs deleted file mode 100644 index 1b15b2f740..0000000000 --- a/Runtime/Export/Ray.cs +++ /dev/null @@ -1,50 +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 UnityEngine -{ - // Representation of rays. - public partial struct Ray - { - private Vector3 m_Origin; - private Vector3 m_Direction; - - // Creates a ray starting at /origin/ along /direction/. - public Ray(Vector3 origin, Vector3 direction) - { - m_Origin = origin; - m_Direction = direction.normalized; - } - - // The origin point of the ray. - public Vector3 origin - { - get { return m_Origin; } - set { m_Origin = value; } - } - - // The direction of the ray. - public Vector3 direction - { - get { return m_Direction; } - set { m_Direction = value.normalized; } - } - - // Returns a point at /distance/ units along the ray. - public Vector3 GetPoint(float distance) - { - return m_Origin + m_Direction * distance; - } - - public override string ToString() - { - return UnityString.Format("Origin: {0}, Dir: {1}", m_Origin, m_Direction); - } - - public string ToString(string format) - { - return UnityString.Format("Origin: {0}, Dir: {1}", m_Origin.ToString(format), m_Direction.ToString(format)); - } - } -} diff --git a/Runtime/Export/Ray2D.cs b/Runtime/Export/Ray2D.cs deleted file mode 100644 index 9131c974f7..0000000000 --- a/Runtime/Export/Ray2D.cs +++ /dev/null @@ -1,46 +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 UnityEngine -{ - // Representation of 2D rays. - public partial struct Ray2D - { - private Vector2 m_Origin; - private Vector2 m_Direction; - - // Creates a ray starting at /origin/ along /direction/. - public Ray2D(Vector2 origin, Vector2 direction) { m_Origin = origin; m_Direction = direction.normalized; } - - // The origin point of the ray. - public Vector2 origin - { - get { return m_Origin; } - set { m_Origin = value; } - } - - // The direction of the ray. - public Vector2 direction - { - get { return m_Direction; } - set { m_Direction = value.normalized; } - } - - // Returns a point at /distance/ units along the ray. - public Vector2 GetPoint(float distance) - { - return m_Origin + m_Direction * distance; - } - - public override string ToString() - { - return UnityString.Format("Origin: {0}, Dir: {1}", m_Origin, m_Direction); - } - - public string ToString(string format) - { - return UnityString.Format("Origin: {0}, Dir: {1}", m_Origin.ToString(format), m_Direction.ToString(format)); - } - } -} diff --git a/Runtime/Export/RenderPipeline/BlendState.cs b/Runtime/Export/RenderPipeline/BlendState.cs deleted file mode 100644 index d44804e307..0000000000 --- a/Runtime/Export/RenderPipeline/BlendState.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 System.Runtime.InteropServices; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match GfxBlendState on C++ side - [StructLayout(LayoutKind.Sequential)] - public struct BlendState - { - public static BlendState Default - { - // Passing a single parameter here to force non-default constructor - get { return new BlendState(false); } - } - - public BlendState(bool separateMRTBlend = false, bool alphaToMask = false) - { - m_BlendState0 = RenderTargetBlendState.Default; - m_BlendState1 = RenderTargetBlendState.Default; - m_BlendState2 = RenderTargetBlendState.Default; - m_BlendState3 = RenderTargetBlendState.Default; - m_BlendState4 = RenderTargetBlendState.Default; - m_BlendState5 = RenderTargetBlendState.Default; - m_BlendState6 = RenderTargetBlendState.Default; - m_BlendState7 = RenderTargetBlendState.Default; - m_SeparateMRTBlendStates = Convert.ToByte(separateMRTBlend); - m_AlphaToMask = Convert.ToByte(alphaToMask); - m_Padding = 0; - } - - public bool separateMRTBlendStates - { - get { return Convert.ToBoolean(m_SeparateMRTBlendStates); } - set { m_SeparateMRTBlendStates = Convert.ToByte(value); } - } - - public bool alphaToMask - { - get { return Convert.ToBoolean(m_AlphaToMask); } - set { m_AlphaToMask = Convert.ToByte(value); } - } - - public RenderTargetBlendState blendState0 - { - get { return m_BlendState0; } - set { m_BlendState0 = value; } - } - - public RenderTargetBlendState blendState1 - { - get { return m_BlendState1; } - set { m_BlendState1 = value; } - } - - public RenderTargetBlendState blendState2 - { - get { return m_BlendState2; } - set { m_BlendState2 = value; } - } - - public RenderTargetBlendState blendState3 - { - get { return m_BlendState3; } - set { m_BlendState3 = value; } - } - - public RenderTargetBlendState blendState4 - { - get { return m_BlendState4; } - set { m_BlendState4 = value; } - } - - public RenderTargetBlendState blendState5 - { - get { return m_BlendState5; } - set { m_BlendState5 = value; } - } - - public RenderTargetBlendState blendState6 - { - get { return m_BlendState6; } - set { m_BlendState6 = value; } - } - - public RenderTargetBlendState blendState7 - { - get { return m_BlendState7; } - set { m_BlendState7 = value; } - } - - RenderTargetBlendState m_BlendState0; - RenderTargetBlendState m_BlendState1; - RenderTargetBlendState m_BlendState2; - RenderTargetBlendState m_BlendState3; - RenderTargetBlendState m_BlendState4; - RenderTargetBlendState m_BlendState5; - RenderTargetBlendState m_BlendState6; - RenderTargetBlendState m_BlendState7; - byte m_SeparateMRTBlendStates; - byte m_AlphaToMask; - short m_Padding; - } -} diff --git a/Runtime/Export/RenderPipeline/DepthState.cs b/Runtime/Export/RenderPipeline/DepthState.cs deleted file mode 100644 index 34a8550488..0000000000 --- a/Runtime/Export/RenderPipeline/DepthState.cs +++ /dev/null @@ -1,44 +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.Runtime.InteropServices; -using UnityEngine.Rendering; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match GfxDepthState on C++ side - [StructLayout(LayoutKind.Sequential)] - public struct DepthState - { - public static DepthState Default - { - // Passing a single parameter here to force non-default constructor - get { return new DepthState(true); } - } - - public DepthState( - bool writeEnabled = true, - CompareFunction compareFunction = CompareFunction.Less) - { - m_WriteEnabled = Convert.ToByte(writeEnabled); - m_CompareFunction = (sbyte)compareFunction; - } - - public bool writeEnabled - { - get { return Convert.ToBoolean(m_WriteEnabled); } - set { m_WriteEnabled = Convert.ToByte(value); } - } - - public CompareFunction compareFunction - { - get { return (CompareFunction)m_CompareFunction; } - set { m_CompareFunction = (sbyte)value; } - } - - byte m_WriteEnabled; - sbyte m_CompareFunction; - } -} diff --git a/Runtime/Export/RenderPipeline/DrawRendererFlags.cs b/Runtime/Export/RenderPipeline/DrawRendererFlags.cs deleted file mode 100644 index fa874a0e27..0000000000 --- a/Runtime/Export/RenderPipeline/DrawRendererFlags.cs +++ /dev/null @@ -1,16 +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 UnityEngine.Experimental.Rendering -{ - [Flags] - public enum DrawRendererFlags - { - None = 0, - EnableDynamicBatching = (1 << 0), - EnableInstancing = (1 << 1), - } -} diff --git a/Runtime/Export/RenderPipeline/DrawShadowsSettings.cs b/Runtime/Export/RenderPipeline/DrawShadowsSettings.cs deleted file mode 100644 index 6d58772427..0000000000 --- a/Runtime/Export/RenderPipeline/DrawShadowsSettings.cs +++ /dev/null @@ -1,34 +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.Runtime.InteropServices; -using UnityEngine.Scripting; - -namespace UnityEngine.Experimental.Rendering -{ - [UsedByNativeCode] - [StructLayout(LayoutKind.Sequential)] - public unsafe struct DrawShadowsSettings - { -#pragma warning disable 414 - private IntPtr _cullResults; -#pragma warning restore 414 - public int lightIndex; - public ShadowSplitData splitData; - - public CullResults cullResults - { - set { _cullResults = value.cullResults; } - } - - public DrawShadowsSettings(CullResults cullResults, int lightIndex) - { - _cullResults = cullResults.cullResults; - this.lightIndex = lightIndex; - this.splitData.cullingPlaneCount = 0; - this.splitData.cullingSphere = Vector4.zero; - } - } -} diff --git a/Runtime/Export/RenderPipeline/FilterResults.cs b/Runtime/Export/RenderPipeline/FilterResults.cs deleted file mode 100644 index d356133aa4..0000000000 --- a/Runtime/Export/RenderPipeline/FilterResults.cs +++ /dev/null @@ -1,17 +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.Runtime.InteropServices; - -namespace UnityEngine.Experimental.Rendering -{ - [StructLayout(LayoutKind.Sequential)] - public struct FilterResults - { -#pragma warning disable 414 - internal IntPtr m_CullResults; -#pragma warning restore 414 - } -} diff --git a/Runtime/Export/RenderPipeline/IRenderPipeline.cs b/Runtime/Export/RenderPipeline/IRenderPipeline.cs deleted file mode 100644 index 009c7a09b6..0000000000 --- a/Runtime/Export/RenderPipeline/IRenderPipeline.cs +++ /dev/null @@ -1,15 +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 UnityEngine.Experimental.Rendering -{ - public interface IRenderPipeline : IDisposable - { - bool disposed { get; } - - void Render(ScriptableRenderContext renderContext, Camera[] cameras); - } -} diff --git a/Runtime/Export/RenderPipeline/IRenderPipelineAsset.cs b/Runtime/Export/RenderPipeline/IRenderPipelineAsset.cs deleted file mode 100644 index 4221c97e94..0000000000 --- a/Runtime/Export/RenderPipeline/IRenderPipelineAsset.cs +++ /dev/null @@ -1,15 +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 UnityEngine.Experimental.Rendering -{ - public interface IRenderPipelineAsset - { - void DestroyCreatedInstances(); - - IRenderPipeline CreatePipeline(); - - int GetTerrainBrushPassIndex(); - } -} diff --git a/Runtime/Export/RenderPipeline/LODParameters.cs b/Runtime/Export/RenderPipeline/LODParameters.cs deleted file mode 100644 index 9185fa0bd9..0000000000 --- a/Runtime/Export/RenderPipeline/LODParameters.cs +++ /dev/null @@ -1,50 +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.Runtime.InteropServices; - -namespace UnityEngine.Experimental.Rendering -{ - [StructLayout(LayoutKind.Sequential)] - public struct LODParameters - { - // has to be int for marshaling - private int m_IsOrthographic; - private Vector3 m_CameraPosition; - private float m_FieldOfView; - private float m_OrthoSize; - private int m_CameraPixelHeight; - - public bool isOrthographic - { - get { return Convert.ToBoolean(m_IsOrthographic); } - set { m_IsOrthographic = Convert.ToInt32(value); } - } - - public Vector3 cameraPosition - { - get { return m_CameraPosition; } - set { m_CameraPosition = value; } - } - - public float fieldOfView - { - get { return m_FieldOfView; } - set { m_FieldOfView = value; } - } - - public float orthoSize - { - get { return m_OrthoSize; } - set { m_OrthoSize = value; } - } - - public int cameraPixelHeight - { - get { return m_CameraPixelHeight; } - set { m_CameraPixelHeight = value; } - } - } -} diff --git a/Runtime/Export/RenderPipeline/ReflectionProbeSortOptions.cs b/Runtime/Export/RenderPipeline/ReflectionProbeSortOptions.cs deleted file mode 100644 index d5a4abaf0c..0000000000 --- a/Runtime/Export/RenderPipeline/ReflectionProbeSortOptions.cs +++ /dev/null @@ -1,14 +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 UnityEngine.Experimental.Rendering -{ - public enum ReflectionProbeSortOptions - { - None, - Importance, - Size, - ImportanceThenSize - } -} diff --git a/Runtime/Export/RenderPipeline/RenderQueueRange.cs b/Runtime/Export/RenderPipeline/RenderQueueRange.cs deleted file mode 100644 index 500ca85bd9..0000000000 --- a/Runtime/Export/RenderPipeline/RenderQueueRange.cs +++ /dev/null @@ -1,30 +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.Runtime.InteropServices; - -namespace UnityEngine.Experimental.Rendering -{ - [StructLayout(LayoutKind.Sequential)] - public struct RenderQueueRange - { - public int min; - public int max; - - public static RenderQueueRange all - { - get { return new RenderQueueRange { min = 0, max = 5000 }; } - } - - public static RenderQueueRange opaque - { - get { return new RenderQueueRange { min = 0, max = (int)UnityEngine.Rendering.RenderQueue.GeometryLast }; } - } - - public static RenderQueueRange transparent - { - get { return new RenderQueueRange { min = (int)UnityEngine.Rendering.RenderQueue.GeometryLast + 1, max = 5000 }; } - } - } -} diff --git a/Runtime/Export/RenderPipeline/RenderStateBlock.cs b/Runtime/Export/RenderPipeline/RenderStateBlock.cs deleted file mode 100644 index c7f9917df4..0000000000 --- a/Runtime/Export/RenderPipeline/RenderStateBlock.cs +++ /dev/null @@ -1,67 +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.Runtime.InteropServices; -using UnityEngine.Rendering; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match RenderStateBlock on C++ side - [StructLayout(LayoutKind.Sequential)] - public struct RenderStateBlock - { - public RenderStateBlock(RenderStateMask mask) - { - m_BlendState = BlendState.Default; - m_RasterState = RasterState.Default; - m_DepthState = DepthState.Default; - m_StencilState = StencilState.Default; - m_StencilReference = 0; - m_Mask = mask; - } - - public BlendState blendState - { - get { return m_BlendState; } - set { m_BlendState = value; } - } - - public RasterState rasterState - { - get { return m_RasterState; } - set { m_RasterState = value; } - } - - public DepthState depthState - { - get { return m_DepthState; } - set { m_DepthState = value; } - } - - public StencilState stencilState - { - get { return m_StencilState; } - set { m_StencilState = value; } - } - - public int stencilReference - { - get { return m_StencilReference; } - set { m_StencilReference = value; } - } - - public RenderStateMask mask - { - get { return m_Mask; } - set { m_Mask = value; } - } - - BlendState m_BlendState; - RasterState m_RasterState; - DepthState m_DepthState; - StencilState m_StencilState; - int m_StencilReference; - RenderStateMask m_Mask; - } -} diff --git a/Runtime/Export/RenderPipeline/RenderStateMapping.cs b/Runtime/Export/RenderPipeline/RenderStateMapping.cs deleted file mode 100644 index eb52cf3ed5..0000000000 --- a/Runtime/Export/RenderPipeline/RenderStateMapping.cs +++ /dev/null @@ -1,36 +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.Runtime.InteropServices; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match RenderStateMapping on C++ side - [StructLayout(LayoutKind.Sequential)] - public struct RenderStateMapping - { - public RenderStateMapping(string renderType, RenderStateBlock stateBlock) - { - m_RenderTypeID = Shader.TagToID(renderType); - m_StateBlock = stateBlock; - } - - public RenderStateMapping(RenderStateBlock stateBlock) : this(null, stateBlock) {} - - public string renderType - { - get { return Shader.IDToTag(m_RenderTypeID); } - set { m_RenderTypeID = Shader.TagToID(value); } - } - - public RenderStateBlock stateBlock - { - get { return m_StateBlock; } - set { m_StateBlock = value; } - } - - int m_RenderTypeID; - RenderStateBlock m_StateBlock; - } -} diff --git a/Runtime/Export/RenderPipeline/RenderStateMask.cs b/Runtime/Export/RenderPipeline/RenderStateMask.cs deleted file mode 100644 index caee6fbb2c..0000000000 --- a/Runtime/Export/RenderPipeline/RenderStateMask.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 System.Runtime.InteropServices; -using UnityEngine.Rendering; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match RenderStateMask on C++ side - [Flags] - public enum RenderStateMask - { - Nothing = 0, - Blend = 1, - Raster = 2, - Depth = 4, - Stencil = 8, - Everything = 15 - } -} diff --git a/Runtime/Export/RenderPipeline/RenderTargetBlendState.cs b/Runtime/Export/RenderPipeline/RenderTargetBlendState.cs deleted file mode 100644 index d09e255db1..0000000000 --- a/Runtime/Export/RenderPipeline/RenderTargetBlendState.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.Runtime.InteropServices; -using UnityEngine.Rendering; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match GfxRenderTargetBlendState on C++ side - [StructLayout(LayoutKind.Sequential)] - public struct RenderTargetBlendState - { - public static RenderTargetBlendState Default - { - // Passing a single parameter here to force non-default constructor - get { return new RenderTargetBlendState(ColorWriteMask.All); } - } - - public RenderTargetBlendState( - ColorWriteMask writeMask = ColorWriteMask.All, - BlendMode sourceColorBlendMode = BlendMode.One, - BlendMode destinationColorBlendMode = BlendMode.Zero, - BlendMode sourceAlphaBlendMode = BlendMode.One, - BlendMode destinationAlphaBlendMode = BlendMode.Zero, - BlendOp colorBlendOperation = BlendOp.Add, - BlendOp alphaBlendOperation = BlendOp.Add) - { - m_WriteMask = (byte)writeMask; - m_SourceColorBlendMode = (byte)sourceColorBlendMode; - m_DestinationColorBlendMode = (byte)destinationColorBlendMode; - m_SourceAlphaBlendMode = (byte)sourceAlphaBlendMode; - m_DestinationAlphaBlendMode = (byte)destinationAlphaBlendMode; - m_ColorBlendOperation = (byte)colorBlendOperation; - m_AlphaBlendOperation = (byte)alphaBlendOperation; - m_Padding = 0; - } - - public ColorWriteMask writeMask - { - get { return (ColorWriteMask)m_WriteMask; } - set { m_WriteMask = (byte)value; } - } - - public BlendMode sourceColorBlendMode - { - get { return (BlendMode)m_SourceColorBlendMode; } - set { m_SourceColorBlendMode = (byte)value; } - } - - public BlendMode destinationColorBlendMode - { - get { return (BlendMode)m_DestinationColorBlendMode; } - set { m_DestinationColorBlendMode = (byte)value; } - } - - public BlendMode sourceAlphaBlendMode - { - get { return (BlendMode)m_SourceAlphaBlendMode; } - set { m_SourceAlphaBlendMode = (byte)value; } - } - - public BlendMode destinationAlphaBlendMode - { - get { return (BlendMode)m_DestinationAlphaBlendMode; } - set { m_DestinationAlphaBlendMode = (byte)value; } - } - - public BlendOp colorBlendOperation - { - get { return (BlendOp)m_ColorBlendOperation; } - set { m_ColorBlendOperation = (byte)value; } - } - - public BlendOp alphaBlendOperation - { - get { return (BlendOp)m_AlphaBlendOperation; } - set { m_AlphaBlendOperation = (byte)value; } - } - - byte m_WriteMask; - byte m_SourceColorBlendMode; - byte m_DestinationColorBlendMode; - byte m_SourceAlphaBlendMode; - byte m_DestinationAlphaBlendMode; - byte m_ColorBlendOperation; - byte m_AlphaBlendOperation; - byte m_Padding; - } -} diff --git a/Runtime/Export/RenderPipeline/RendererConfiguration.cs b/Runtime/Export/RenderPipeline/RendererConfiguration.cs deleted file mode 100644 index ab3c170fc3..0000000000 --- a/Runtime/Export/RenderPipeline/RendererConfiguration.cs +++ /dev/null @@ -1,25 +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 UnityEngine.Experimental.Rendering -{ - [Flags] - public enum RendererConfiguration - { - None = 0, - PerObjectLightProbe = (1 << 0), - PerObjectReflectionProbes = (1 << 1), - PerObjectLightProbeProxyVolume = (1 << 2), - PerObjectLightmaps = (1 << 3), - ProvideLightIndices = (1 << 4), - PerObjectMotionVectors = (1 << 5), - PerObjectLightIndices8 = (1 << 6), - ProvideReflectionProbeIndices = (1 << 7), - PerObjectOcclusionProbe = (1 << 8), - PerObjectOcclusionProbeProxyVolume = (1 << 9), - PerObjectShadowMask = (1 << 10), - } -} diff --git a/Runtime/Export/RenderPipeline/ScriptableRenderContext.cs b/Runtime/Export/RenderPipeline/ScriptableRenderContext.cs deleted file mode 100644 index 9495c876f9..0000000000 --- a/Runtime/Export/RenderPipeline/ScriptableRenderContext.cs +++ /dev/null @@ -1,112 +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.Rendering; - -namespace UnityEngine.Experimental.Rendering -{ - public partial struct ScriptableRenderContext - { - //@TODO: Would be good if there was some safety - // against keeping hold RenderLoop after destruction - private IntPtr m_Ptr; - - internal ScriptableRenderContext(IntPtr ptr) - { - m_Ptr = ptr; - } - - public void Submit() - { - CheckValid(); - Submit_Internal(); - } - - public void DrawRenderers(FilterResults renderers, ref DrawRendererSettings drawSettings, FilterRenderersSettings filterSettings) - { - CheckValid(); - DrawRenderers_Internal(renderers, ref drawSettings, filterSettings); - } - - public void DrawRenderers(FilterResults renderers, ref DrawRendererSettings drawSettings, FilterRenderersSettings filterSettings, RenderStateBlock stateBlock) - { - CheckValid(); - DrawRenderers_StateBlock_Internal(renderers, ref drawSettings, filterSettings, stateBlock); - } - - public void DrawRenderers(FilterResults renderers, ref DrawRendererSettings drawSettings, FilterRenderersSettings filterSettings, List stateMap) - { - CheckValid(); - DrawRenderers_StateMap_Internal(renderers, ref drawSettings, filterSettings, NoAllocHelpers.ExtractArrayFromList(stateMap), stateMap.Count); - } - - public void DrawShadows(ref DrawShadowsSettings settings) - { - CheckValid(); - DrawShadows_Internal(ref settings); - } - - public void ExecuteCommandBuffer(CommandBuffer commandBuffer) - { - if (commandBuffer == null) - throw new ArgumentNullException("commandBuffer"); - - CheckValid(); - ExecuteCommandBuffer_Internal(commandBuffer); - } - - public void ExecuteCommandBufferAsync(CommandBuffer commandBuffer, ComputeQueueType queueType) - { - if (commandBuffer == null) - throw new ArgumentNullException("commandBuffer"); - - CheckValid(); - ExecuteCommandBufferAsync_Internal(commandBuffer, queueType); - } - - public void SetupCameraProperties(Camera camera) - { - CheckValid(); - SetupCameraProperties_Internal(camera, false); - } - - public void SetupCameraProperties(Camera camera, bool stereoSetup) - { - CheckValid(); - SetupCameraProperties_Internal(camera, stereoSetup); - } - - public void StereoEndRender(Camera camera) - { - CheckValid(); - StereoEndRender_Internal(camera); - } - - public void StartMultiEye(Camera camera) - { - CheckValid(); - StartMultiEye_Internal(camera); - } - - public void StopMultiEye(Camera camera) - { - CheckValid(); - StopMultiEye_Internal(camera); - } - - public void DrawSkybox(Camera camera) - { - CheckValid(); - DrawSkybox_Internal(camera); - } - - internal void CheckValid() - { - if (m_Ptr.ToInt64() == 0) - throw new ArgumentException("Invalid ScriptableRenderContext. This can be caused by allocating a context in user code."); - } - } -} diff --git a/Runtime/Export/RenderPipeline/StencilState.cs b/Runtime/Export/RenderPipeline/StencilState.cs deleted file mode 100644 index 04a4e8d14c..0000000000 --- a/Runtime/Export/RenderPipeline/StencilState.cs +++ /dev/null @@ -1,173 +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.Runtime.InteropServices; -using UnityEngine.Rendering; - -namespace UnityEngine.Experimental.Rendering -{ - // Must match GfxStencilState on C++ side - [StructLayout(LayoutKind.Sequential)] - public struct StencilState - { - public static StencilState Default - { - // Passing a single parameter here to force non-default constructor - get { return new StencilState(false); } - } - - public StencilState( - bool enabled = false, - byte readMask = 255, - byte writeMask = 255, - CompareFunction compareFunction = CompareFunction.Always, - StencilOp passOperation = StencilOp.Keep, - StencilOp failOperation = StencilOp.Keep, - StencilOp zFailOperation = StencilOp.Keep) - : this(enabled, readMask, writeMask, compareFunction, passOperation, failOperation, zFailOperation, compareFunction, passOperation, failOperation, zFailOperation) {} - - public StencilState( - bool enabled, - byte readMask, - byte writeMask, - CompareFunction compareFunctionFront, - StencilOp passOperationFront, - StencilOp failOperationFront, - StencilOp zFailOperationFront, - CompareFunction compareFunctionBack, - StencilOp passOperationBack, - StencilOp failOperationBack, - StencilOp zFailOperationBack) - { - m_Enabled = Convert.ToByte(enabled); - m_ReadMask = readMask; - m_WriteMask = writeMask; - m_Padding = 0; - m_CompareFunctionFront = (byte)compareFunctionFront; - m_PassOperationFront = (byte)passOperationFront; - m_FailOperationFront = (byte)failOperationFront; - m_ZFailOperationFront = (byte)zFailOperationFront; - m_CompareFunctionBack = (byte)compareFunctionBack; - m_PassOperationBack = (byte)passOperationBack; - m_FailOperationBack = (byte)failOperationBack; - m_ZFailOperationBack = (byte)zFailOperationBack; - } - - public bool enabled - { - get { return Convert.ToBoolean(m_Enabled); } - set { m_Enabled = Convert.ToByte(value); } - } - - public byte readMask - { - get { return m_ReadMask; } - set { m_ReadMask = value; } - } - - public byte writeMask - { - get { return m_WriteMask; } - set { m_WriteMask = value; } - } - - public CompareFunction compareFunction - { - set - { - compareFunctionFront = value; - compareFunctionBack = value; - } - } - - public StencilOp passOperation - { - set - { - passOperationFront = value; - passOperationBack = value; - } - } - - public StencilOp failOperation - { - set - { - failOperationFront = value; - failOperationBack = value; - } - } - - public StencilOp zFailOperation - { - set - { - zFailOperationFront = value; - zFailOperationBack = value; - } - } - - public CompareFunction compareFunctionFront - { - get { return (CompareFunction)m_CompareFunctionFront; } - set { m_CompareFunctionFront = (byte)value; } - } - - public StencilOp passOperationFront - { - get { return (StencilOp)m_PassOperationFront; } - set { m_PassOperationFront = (byte)value; } - } - - public StencilOp failOperationFront - { - get { return (StencilOp)m_FailOperationFront; } - set { m_FailOperationFront = (byte)value; } - } - - public StencilOp zFailOperationFront - { - get { return (StencilOp)m_ZFailOperationFront; } - set { m_ZFailOperationFront = (byte)value; } - } - - public CompareFunction compareFunctionBack - { - get { return (CompareFunction)m_CompareFunctionBack; } - set { m_CompareFunctionBack = (byte)value; } - } - - public StencilOp passOperationBack - { - get { return (StencilOp)m_PassOperationBack; } - set { m_PassOperationBack = (byte)value; } - } - - public StencilOp failOperationBack - { - get { return (StencilOp)m_FailOperationBack; } - set { m_FailOperationBack = (byte)value; } - } - - public StencilOp zFailOperationBack - { - get { return (StencilOp)m_ZFailOperationBack; } - set { m_ZFailOperationBack = (byte)value; } - } - - byte m_Enabled; - byte m_ReadMask; - byte m_WriteMask; - byte m_Padding; - byte m_CompareFunctionFront; - byte m_PassOperationFront; - byte m_FailOperationFront; - byte m_ZFailOperationFront; - byte m_CompareFunctionBack; - byte m_PassOperationBack; - byte m_FailOperationBack; - byte m_ZFailOperationBack; - } -} diff --git a/Runtime/Export/RenderPipeline/VisibleLightFlags.cs b/Runtime/Export/RenderPipeline/VisibleLightFlags.cs deleted file mode 100644 index fe6b023f79..0000000000 --- a/Runtime/Export/RenderPipeline/VisibleLightFlags.cs +++ /dev/null @@ -1,16 +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 UnityEngine.Experimental.Rendering -{ - [Flags] - public enum VisibleLightFlags - { - None = 0, - IntersectsNearPlane = 1, - IntersectsFarPlane = 2, - } -} diff --git a/Runtime/Export/RuntimeInitializeOnLoadAttribute.cs b/Runtime/Export/RuntimeInitializeOnLoadAttribute.cs deleted file mode 100644 index 65ec01fe4f..0000000000 --- a/Runtime/Export/RuntimeInitializeOnLoadAttribute.cs +++ /dev/null @@ -1,23 +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 UnityEngine -{ - public enum RuntimeInitializeLoadType - { - AfterSceneLoad = 0, - BeforeSceneLoad - }; - - [System.AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - public class RuntimeInitializeOnLoadMethodAttribute : Scripting.PreserveAttribute - { - public RuntimeInitializeOnLoadMethodAttribute() { this.loadType = RuntimeInitializeLoadType.AfterSceneLoad; } - public RuntimeInitializeOnLoadMethodAttribute(RuntimeInitializeLoadType loadType) { this.loadType = loadType; } - - public RuntimeInitializeLoadType loadType { get; private set; } - } -} diff --git a/Runtime/Export/ScriptableRenderLoop/RenderPass.cs b/Runtime/Export/ScriptableRenderLoop/RenderPass.cs deleted file mode 100644 index 542521dc2b..0000000000 --- a/Runtime/Export/ScriptableRenderLoop/RenderPass.cs +++ /dev/null @@ -1,58 +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.Rendering; -using System; - -namespace UnityEngine.Experimental.Rendering -{ - public class RenderPass : System.IDisposable - { - public class SubPass : System.IDisposable - { - public SubPass(RenderPass renderPass, RenderPassAttachment[] colors, RenderPassAttachment[] inputs, bool readOnlyDepth = false) - { - ScriptableRenderContext.BeginSubPassInternal(renderPass.context.Internal_GetPtr(), - colors != null ? colors : new RenderPassAttachment[] {}, - inputs != null ? inputs : new RenderPassAttachment[] {}, - readOnlyDepth); - } - - public void Dispose() - { - // Nothing to do here - } - } - - public RenderPassAttachment[] colorAttachments { get; private set; } - public RenderPassAttachment depthAttachment { get; private set; } - - // Render image width in pixels - public int width { get; private set; } - // Render image height in pixels - public int height { get; private set; } - - // Number of MSAA samples, or 1 if no AA - public int sampleCount { get; private set; } - - public UnityEngine.Experimental.Rendering.ScriptableRenderContext context { get; private set; } - - public void Dispose() - { - ScriptableRenderContext.EndRenderPassInternal(context.Internal_GetPtr()); - } - - public RenderPass(ScriptableRenderContext ctx, int w, int h, int samples, RenderPassAttachment[] colors, RenderPassAttachment depth = null) - { - width = w; - height = h; - sampleCount = samples; - colorAttachments = colors; - depthAttachment = depth; - context = ctx; - - ScriptableRenderContext.BeginRenderPassInternal(ctx.Internal_GetPtr(), w, h, samples, colors, depth); - } - } -} diff --git a/Runtime/Export/ScriptableRenderLoop/RenderPassAttachment.bindings.cs b/Runtime/Export/ScriptableRenderLoop/RenderPassAttachment.bindings.cs deleted file mode 100644 index 09f46d140d..0000000000 --- a/Runtime/Export/ScriptableRenderLoop/RenderPassAttachment.bindings.cs +++ /dev/null @@ -1,89 +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.Bindings; -using UnityEngine.Rendering; -using System; - -namespace UnityEngine.Experimental.Rendering -{ - [NativeType("Runtime/Graphics/ScriptableRenderLoop/ScriptableRenderContext.h")] - public class RenderPassAttachment : UnityEngine.Object - { - // The Load action to use when this attachment is accessed for the first time in this renderpass - extern public RenderBufferLoadAction loadAction { get; private set; } - // Store action to use when the the last subpass that accesses this attachment is done. - // Note that this isn't set by the constructor, but rather by calling SetStoreTarget/SetResolveTarget - extern public RenderBufferStoreAction storeAction { get; private set; } - // The format of this attachment - extern public RenderTextureFormat format { get; private set; } - - // The render texture where the load/store operations take place - extern private RenderTargetIdentifier loadStoreTarget { get; set; } - // The render texture to resolve the attachment into at the end of the renderpass - extern private RenderTargetIdentifier resolveTarget { get; set; } - - // If loadAction is set to clear and this is a color surface, clear it to this color - extern public Color clearColor { get; private set; } - // If loadAction is set to clear and this is a depth surface, clear to this value - extern public float clearDepth { get; private set; } - // If loadAction is set to clear and this is a depth+stencil surface, clear to this value - extern public uint clearStencil { get; private set; } - - // Bind a backing surface for this attachment. If none is set, the attachment is transient / memoryless (where supported) - // or a temporary surface that's released at the end of the renderpass. - // If loadExistingContents is true, the current contents of the surface is loaded as the initial pixel values for the attachment, - // otherwise the initial values are undefined (with the expectation that the renderpass will render to every pixel on the screen) - // If storeResults is true, the attachment contents at the end of the renderpass are stored to the surface, - // otherwise the contents of the surface are undefined after the end of the renderpass. - public void BindSurface(RenderTargetIdentifier tgt, bool loadExistingContents, bool storeResults) - { - loadStoreTarget = tgt; - if (loadExistingContents && loadAction != RenderBufferLoadAction.Clear) - loadAction = RenderBufferLoadAction.Load; - if (storeResults) - { - if (storeAction == RenderBufferStoreAction.StoreAndResolve || storeAction == RenderBufferStoreAction.Resolve) - storeAction = RenderBufferStoreAction.StoreAndResolve; - else - storeAction = RenderBufferStoreAction.Store; - } - } - - // If the renderpass has MSAA enabled, AA-resolve this attachment into the given render target. - public void BindResolveSurface(RenderTargetIdentifier tgt) - { - resolveTarget = tgt; - if (storeAction == RenderBufferStoreAction.StoreAndResolve || storeAction == RenderBufferStoreAction.Store) - storeAction = RenderBufferStoreAction.StoreAndResolve; - else - storeAction = RenderBufferStoreAction.Resolve; - } - - // At the beginning of the renderpass, clear this attachment with the given clear color (or depth/stencil) - public void Clear(Color clearCol, float clearDep = 1.0f, uint clearStenc = 0) - { - clearColor = clearCol; - clearDepth = clearDep; - clearStencil = clearStenc; - loadAction = RenderBufferLoadAction.Clear; - } - - public RenderPassAttachment(RenderTextureFormat fmt) - { - Internal_CreateAttachment(this); - - loadAction = RenderBufferLoadAction.DontCare; - storeAction = RenderBufferStoreAction.DontCare; - format = fmt; - loadStoreTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.None); - resolveTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.None); - clearColor = new Color(0.0f, 0.0f, 0.0f, 0.0f); - clearDepth = 1.0f; - } - - [NativeMethod(Name = "RenderPassAttachment::Internal_CreateAttachment", IsFreeFunction = true)] - extern public static void Internal_CreateAttachment([Writable] RenderPassAttachment self); - } -} diff --git a/Runtime/Export/Scripting/APIUpdating/UpdatedFromAttribute.cs b/Runtime/Export/Scripting/APIUpdating/UpdatedFromAttribute.cs deleted file mode 100644 index 0119f62a6f..0000000000 --- a/Runtime/Export/Scripting/APIUpdating/UpdatedFromAttribute.cs +++ /dev/null @@ -1,25 +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 UnityEngine.Scripting.APIUpdating -{ - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Interface)] - public class MovedFromAttribute : Attribute - { - public MovedFromAttribute(string sourceNamespace) : this(sourceNamespace, false) - { - } - - public MovedFromAttribute(string sourceNamespace, bool isInDifferentAssembly) - { - Namespace = sourceNamespace; - IsInDifferentAssembly = isInDifferentAssembly; - } - - public string Namespace { get; private set; } - public bool IsInDifferentAssembly { get; private set; } - } -} diff --git a/Runtime/Export/Scripting/GarbageCollector.bindings.cs b/Runtime/Export/Scripting/GarbageCollector.bindings.cs new file mode 100644 index 0000000000..3ed1d0271e --- /dev/null +++ b/Runtime/Export/Scripting/GarbageCollector.bindings.cs @@ -0,0 +1,46 @@ +// 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.Bindings; + +namespace UnityEngine.Scripting +{ + [NativeHeader("Runtime/Scripting/GarbageCollector.h")] + [VisibleToOtherModules] + public static class GarbageCollector + { + public enum Mode + { + Disabled = 0, + Enabled = 1, + } + + public static Action GCModeChanged; + + public static Mode GCMode + { + get + { + return GetMode(); + } + + set + { + if (value == GetMode()) + return; + + SetMode(value); + + if (GCModeChanged != null) + GCModeChanged(value); + } + } + + [NativeThrows] + extern static void SetMode(Mode mode); + [NativeThrows] + extern static Mode GetMode(); + } +} diff --git a/Runtime/Export/Scripting/PreserveAttribute.cs b/Runtime/Export/Scripting/PreserveAttribute.cs deleted file mode 100644 index cdec847607..0000000000 --- a/Runtime/Export/Scripting/PreserveAttribute.cs +++ /dev/null @@ -1,13 +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 UnityEngine.Scripting -{ - [System.AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] - public class PreserveAttribute : System.Attribute - { - } -} diff --git a/Runtime/Export/ScrollWaitDefinitions.cs b/Runtime/Export/ScrollWaitDefinitions.cs deleted file mode 100644 index 699e374ef9..0000000000 --- a/Runtime/Export/ScrollWaitDefinitions.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 UnityEngine -{ - internal static class ScrollWaitDefinitions - { - public const int firstWait = 250; // ms - public const int regularWait = 30; // ms - } -} diff --git a/Runtime/Export/SelectionBaseAttribute.cs b/Runtime/Export/SelectionBaseAttribute.cs deleted file mode 100644 index 596e14f301..0000000000 --- a/Runtime/Export/SelectionBaseAttribute.cs +++ /dev/null @@ -1,13 +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 UnityEngine -{ - [System.AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] - public class SelectionBaseAttribute : Attribute - { - } -} diff --git a/Runtime/Export/Serialization.cs b/Runtime/Export/Serialization.cs deleted file mode 100644 index c2852d50b7..0000000000 --- a/Runtime/Export/Serialization.cs +++ /dev/null @@ -1,39 +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 scm = System.ComponentModel; -using uei = UnityEngine.Internal; -using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute = UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -namespace UnityEngine -{ - [System.Obsolete("Use SerializeField on the private variables that you want to be serialized instead")] - [RequiredByNativeCode] - public sealed partial class SerializePrivateVariables : Attribute - { - } - - [RequiredByNativeCode] - public sealed partial class SerializeField : Attribute - { - } - - [RequiredByNativeCode] - [AttributeUsage(AttributeTargets.Class)] - public sealed class PreferBinarySerialization : Attribute - { - } - - [RequiredByNativeCode] - public interface ISerializationCallbackReceiver - { - [RequiredByNativeCode] - void OnBeforeSerialize(); - - [RequiredByNativeCode] - void OnAfterDeserialize(); - } -} diff --git a/Runtime/Export/Serialization/FormerlySerializedAsAttribute.cs b/Runtime/Export/Serialization/FormerlySerializedAsAttribute.cs deleted file mode 100644 index 6d5913220b..0000000000 --- a/Runtime/Export/Serialization/FormerlySerializedAsAttribute.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.Scripting; - -namespace UnityEngine.Serialization -{ - [AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = false)] - [RequiredByNativeCode] - public class FormerlySerializedAsAttribute : Attribute - { - private string m_oldName; - public FormerlySerializedAsAttribute(string oldName) - { - m_oldName = oldName; - } - - public string oldName { get { return m_oldName; } } - } -} diff --git a/Runtime/Export/Serialization/IPPtrRemapper.cs b/Runtime/Export/Serialization/IPPtrRemapper.cs deleted file mode 100644 index 5aef2ce4fa..0000000000 --- a/Runtime/Export/Serialization/IPPtrRemapper.cs +++ /dev/null @@ -1,7 +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 UnityEngine -{ -} diff --git a/Runtime/Export/Serialization/ISerializedNamedStateReader.cs b/Runtime/Export/Serialization/ISerializedNamedStateReader.cs deleted file mode 100644 index 21273bf0d4..0000000000 --- a/Runtime/Export/Serialization/ISerializedNamedStateReader.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 - -using System; -using System.Collections.Generic; - -namespace UnityEngine -{ -} diff --git a/Runtime/Export/Serialization/ISerializedNamedStateWriter.cs b/Runtime/Export/Serialization/ISerializedNamedStateWriter.cs deleted file mode 100644 index 21273bf0d4..0000000000 --- a/Runtime/Export/Serialization/ISerializedNamedStateWriter.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 - -using System; -using System.Collections.Generic; - -namespace UnityEngine -{ -} diff --git a/Runtime/Export/Serialization/ISerializedStateReader.cs b/Runtime/Export/Serialization/ISerializedStateReader.cs deleted file mode 100644 index bd6b6bb704..0000000000 --- a/Runtime/Export/Serialization/ISerializedStateReader.cs +++ /dev/null @@ -1,9 +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.Collections.Generic; - -namespace UnityEngine -{ -} diff --git a/Runtime/Export/Serialization/ISerializedStateWriter.cs b/Runtime/Export/Serialization/ISerializedStateWriter.cs deleted file mode 100644 index bd6b6bb704..0000000000 --- a/Runtime/Export/Serialization/ISerializedStateWriter.cs +++ /dev/null @@ -1,9 +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.Collections.Generic; - -namespace UnityEngine -{ -} diff --git a/Runtime/Export/Serialization/IUnitySerializable.cs b/Runtime/Export/Serialization/IUnitySerializable.cs deleted file mode 100644 index adcb8af550..0000000000 --- a/Runtime/Export/Serialization/IUnitySerializable.cs +++ /dev/null @@ -1,11 +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.Scripting; - -namespace UnityEngine -{ - // We always enable it for WinRT because [RequiredByNativeCode] attributes - // must match for all scripting backends -} diff --git a/Runtime/Export/Serialization/SerializedStateReader.cs b/Runtime/Export/Serialization/SerializedStateReader.cs deleted file mode 100644 index 560599aad0..0000000000 --- a/Runtime/Export/Serialization/SerializedStateReader.cs +++ /dev/null @@ -1,9 +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; - -namespace UnityEngine.Serialization -{ -} diff --git a/Runtime/Export/Serialization/SerializedStateWriter.cs b/Runtime/Export/Serialization/SerializedStateWriter.cs deleted file mode 100644 index 560599aad0..0000000000 --- a/Runtime/Export/Serialization/SerializedStateWriter.cs +++ /dev/null @@ -1,9 +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; - -namespace UnityEngine.Serialization -{ -} diff --git a/Runtime/Export/Serialization/UnitySurrogateSelector.cs b/Runtime/Export/Serialization/UnitySurrogateSelector.cs deleted file mode 100644 index 77bb8ec331..0000000000 --- a/Runtime/Export/Serialization/UnitySurrogateSelector.cs +++ /dev/null @@ -1,117 +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.Runtime.Serialization; - -namespace UnityEngine.Serialization -{ - /// - /// Serialization support for and that doesn't rely on reflection - /// of private members in order to be useable under the CoreCLR security model (WebPlayer). - /// - public class UnitySurrogateSelector : ISurrogateSelector - { - public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) - { - if (type.IsGenericType) - { - var genericTypeDefinition = type.GetGenericTypeDefinition(); - if (genericTypeDefinition == typeof(List<>)) - { - selector = this; - return ListSerializationSurrogate.Default; - } - if (genericTypeDefinition == typeof(Dictionary<, >)) - { - selector = this; - var dictSurrogateType = typeof(DictionarySerializationSurrogate<, >).MakeGenericType(type.GetGenericArguments()); - return (ISerializationSurrogate)Activator.CreateInstance(dictSurrogateType); - } - } - - selector = null; - return null; - } - - public void ChainSelector(ISurrogateSelector selector) - { - throw new NotImplementedException(); - } - - public ISurrogateSelector GetNextSelector() - { - throw new NotImplementedException(); - } - } - - /// - /// Serialization support for that doesn't rely on reflection of private members. - /// - class ListSerializationSurrogate : ISerializationSurrogate - { - public static readonly ISerializationSurrogate Default = new ListSerializationSurrogate(); - - public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) - { - var list = (IList)obj; - info.AddValue("_size", list.Count); - info.AddValue("_items", ArrayFromGenericList(list)); - info.AddValue("_version", 0); // required for compatibility with platform deserialization - } - - public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) - { - var list = (IList)Activator.CreateInstance(obj.GetType()); - var size = info.GetInt32("_size"); - if (size == 0) - return list; - - var items = ((IEnumerable)info.GetValue("_items", typeof(IEnumerable))).GetEnumerator(); - for (var i = 0; i < size; ++i) - { - if (!items.MoveNext()) - throw new InvalidOperationException(); - list.Add(items.Current); - } - return list; - } - - private static Array ArrayFromGenericList(IList list) - { - var items = Array.CreateInstance(list.GetType().GetGenericArguments()[0], list.Count); - list.CopyTo(items, 0); - return items; - } - } - - /// - /// Serialization support for that doesn't rely on non public members. - /// - class DictionarySerializationSurrogate : ISerializationSurrogate - { - public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) - { - var dictionary = ((Dictionary)obj); - dictionary.GetObjectData(info, context); - } - - public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) - { - var comparer = (IEqualityComparer)info.GetValue("Comparer", typeof(IEqualityComparer)); - var dictionary = new Dictionary(comparer); - if (info.MemberCount > 3) // KeyValuePairs might not be present if the dictionary was empty - { - var keyValuePairs = - (KeyValuePair[])info.GetValue("KeyValuePairs", typeof(KeyValuePair[])); - if (keyValuePairs != null) - foreach (var kvp in keyValuePairs) - dictionary.Add(kvp.Key, kvp.Value); - } - return dictionary; - } - } -} diff --git a/Runtime/Export/StaticBatching/CombineForStaticBatching.cs b/Runtime/Export/StaticBatching/CombineForStaticBatching.cs deleted file mode 100644 index 42ff36b9aa..0000000000 --- a/Runtime/Export/StaticBatching/CombineForStaticBatching.cs +++ /dev/null @@ -1,265 +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 System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; - -namespace UnityEngine -{ - public sealed partial class StaticBatchingUtility - { - static public void Combine(GameObject staticBatchRoot) - { - InternalStaticBatchingUtility.CombineRoot(staticBatchRoot); - } - - static public void Combine(GameObject[] gos, GameObject staticBatchRoot) - { - InternalStaticBatchingUtility.CombineGameObjects(gos, staticBatchRoot, false); - } - } - - internal class InternalStaticBatchingUtility - { - // assume 16bit indices - const int MaxVerticesInBatch = 64000; // a little bit less than 64K - just in case - const string CombinedMeshPrefix = "Combined Mesh"; - - static public void CombineRoot(UnityEngine.GameObject staticBatchRoot) - { - Combine(staticBatchRoot, false, false); - } - - static public void Combine(UnityEngine.GameObject staticBatchRoot, bool combineOnlyStatic, bool isEditorPostprocessScene) - { - GameObject[] gos = (GameObject[])UnityEngine.Object.FindObjectsOfType(typeof(GameObject)); - - List filteredGos = new List(); - foreach (GameObject go in gos) - { - if (staticBatchRoot != null) - if (!go.transform.IsChildOf(staticBatchRoot.transform)) - continue; - - if (combineOnlyStatic && !go.isStaticBatchable) - continue; - - filteredGos.Add(go); - } - - gos = filteredGos.ToArray(); - - CombineGameObjects(gos, staticBatchRoot, isEditorPostprocessScene); - } - - static public void CombineGameObjects(GameObject[] gos, UnityEngine.GameObject staticBatchRoot, bool isEditorPostprocessScene) - { - Matrix4x4 staticBatchInverseMatrix = Matrix4x4.identity; - Transform staticBatchRootTransform = null; - if (staticBatchRoot) - { - staticBatchInverseMatrix = staticBatchRoot.transform.worldToLocalMatrix; - staticBatchRootTransform = staticBatchRoot.transform; - } - - int batchIndex = 0; - int verticesInBatch = 0; - List meshes = new List(); - - Array.Sort(gos, new SortGO()); - - foreach (GameObject go in gos) - { - MeshFilter filter = go.GetComponent(typeof(MeshFilter)) as MeshFilter; - if (filter == null) - continue; - - Mesh instanceMesh = filter.sharedMesh; - - // reject if has no mesh or (mesh not readable and not called from Editor PostprocessScene.cs) - // Editor is allowed to modify meshes even if they are marked as read-only e.g. Applicatiopn.LoadLevel() called from a script inside the editor player - if (instanceMesh == null || (!isEditorPostprocessScene && !instanceMesh.canAccess)) - continue; - - Renderer renderer = filter.GetComponent(); - - // reject if has not renderer or renderer is disabled - if (renderer == null || !renderer.enabled) - continue; - - // reject if already combined for static batching - if (renderer.staticBatchIndex != 0) - continue; - - Material[] materials = renderer.sharedMaterials; - - // reject if any of the material's shader is using DisableBatching tag - if (materials.Any(m => m != null && m.shader != null && m.shader.disableBatching != DisableBatchingType.False)) - continue; - - int vertexCount = instanceMesh.vertexCount; - // Use same tests as MeshCombiner::IsMeshBatchable to stay consistent with C++ code - if (vertexCount == 0) - continue; - - MeshRenderer meshRenderer = renderer as MeshRenderer; - if ((meshRenderer != null) && (meshRenderer.additionalVertexStreams != null)) - { - if (vertexCount != meshRenderer.additionalVertexStreams.vertexCount) - continue; - } - - // check if we have enough space inside the current batch - if (verticesInBatch + vertexCount > MaxVerticesInBatch) - { - MakeBatch(meshes, staticBatchRootTransform, batchIndex++); - meshes.Clear(); - verticesInBatch = 0; - } - - MeshSubsetCombineUtility.MeshInstance instance = new MeshSubsetCombineUtility.MeshInstance(); - instance.meshInstanceID = instanceMesh.GetInstanceID(); - instance.rendererInstanceID = renderer.GetInstanceID(); - if (meshRenderer != null && meshRenderer.additionalVertexStreams != null) - instance.additionalVertexStreamsMeshInstanceID = meshRenderer.additionalVertexStreams.GetInstanceID(); - - instance.transform = staticBatchInverseMatrix * filter.transform.localToWorldMatrix; - instance.lightmapScaleOffset = renderer.lightmapScaleOffset; - instance.realtimeLightmapScaleOffset = renderer.realtimeLightmapScaleOffset; - - MeshSubsetCombineUtility.MeshContainer mesh = new MeshSubsetCombineUtility.MeshContainer(); - mesh.gameObject = go; - mesh.instance = instance; - mesh.subMeshInstances = new List(); - - //;;Debug.Log("New static mesh (" + go.name + ")verts: " + instanceMesh.vertexCount + - // ", tris: " + instanceMesh.triangles.Length + - // ", materials: " + renderer.sharedMaterials.Length + - // ", subs: " + instanceMesh.subMeshCount - // ); - - meshes.Add(mesh); - - if (materials.Length > instanceMesh.subMeshCount) - { - Debug.LogWarning("Mesh '" + instanceMesh.name + "' has more materials (" + materials.Length + ") than subsets (" + instanceMesh.subMeshCount + ")", renderer); - // extra materials don't have a meaning and it screws the rendering as Unity - // tries to render with those extra materials. - Material[] newMats = new Material[instanceMesh.subMeshCount]; - for (int i = 0; i < instanceMesh.subMeshCount; ++i) - newMats[i] = renderer.sharedMaterials[i]; - renderer.sharedMaterials = newMats; - materials = newMats; - } - - for (int m = 0; m < System.Math.Min(materials.Length, instanceMesh.subMeshCount); ++m) - { - //;;Debug.Log(" new subset : " + m + ", tris " + instanceMesh.GetTriangles(m).Length); - MeshSubsetCombineUtility.SubMeshInstance subMeshInstance = new MeshSubsetCombineUtility.SubMeshInstance(); - subMeshInstance.meshInstanceID = filter.sharedMesh.GetInstanceID(); - subMeshInstance.vertexOffset = verticesInBatch; - subMeshInstance.subMeshIndex = m; - subMeshInstance.gameObjectInstanceID = go.GetInstanceID(); - subMeshInstance.transform = instance.transform; - mesh.subMeshInstances.Add(subMeshInstance); - } - verticesInBatch += instanceMesh.vertexCount; - } - - MakeBatch(meshes, staticBatchRootTransform, batchIndex); - } - - static private void MakeBatch(List meshes, Transform staticBatchRootTransform, int batchIndex) - { - if (meshes.Count < 2) - return; - - List meshInstances = new List(); - List allSubMeshInstances = new List(); - foreach (MeshSubsetCombineUtility.MeshContainer mesh in meshes) - { - meshInstances.Add(mesh.instance); - allSubMeshInstances.AddRange(mesh.subMeshInstances); - } - - string combinedMeshName = CombinedMeshPrefix; - combinedMeshName += " (root: " + ((staticBatchRootTransform != null) ? staticBatchRootTransform.name : "scene") + ")"; - if (batchIndex > 0) - combinedMeshName += " " + (batchIndex + 1); - - Mesh combinedMesh = StaticBatchingHelper.InternalCombineVertices(meshInstances.ToArray(), combinedMeshName); - StaticBatchingHelper.InternalCombineIndices(allSubMeshInstances.ToArray(), combinedMesh); - int totalSubMeshCount = 0; - - foreach (MeshSubsetCombineUtility.MeshContainer mesh in meshes) - { - // Changing the mesh resets the static batch info, so we have to assign sharedMesh first - MeshFilter filter = (MeshFilter)mesh.gameObject.GetComponent(typeof(MeshFilter)); - filter.sharedMesh = combinedMesh; - - int subMeshCount = mesh.subMeshInstances.Count(); - Renderer renderer = mesh.gameObject.GetComponent(); - renderer.SetStaticBatchInfo(totalSubMeshCount, subMeshCount); - renderer.staticBatchRootTransform = staticBatchRootTransform; - - // For some reason if GOs were created dynamically - // then we need to toggle renderer to avoid caching old geometry - renderer.enabled = false; - renderer.enabled = true; - - // Remove the additionalVertexStreamsMesh, all its data has been copied into the combined mesh. - MeshRenderer meshRenderer = renderer as MeshRenderer; - if (meshRenderer != null) - meshRenderer.additionalVertexStreams = null; - - totalSubMeshCount += subMeshCount; - } - } - - internal class SortGO : IComparer - { - int IComparer.Compare(object a, object b) - { - if (a == b) - return 0; - - Renderer aRenderer = GetRenderer(a as GameObject); - Renderer bRenderer = GetRenderer(b as GameObject); - - int compare = GetMaterialId(aRenderer).CompareTo(GetMaterialId(bRenderer)); - if (compare == 0) - compare = GetLightmapIndex(aRenderer).CompareTo(GetLightmapIndex(bRenderer)); - return compare; - } - - static private int GetMaterialId(Renderer renderer) - { - if (renderer == null || renderer.sharedMaterial == null) - return 0; - return renderer.sharedMaterial.GetInstanceID(); - } - - static private int GetLightmapIndex(Renderer renderer) - { - if (renderer == null) - return -1; - return renderer.lightmapIndex; - } - - static private Renderer GetRenderer(GameObject go) - { - if (go == null) - return null; - MeshFilter filter = go.GetComponent(typeof(MeshFilter)) as MeshFilter; - if (filter == null) - return null; - - return filter.GetComponent(); - } - } - } -} // namespace UnityEngine diff --git a/Runtime/Export/StaticBatching/MeshSubsetCombineUtility.cs b/Runtime/Export/StaticBatching/MeshSubsetCombineUtility.cs deleted file mode 100644 index e7b2211a57..0000000000 --- a/Runtime/Export/StaticBatching/MeshSubsetCombineUtility.cs +++ /dev/null @@ -1,38 +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 System.Collections.Generic; - -namespace UnityEngine -{ - internal class MeshSubsetCombineUtility - { - public struct MeshInstance - { - public int meshInstanceID; - public int rendererInstanceID; - public int additionalVertexStreamsMeshInstanceID; - public Matrix4x4 transform; - public Vector4 lightmapScaleOffset; - public Vector4 realtimeLightmapScaleOffset; - } - - public struct SubMeshInstance - { - public int meshInstanceID; - public int vertexOffset; - public int gameObjectInstanceID; - public int subMeshIndex; - public Matrix4x4 transform; - } - - public struct MeshContainer - { - public GameObject gameObject; - public MeshInstance instance; - public List subMeshInstances; - } - } -} // namespace UnityEngine diff --git a/Runtime/Export/SystemClock.cs b/Runtime/Export/SystemClock.cs deleted file mode 100644 index 76f668b322..0000000000 --- a/Runtime/Export/SystemClock.cs +++ /dev/null @@ -1,30 +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.Bindings; - -namespace UnityEngine -{ - [VisibleToOtherModules] - internal class SystemClock - { - static readonly DateTime s_Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - public static DateTime now - { - get { return DateTime.Now; } - } - - public static long ToUnixTimeMilliseconds(DateTime date) - { - return Convert.ToInt64((date.ToUniversalTime() - s_Epoch).TotalMilliseconds); - } - - public static long ToUnixTimeSeconds(DateTime date) - { - return Convert.ToInt64((date.ToUniversalTime() - s_Epoch).TotalSeconds); - } - } -} diff --git a/Runtime/Export/SystemInfo.bindings.cs b/Runtime/Export/SystemInfo.bindings.cs index 6125bb74a1..23fa6dc4ed 100644 --- a/Runtime/Export/SystemInfo.bindings.cs +++ b/Runtime/Export/SystemInfo.bindings.cs @@ -214,6 +214,11 @@ public static bool graphicsMultiThreaded get { return GetGraphicsMultiThreaded(); } } + public static bool hasHiddenSurfaceRemovalOnGPU + { + get { return HasHiddenSurfaceRemovalOnGPU(); } + } + // Are built-in shadows supported? (RO) public static bool supportsShadows { @@ -527,6 +532,9 @@ public static int graphicsPixelFillrate [FreeFunction("ScriptingGraphicsCaps::GetGraphicsMultiThreaded")] static extern bool GetGraphicsMultiThreaded(); + [FreeFunction("ScriptingGraphicsCaps::HasHiddenSurfaceRemovalOnGPU")] + static extern bool HasHiddenSurfaceRemovalOnGPU(); + [FreeFunction("ScriptingGraphicsCaps::SupportsShadows")] static extern bool SupportsShadows(); diff --git a/Runtime/Export/Texture.cs b/Runtime/Export/Texture.cs index 06d0730b91..972e0c25ee 100644 --- a/Runtime/Export/Texture.cs +++ b/Runtime/Export/Texture.cs @@ -739,6 +739,7 @@ public void Apply([uei.DefaultValue("true")] bool updateMipmaps, [uei.DefaultVal public sealed partial class CubemapArray : Texture { + [RequiredByNativeCode] public CubemapArray(int width, int cubemapCount, GraphicsFormat format, TextureCreationFlags flags) { if (ValidateFormat(format, FormatUsage.Sample)) diff --git a/Runtime/Export/Time.bindings.cs b/Runtime/Export/Time.bindings.cs deleted file mode 100644 index 22eb7f8386..0000000000 --- a/Runtime/Export/Time.bindings.cs +++ /dev/null @@ -1,77 +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.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Input/TimeManager.h")] - [StaticAccessor("GetTimeManager()", StaticAccessorType.Dot)] - // The interface to get time information from Unity. - public class Time - { - // The time this frame has started (RO). This is the time in seconds since the start of the game. - [NativeProperty("CurTime")] - public static extern float time { get; } - - // The time this frame has started (RO). This is the time in seconds since the last level has been loaded. - [NativeProperty("TimeSinceSceneLoad")] - public static extern float timeSinceLevelLoad { get; } - - // The time in seconds it took to complete the last frame (RO). - public static extern float deltaTime { get; } - - // The time the latest MonoBehaviour::pref::FixedUpdate has started (RO). This is the time in seconds since the start of the game. - public static extern float fixedTime { get; } - - // The cached real time (realTimeSinceStartup) at the start of this frame - public static extern float unscaledTime { get; } - - // The real time corresponding to this fixed frame - public static extern float fixedUnscaledTime { get; } - - // The delta time based upon the realTime - public static extern float unscaledDeltaTime { get; } - - // The delta time based upon the realTime - public static extern float fixedUnscaledDeltaTime { get; } - - // The interval in seconds at which physics and other fixed frame rate updates (like MonoBehaviour's MonoBehaviour::pref::FixedUpdate) are performed. - public static extern float fixedDeltaTime { get; set; } - - // The maximum time a frame can take. Physics and other fixed frame rate updates (like MonoBehaviour's MonoBehaviour::pref::FixedUpdate) - public static extern float maximumDeltaTime { get; set; } - - // A smoothed out Time.deltaTime (RO). - public static extern float smoothDeltaTime { get; } - - // The maximum time a frame can spend on particle updates. If the frame takes longer than this, then updates are split into multiple smaller updates. - public static extern float maximumParticleDeltaTime { get; set; } - - // The scale at which the time is passing. This can be used for slow motion effects. - public static extern float timeScale { get; set; } - - // The total number of frames that have passed (RO). - public static extern int frameCount { get; } - - //*undocumented* - [NativeProperty("RenderFrameCount")] - public static extern int renderedFrameCount { get; } - - // The real time in seconds since the game started (RO). - [NativeProperty("Realtime")] - public static extern float realtimeSinceStartup { get; } - - // If /captureFramerate/ is set to a value larger than 0, time will advance in - public static extern int captureFramerate { get; set; } - - // Returns true if inside a fixed time step callback such as FixedUpdate, otherwise false. - public static extern bool inFixedTimeStep - { - [NativeName("IsUsingFixedTimeStep")] - get; - } - } -} diff --git a/Runtime/Export/TouchScreenKeyboardType.cs b/Runtime/Export/TouchScreenKeyboardType.cs deleted file mode 100644 index ba93dc8275..0000000000 --- a/Runtime/Export/TouchScreenKeyboardType.cs +++ /dev/null @@ -1,34 +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 UnityEngine -{ - // Describes the type of keyboard. - public enum TouchScreenKeyboardType - { - // The default keyboard layout of the target platform. - Default = 0, - // Keyboard with standard ASCII keys. - ASCIICapable = 1, - // Keyboard with numbers and punctuation mark keys. - NumbersAndPunctuation = 2, - // Keyboard optimized for URL entry, features ".", "/", and ".com" - URL = 3, - // Keyboard with standard numeric keys, suitable for typing PINs or passwords - NumberPad = 4, - // Keyboard with a layout suitable for typing telephone numbers, has the numeric 0 to 9, the "*", and "#" keys - PhonePad = 5, - // Keyboard with alphanumeric keys designed for entering a person's name or phone number. - NamePhonePad = 6, - // Keyboard with additional keys suitable for typing email addresses, features the "@" and "." - EmailAddress = 7, - // Keyboard with the Nintendo Network Account key layout (only available on the Wii U) - [System.Obsolete("Wii U is no longer supported as of Unity 2018.1.")] - NintendoNetworkAccount = 8, - // Keyboard with symbol keys often used on social media such as Twitter, features the "@" (and "#" on iOS/tvOS) - Social = 9, - // Keyboard optimized for search terms, features the space and "." - Search = 10 - } -} diff --git a/Runtime/Export/TrackedReference.cs b/Runtime/Export/TrackedReference.cs deleted file mode 100644 index 9f3be32216..0000000000 --- a/Runtime/Export/TrackedReference.cs +++ /dev/null @@ -1,44 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEngineInternal; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - [StructLayout(LayoutKind.Sequential)] - [UsedByNativeCode] - //This class should be internal. Next time we can break backwardscompatibility we should do it. - public class TrackedReference - { - internal IntPtr m_Ptr; - - protected TrackedReference() {} - - public static bool operator==(TrackedReference x, TrackedReference y) - { - object xo = x; - object yo = y; - - if (yo == null && xo == null) return true; - if (yo == null) return x.m_Ptr == IntPtr.Zero; - if (xo == null) return y.m_Ptr == IntPtr.Zero; - return x.m_Ptr == y.m_Ptr; - } - - public static bool operator!=(TrackedReference x, TrackedReference y) { return !(x == y); } - - public override bool Equals(object o) { return (o as TrackedReference) == this; } - public override int GetHashCode() { return (int)m_Ptr; } - - public static implicit operator bool(TrackedReference exists) - { - return exists != null; - } - } -} diff --git a/Runtime/Export/UnityAPICompatibilityVersionAttribute.cs b/Runtime/Export/UnityAPICompatibilityVersionAttribute.cs deleted file mode 100644 index d1e6925fa8..0000000000 --- a/Runtime/Export/UnityAPICompatibilityVersionAttribute.cs +++ /dev/null @@ -1,20 +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 UnityEngine -{ - [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - public class UnityAPICompatibilityVersionAttribute : Attribute - { - public UnityAPICompatibilityVersionAttribute(string version) - { - _version = version; - } - - public string version { get { return _version; } } - - private string _version; - } -} diff --git a/Runtime/Export/UnityEngineInternal/APIUpdaterRuntimeServices.cs b/Runtime/Export/UnityEngineInternal/APIUpdaterRuntimeServices.cs deleted file mode 100644 index 1177fe9d28..0000000000 --- a/Runtime/Export/UnityEngineInternal/APIUpdaterRuntimeServices.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 System.Reflection; -using UnityEngine; - -namespace UnityEngineInternal -{ - public sealed class APIUpdaterRuntimeServices - { - - [Obsolete(@"AddComponent(string) has been deprecated. Use GameObject.AddComponent() / GameObject.AddComponent(Type) instead. -API Updater could not automatically update the original call to AddComponent(string name), because it was unable to resolve the type specified in parameter 'name'. -Instead, this call has been replaced with a call to APIUpdaterRuntimeServices.AddComponent() so you can try to test your game in the editor. -In order to be able to build the game, replace this call (APIUpdaterRuntimeServices.AddComponent()) with a call to GameObject.AddComponent() / GameObject.AddComponent(Type).")] - public static Component AddComponent(GameObject go, string sourceInfo, string name) - { - Debug.LogWarningFormat("Performing a potentially slow search for component {0}.", name); - - var type = ResolveType(name, Assembly.GetCallingAssembly(), sourceInfo); - return type == null - ? null - : go.AddComponent(type); - } - - private static Type ResolveType(string name, Assembly callingAssembly, string sourceInfo) - { - var foundOnUnityEngine = ComponentsFromUnityEngine.FirstOrDefault(t => (t.Name == name || t.FullName == name) && !IsMarkedAsObsolete(t)); - if (foundOnUnityEngine != null) - { - Debug.LogWarningFormat("[{1}] Component type '{0}' found in UnityEngine, consider replacing with go.AddComponent<{0}>()", name, sourceInfo); - return foundOnUnityEngine; - } - - var candidateType = callingAssembly.GetType(name); - if (candidateType != null) - { - Debug.LogWarningFormat("[{1}] Component type '{0}' found on caller assembly, consider replacing with go.AddComponent<{0}>()", name, sourceInfo); - return candidateType; - } - - candidateType = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).SingleOrDefault(t => (t.Name == name || t.FullName == name) && typeof(Component).IsAssignableFrom(t)); - if (candidateType != null) - { - Debug.LogWarningFormat("[{2}] Component type '{0}' found on assembly {1}, consider replacing with go.AddComponent<{0}>()", name, new AssemblyName(candidateType.Assembly.FullName).Name, sourceInfo); - return candidateType; - } - - Debug.LogErrorFormat("[{1}] Component Type '{0}' not found.", name, sourceInfo); - return null; - } - - private static bool IsMarkedAsObsolete(Type t) - { - return t.GetCustomAttributes(typeof(ObsoleteAttribute), false).Any(); - } - - static APIUpdaterRuntimeServices() - { - var componentType = typeof(Component); - ComponentsFromUnityEngine = componentType.Assembly.GetTypes().Where(componentType.IsAssignableFrom).ToList(); - } - - private static IList ComponentsFromUnityEngine; - } -} diff --git a/Runtime/Export/UnityEngineInternal/TypeInferenceRuleAttribute.cs b/Runtime/Export/UnityEngineInternal/TypeInferenceRuleAttribute.cs deleted file mode 100644 index 386831bdd7..0000000000 --- a/Runtime/Export/UnityEngineInternal/TypeInferenceRuleAttribute.cs +++ /dev/null @@ -1,56 +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 UnityEngineInternal -{ - public enum TypeInferenceRules - { - /// - /// (typeof(T)) as T - /// - TypeReferencedByFirstArgument, - - /// - /// (, typeof(T)) as T - /// - TypeReferencedBySecondArgument, - - /// - /// (typeof(T)) as (T) - /// - ArrayOfTypeReferencedByFirstArgument, - - /// - /// (T) as T - /// - TypeOfFirstArgument, - } - - /// - /// Adds a special type inference rule to a method. - /// - [Serializable] - [AttributeUsage(AttributeTargets.Method)] - public class TypeInferenceRuleAttribute : Attribute - { - private readonly string _rule; - - public TypeInferenceRuleAttribute(TypeInferenceRules rule) - : this(rule.ToString()) - { - } - - public TypeInferenceRuleAttribute(string rule) - { - _rule = rule; - } - - public override string ToString() - { - return _rule; - } - } -} diff --git a/Runtime/Export/UnityEngineInternal/WrappedTypes.cs b/Runtime/Export/UnityEngineInternal/WrappedTypes.cs deleted file mode 100644 index aa92583b91..0000000000 --- a/Runtime/Export/UnityEngineInternal/WrappedTypes.cs +++ /dev/null @@ -1,15 +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; -namespace UnityEngineInternal -{ - // This is a solution to problem where we cannot use: - // * System.Collections.Stack on WP8 and Metro, because it was stripped from .NET - // * System.Collections.Generic.Stack cannot use on iOS because it creates a dependency to System.dll thus increasing overall executable size - public class GenericStack : System.Collections.Stack - { - } -} diff --git a/Runtime/Export/UnityEventQueueSystem.bindings.cs b/Runtime/Export/UnityEventQueueSystem.bindings.cs deleted file mode 100644 index 540d0b3808..0000000000 --- a/Runtime/Export/UnityEventQueueSystem.bindings.cs +++ /dev/null @@ -1,28 +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.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Export/UnityEventQueueSystem.bindings.h")] - public class UnityEventQueueSystem - { - public static string GenerateEventIdForPayload(string eventPayloadName) - { - byte[] bs = Guid.NewGuid().ToByteArray(); - return string.Format("REGISTER_EVENT_ID(0x{0:X2}{1:X2}{2:X2}{3:X2}{4:X2}{5:X2}{6:X2}{7:X2}ULL,0x{8:X2}{9:X2}{10:X2}{11:X2}{12:X2}{13:X2}{14:X2}{15:X2}ULL,{16})" - , bs[0], bs[1], bs[2], bs[3], bs[4], bs[5], bs[6], bs[7] - , bs[8], bs[9], bs[10], bs[11], bs[12], bs[13], bs[14], bs[15] - , eventPayloadName); - } - - // Used to pass the GlobalEventQueue to native plugins. This allows native plugins to intra communicate - // and schedule cross thread work (to be executed on the main thread) without having to touch managed - // systems. - [FreeFunction] - public static extern IntPtr GetGlobalEventQueue(); - } -} diff --git a/Runtime/Export/UnityEvent_0.cs b/Runtime/Export/UnityEvent_0.cs deleted file mode 100644 index 815ee48f64..0000000000 --- a/Runtime/Export/UnityEvent_0.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - - -// If you wish to modify this template do so and then regenerate the unity -// events with the command line as shown below from within the directory -// that the template lives in. -// -// perl ../../Tools/Build/GenerateUnityEvents.pl 5 UnityEvent.template . - -using System; -using System.Reflection; -using UnityEngineInternal; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine.Events -{ - public delegate void UnityAction(); - - [Serializable] - public class UnityEvent : UnityEventBase - { - [RequiredByNativeCode] - public UnityEvent() {} - - public void AddListener(UnityAction call) - { - AddCall(GetDelegate(call)); - } - - public void RemoveListener(UnityAction call) - { - RemoveListener(call.Target, call.GetMethodInfo()); - } - - protected override MethodInfo FindMethod_Impl(string name, object targetObj) - { - return GetValidMethodInfo(targetObj, name, new Type[] {}); - } - - internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) - { - return new InvokableCall(target, theFunction); - } - - private static BaseInvokableCall GetDelegate(UnityAction action) - { - return new InvokableCall(action); - } - - private object[] m_InvokeArray = null; - public void Invoke() - { - List calls = PrepareInvoke(); - for (var i = 0; i < calls.Count; i++) - { - var curCall = calls[i] as InvokableCall; - if (curCall != null) - curCall.Invoke(); - else - { - var staticCurCall = calls[i] as InvokableCall; - if (staticCurCall != null) - staticCurCall.Invoke(); - else - { - var cachedCurCall = calls[i]; - if (m_InvokeArray == null) - m_InvokeArray = new object[0]; - - cachedCurCall.Invoke(m_InvokeArray); - } - } - } - } - - - internal void AddPersistentListener(UnityAction call) - { - AddPersistentListener(call, UnityEventCallState.RuntimeOnly); - } - - internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) - { - var count = GetPersistentEventCount(); - AddPersistentListener(); - RegisterPersistentListener(count, call); - SetPersistentListenerState(count, callState); - } - - internal void RegisterPersistentListener(int index, UnityAction call) - { - if (call == null) - { - Debug.LogWarning("Registering a Listener requires an action"); - return; - } - - RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); - } - - } -} diff --git a/Runtime/Export/UnityEvent_1.cs b/Runtime/Export/UnityEvent_1.cs deleted file mode 100644 index 2a3a02da28..0000000000 --- a/Runtime/Export/UnityEvent_1.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - - -// If you wish to modify this template do so and then regenerate the unity -// events with the command line as shown below from within the directory -// that the template lives in. -// -// perl ../../Tools/Build/GenerateUnityEvents.pl 5 UnityEvent.template . - -using System; -using System.Reflection; -using UnityEngineInternal; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine.Events -{ - public delegate void UnityAction(T0 arg0); - - [Serializable] - public abstract class UnityEvent : UnityEventBase - { - [RequiredByNativeCode] - public UnityEvent() {} - - public void AddListener(UnityAction call) - { - AddCall(GetDelegate(call)); - } - - public void RemoveListener(UnityAction call) - { - RemoveListener(call.Target, call.GetMethodInfo()); - } - - protected override MethodInfo FindMethod_Impl(string name, object targetObj) - { - return GetValidMethodInfo(targetObj, name, new Type[] {typeof(T0)}); - } - - internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) - { - return new InvokableCall(target, theFunction); - } - - private static BaseInvokableCall GetDelegate(UnityAction action) - { - return new InvokableCall(action); - } - - private object[] m_InvokeArray = null; - public void Invoke(T0 arg0) - { - List calls = PrepareInvoke(); - for (var i = 0; i < calls.Count; i++) - { - var curCall = calls[i] as InvokableCall; - if (curCall != null) - curCall.Invoke(arg0); - else - { - var staticCurCall = calls[i] as InvokableCall; - if (staticCurCall != null) - staticCurCall.Invoke(); - else - { - var cachedCurCall = calls[i]; - if (m_InvokeArray == null) - m_InvokeArray = new object[1]; - m_InvokeArray[0] = arg0; - cachedCurCall.Invoke(m_InvokeArray); - } - } - } - } - - - internal void AddPersistentListener(UnityAction call) - { - AddPersistentListener(call, UnityEventCallState.RuntimeOnly); - } - - internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) - { - var count = GetPersistentEventCount(); - AddPersistentListener(); - RegisterPersistentListener(count, call); - SetPersistentListenerState(count, callState); - } - - internal void RegisterPersistentListener(int index, UnityAction call) - { - if (call == null) - { - Debug.LogWarning("Registering a Listener requires an action"); - return; - } - - RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); - } - - } -} diff --git a/Runtime/Export/UnityEvent_2.cs b/Runtime/Export/UnityEvent_2.cs deleted file mode 100644 index c082bfd3a9..0000000000 --- a/Runtime/Export/UnityEvent_2.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - - -// If you wish to modify this template do so and then regenerate the unity -// events with the command line as shown below from within the directory -// that the template lives in. -// -// perl ../../Tools/Build/GenerateUnityEvents.pl 5 UnityEvent.template . - -using System; -using System.Reflection; -using UnityEngineInternal; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine.Events -{ - public delegate void UnityAction(T0 arg0, T1 arg1); - - [Serializable] - public abstract class UnityEvent : UnityEventBase - { - [RequiredByNativeCode] - public UnityEvent() {} - - public void AddListener(UnityAction call) - { - AddCall(GetDelegate(call)); - } - - public void RemoveListener(UnityAction call) - { - RemoveListener(call.Target, call.GetMethodInfo()); - } - - protected override MethodInfo FindMethod_Impl(string name, object targetObj) - { - return GetValidMethodInfo(targetObj, name, new Type[] {typeof(T0), typeof(T1)}); - } - - internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) - { - return new InvokableCall(target, theFunction); - } - - private static BaseInvokableCall GetDelegate(UnityAction action) - { - return new InvokableCall(action); - } - - private object[] m_InvokeArray = null; - public void Invoke(T0 arg0, T1 arg1) - { - List calls = PrepareInvoke(); - for (var i = 0; i < calls.Count; i++) - { - var curCall = calls[i] as InvokableCall; - if (curCall != null) - curCall.Invoke(arg0, arg1); - else - { - var staticCurCall = calls[i] as InvokableCall; - if (staticCurCall != null) - staticCurCall.Invoke(); - else - { - var cachedCurCall = calls[i]; - if (m_InvokeArray == null) - m_InvokeArray = new object[2]; - m_InvokeArray[0] = arg0; m_InvokeArray[1] = arg1; - cachedCurCall.Invoke(m_InvokeArray); - } - } - } - } - - - internal void AddPersistentListener(UnityAction call) - { - AddPersistentListener(call, UnityEventCallState.RuntimeOnly); - } - - internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) - { - var count = GetPersistentEventCount(); - AddPersistentListener(); - RegisterPersistentListener(count, call); - SetPersistentListenerState(count, callState); - } - - internal void RegisterPersistentListener(int index, UnityAction call) - { - if (call == null) - { - Debug.LogWarning("Registering a Listener requires an action"); - return; - } - - RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); - } - - } -} diff --git a/Runtime/Export/UnityEvent_3.cs b/Runtime/Export/UnityEvent_3.cs deleted file mode 100644 index ed058d26cc..0000000000 --- a/Runtime/Export/UnityEvent_3.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - - -// If you wish to modify this template do so and then regenerate the unity -// events with the command line as shown below from within the directory -// that the template lives in. -// -// perl ../../Tools/Build/GenerateUnityEvents.pl 5 UnityEvent.template . - -using System; -using System.Reflection; -using UnityEngineInternal; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine.Events -{ - public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2); - - [Serializable] - public abstract class UnityEvent : UnityEventBase - { - [RequiredByNativeCode] - public UnityEvent() {} - - public void AddListener(UnityAction call) - { - AddCall(GetDelegate(call)); - } - - public void RemoveListener(UnityAction call) - { - RemoveListener(call.Target, call.GetMethodInfo()); - } - - protected override MethodInfo FindMethod_Impl(string name, object targetObj) - { - return GetValidMethodInfo(targetObj, name, new Type[] {typeof(T0), typeof(T1), typeof(T2)}); - } - - internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) - { - return new InvokableCall(target, theFunction); - } - - private static BaseInvokableCall GetDelegate(UnityAction action) - { - return new InvokableCall(action); - } - - private object[] m_InvokeArray = null; - public void Invoke(T0 arg0, T1 arg1, T2 arg2) - { - List calls = PrepareInvoke(); - for (var i = 0; i < calls.Count; i++) - { - var curCall = calls[i] as InvokableCall; - if (curCall != null) - curCall.Invoke(arg0, arg1, arg2); - else - { - var staticCurCall = calls[i] as InvokableCall; - if (staticCurCall != null) - staticCurCall.Invoke(); - else - { - var cachedCurCall = calls[i]; - if (m_InvokeArray == null) - m_InvokeArray = new object[3]; - m_InvokeArray[0] = arg0; m_InvokeArray[1] = arg1; m_InvokeArray[2] = arg2; - cachedCurCall.Invoke(m_InvokeArray); - } - } - } - } - - - internal void AddPersistentListener(UnityAction call) - { - AddPersistentListener(call, UnityEventCallState.RuntimeOnly); - } - - internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) - { - var count = GetPersistentEventCount(); - AddPersistentListener(); - RegisterPersistentListener(count, call); - SetPersistentListenerState(count, callState); - } - - internal void RegisterPersistentListener(int index, UnityAction call) - { - if (call == null) - { - Debug.LogWarning("Registering a Listener requires an action"); - return; - } - - RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); - } - - } -} diff --git a/Runtime/Export/UnityEvent_4.cs b/Runtime/Export/UnityEvent_4.cs deleted file mode 100644 index 35e4608e75..0000000000 --- a/Runtime/Export/UnityEvent_4.cs +++ /dev/null @@ -1,105 +0,0 @@ -// Unity C# reference source -// Copyright (c) Unity Technologies. For terms of use, see -// https://unity3d.com/legal/licenses/Unity_Reference_Only_License - - -// If you wish to modify this template do so and then regenerate the unity -// events with the command line as shown below from within the directory -// that the template lives in. -// -// perl ../../Tools/Build/GenerateUnityEvents.pl 5 UnityEvent.template . - -using System; -using System.Reflection; -using UnityEngineInternal; -using UnityEngine.Scripting; -using System.Collections.Generic; - -namespace UnityEngine.Events -{ - public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2, T3 arg3); - - [Serializable] - public abstract class UnityEvent : UnityEventBase - { - [RequiredByNativeCode] - public UnityEvent() {} - - public void AddListener(UnityAction call) - { - AddCall(GetDelegate(call)); - } - - public void RemoveListener(UnityAction call) - { - RemoveListener(call.Target, call.GetMethodInfo()); - } - - protected override MethodInfo FindMethod_Impl(string name, object targetObj) - { - return GetValidMethodInfo(targetObj, name, new Type[] {typeof(T0), typeof(T1), typeof(T2), typeof(T3)}); - } - - internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) - { - return new InvokableCall(target, theFunction); - } - - private static BaseInvokableCall GetDelegate(UnityAction action) - { - return new InvokableCall(action); - } - - private object[] m_InvokeArray = null; - public void Invoke(T0 arg0, T1 arg1, T2 arg2, T3 arg3) - { - List calls = PrepareInvoke(); - for (var i = 0; i < calls.Count; i++) - { - var curCall = calls[i] as InvokableCall; - if (curCall != null) - curCall.Invoke(arg0, arg1, arg2, arg3); - else - { - var staticCurCall = calls[i] as InvokableCall; - if (staticCurCall != null) - staticCurCall.Invoke(); - else - { - var cachedCurCall = calls[i]; - if (m_InvokeArray == null) - m_InvokeArray = new object[4]; - m_InvokeArray[0] = arg0; m_InvokeArray[1] = arg1; m_InvokeArray[2] = arg2; m_InvokeArray[3] = arg3; - cachedCurCall.Invoke(m_InvokeArray); - } - } - } - } - - - internal void AddPersistentListener(UnityAction call) - { - AddPersistentListener(call, UnityEventCallState.RuntimeOnly); - } - - internal void AddPersistentListener(UnityAction call, UnityEventCallState callState) - { - var count = GetPersistentEventCount(); - AddPersistentListener(); - RegisterPersistentListener(count, call); - SetPersistentListenerState(count, callState); - } - - internal void RegisterPersistentListener(int index, UnityAction call) - { - if (call == null) - { - Debug.LogWarning("Registering a Listener requires an action"); - return; - } - - RegisterPersistentListener(index, call.Target as UnityEngine.Object, call.Method); - } - - } -} diff --git a/Runtime/Export/UnityLogWriter.bindings.cs b/Runtime/Export/UnityLogWriter.bindings.cs deleted file mode 100644 index 6ce5c86a97..0000000000 --- a/Runtime/Export/UnityLogWriter.bindings.cs +++ /dev/null @@ -1,51 +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.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.IO; -using System.Text; -using UnityEngine.Bindings; - -namespace UnityEngine -{ - [NativeHeader("Runtime/Export/UnityLogWriter.bindings.h")] - internal class UnityLogWriter : System.IO.TextWriter - { - [ThreadAndSerializationSafe] - public static void WriteStringToUnityLog(string s) - { - if (s == null) return; - WriteStringToUnityLogImpl(s); - } - - [FreeFunction(IsThreadSafe = true)] - private static extern void WriteStringToUnityLogImpl(string s); - - public static void Init() - { - System.Console.SetOut(new UnityLogWriter()); - } - - public override System.Text.Encoding Encoding - { - get { return System.Text.Encoding.UTF8; } - } - public override void Write(char value) - { - WriteStringToUnityLog(value.ToString()); - } - - public override void Write(string s) - { - WriteStringToUnityLog(s); - } - - public override void Write(char[] buffer, int index, int count) - { - WriteStringToUnityLogImpl(new string(buffer, index, count)); - } - } -} diff --git a/Runtime/Export/Vector3Int.cs b/Runtime/Export/Vector3Int.cs index d7871a42a8..15e21aa1f8 100644 --- a/Runtime/Export/Vector3Int.cs +++ b/Runtime/Export/Vector3Int.cs @@ -177,7 +177,9 @@ public bool Equals(Vector3Int other) public override int GetHashCode() { - return x.GetHashCode() ^ (y.GetHashCode() << 2) ^ (z.GetHashCode() >> 2); + var yHash = y.GetHashCode(); + var zHash = z.GetHashCode(); + return x.GetHashCode() ^ (yHash << 4) ^ (yHash >> 28) ^ (zHash >> 4) ^ (zHash << 28); } public override string ToString() diff --git a/Runtime/Export/WaitForEndOfFrame.cs b/Runtime/Export/WaitForEndOfFrame.cs deleted file mode 100644 index 411ff43931..0000000000 --- a/Runtime/Export/WaitForEndOfFrame.cs +++ /dev/null @@ -1,14 +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.Scripting; - -namespace UnityEngine -{ - // Waits until the end of the frame after all cameras and GUI is rendered, just before displaying the frame on screen. - [RequiredByNativeCode] - public sealed class WaitForEndOfFrame : YieldInstruction - { - } -} diff --git a/Runtime/Export/WaitForFixedUpdate.cs b/Runtime/Export/WaitForFixedUpdate.cs deleted file mode 100644 index 1ac4f7d0fb..0000000000 --- a/Runtime/Export/WaitForFixedUpdate.cs +++ /dev/null @@ -1,14 +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.Scripting; - -namespace UnityEngine -{ - // Waits until next fixed frame rate update function. SA: MonoBehaviour::pref::FixedUpdate. - [RequiredByNativeCode] - public sealed class WaitForFixedUpdate : YieldInstruction - { - } -} diff --git a/Runtime/Export/WaitForSeconds.cs b/Runtime/Export/WaitForSeconds.cs deleted file mode 100644 index dfef27d281..0000000000 --- a/Runtime/Export/WaitForSeconds.cs +++ /dev/null @@ -1,20 +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.Runtime.InteropServices; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - // Suspends the coroutine execution for the given amount of seconds. - [StructLayout(LayoutKind.Sequential)] - [RequiredByNativeCode] - public sealed class WaitForSeconds : YieldInstruction - { - internal float m_Seconds; - - // Creates a yield instruction to wait for a given number of seconds - public WaitForSeconds(float seconds) { m_Seconds = seconds; } - } -} diff --git a/Runtime/Export/WaitUntil.cs b/Runtime/Export/WaitUntil.cs deleted file mode 100644 index 5219e3ab13..0000000000 --- a/Runtime/Export/WaitUntil.cs +++ /dev/null @@ -1,17 +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 UnityEngine -{ - public sealed class WaitUntil : CustomYieldInstruction - { - Func m_Predicate; - - public override bool keepWaiting { get { return !m_Predicate(); } } - - public WaitUntil(Func predicate) { m_Predicate = predicate; } - } -} diff --git a/Runtime/Export/WaitWhile.cs b/Runtime/Export/WaitWhile.cs deleted file mode 100644 index 2b30122813..0000000000 --- a/Runtime/Export/WaitWhile.cs +++ /dev/null @@ -1,17 +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 UnityEngine -{ - public sealed class WaitWhile : CustomYieldInstruction - { - Func m_Predicate; - - public override bool keepWaiting { get { return m_Predicate(); } } - - public WaitWhile(Func predicate) { m_Predicate = predicate; } - } -} diff --git a/Runtime/Export/WinRT/NetFxCoreExtensions.cs b/Runtime/Export/WinRT/NetFxCoreExtensions.cs deleted file mode 100644 index ae8aabcc92..0000000000 --- a/Runtime/Export/WinRT/NetFxCoreExtensions.cs +++ /dev/null @@ -1,23 +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.Reflection; - -namespace UnityEngineInternal -{ - internal static class NetFxCoreExtensions - { - public static Delegate CreateDelegate(this MethodInfo self, Type delegateType, object target) - { - return Delegate.CreateDelegate(delegateType, target, self); - } - - public static MethodInfo GetMethodInfo(this Delegate self) - { - return self.Method; - } - - } -} diff --git a/Runtime/Export/YieldOperation.cs b/Runtime/Export/YieldOperation.cs deleted file mode 100644 index 9f59a77c44..0000000000 --- a/Runtime/Export/YieldOperation.cs +++ /dev/null @@ -1,16 +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.Runtime.InteropServices; -using UnityEngine.Scripting; - -namespace UnityEngine -{ - // Base class for all /yield/ instructions. - [StructLayout(LayoutKind.Sequential)] - [UsedByNativeCode] - public class YieldInstruction - { - } -} diff --git a/Runtime/Networking/Managed/MatchMakingClient.cs b/Runtime/Networking/Managed/MatchMakingClient.cs index 79df91f44d..4725689b0a 100644 --- a/Runtime/Networking/Managed/MatchMakingClient.cs +++ b/Runtime/Networking/Managed/MatchMakingClient.cs @@ -12,6 +12,7 @@ namespace UnityEngine.Networking.Match { // returned when you create or join a match (private info) //[Serializable] //TODO: enabled this when 64 bit enum issue is resolved + [Obsolete("The matchmaker and relay feature will be removed in the future, minimal support will continue until this can be safely done.")] public class MatchInfo { public string address { get; private set; } @@ -53,6 +54,7 @@ public override string ToString() } } + [Obsolete("The matchmaker and relay feature will be removed in the future, minimal support will continue until this can be safely done.")] public class MatchInfoSnapshot { public NetworkID networkId { get; private set; } @@ -109,6 +111,7 @@ internal MatchInfoSnapshot(MatchDesc matchDesc) } } + [Obsolete("The matchmaker and relay feature will be removed in the future, minimal support will continue until this can be safely done.")] public class NetworkMatch : MonoBehaviour { public delegate void BasicResponseDelegate(bool success, string extendedInfo); @@ -137,11 +140,9 @@ public Coroutine CreateMatch(string matchName, uint matchSize, bool matchAdverti Debug.LogError("Matchmaking is not supported on WebGL player."); return null; } - else - return CreateMatch(new CreateMatchRequest { name = matchName, size = matchSize, advertise = matchAdvertise, password = matchPassword, publicAddress = publicClientAddress, privateAddress = privateClientAddress, eloScore = eloScoreForMatch, domain = requestDomain }, callback); + return CreateMatch(new CreateMatchRequest { name = matchName, size = matchSize, advertise = matchAdvertise, password = matchPassword, publicAddress = publicClientAddress, privateAddress = privateClientAddress, eloScore = eloScoreForMatch, domain = requestDomain }, callback); } - // Begin Create a match internal Coroutine CreateMatch(CreateMatchRequest req, DataResponseDelegate callback) { if (callback == null) diff --git a/Runtime/Networking/Managed/NetworkTransportConfig.cs b/Runtime/Networking/Managed/NetworkTransportConfig.cs index 9bdf9f3b57..84450263db 100644 --- a/Runtime/Networking/Managed/NetworkTransportConfig.cs +++ b/Runtime/Networking/Managed/NetworkTransportConfig.cs @@ -68,6 +68,7 @@ public enum ConnectionAcksType }; [Serializable] + [Obsolete("The UNET transport will be removed in the future as soon a replacement is ready.")] public class ChannelQOS { [SerializeField] @@ -105,6 +106,7 @@ public ChannelQOS(ChannelQOS channel) //to allow user manipulate channel info via property with parameter (using array interface) //all fields are defined for direct access from HLAPI (it it needed) [Serializable] + [Obsolete("The UNET transport will be removed in the future as soon a replacement is ready.")] public class ConnectionConfig { private const int g_MinPacketSize = 128; @@ -502,6 +504,7 @@ public IList GetSharedOrderChannels(byte idx) //and array of special connection (with special configuration) //AddSpecialConnection will return connection id which user should use when he call connect to identify special configuration for this connection [Serializable] + [Obsolete("The UNET transport will be removed in the future as soon a replacement is ready.")] public class HostTopology { [SerializeField] @@ -589,6 +592,7 @@ public int AddSpecialConnectionConfig(ConnectionConfig config) } [Serializable] + [Obsolete("The UNET transport will be removed in the future as soon a replacement is ready.")] public class GlobalConfig { private const uint g_MaxTimerTimeout = 12000; //before changing check UNETConfiguration.h file @@ -753,6 +757,7 @@ public Action ConnectionReadyForSend } } + [Obsolete("The UNET transport will be removed in the future as soon a replacement is ready.")] public class ConnectionSimulatorConfig : IDisposable { internal int m_OutMinDelay; diff --git a/Runtime/Networking/Managed/UNETWebSocketLib.cs b/Runtime/Networking/Managed/UNETWebSocketLib.cs deleted file mode 100644 index 3afc7aa210..0000000000 --- a/Runtime/Networking/Managed/UNETWebSocketLib.cs +++ /dev/null @@ -1,15 +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.Diagnostics; -using System.Runtime.InteropServices; -using System.Net; -using UnityEngine.Networking; -using UnityEngine.Networking.Types; -using UnityEngine; -using Debug = UnityEngine.Debug; - - diff --git a/Runtime/Networking/ScriptBindings/UNETTransportConfig.bindings.cs b/Runtime/Networking/ScriptBindings/UNETTransportConfig.bindings.cs index a170c1b9ed..10e043cef8 100644 --- a/Runtime/Networking/ScriptBindings/UNETTransportConfig.bindings.cs +++ b/Runtime/Networking/ScriptBindings/UNETTransportConfig.bindings.cs @@ -13,6 +13,7 @@ namespace UnityEngine.Networking { +#pragma warning disable 618 [NativeHeader("Runtime/Networking/UNETManager.h")] [NativeHeader("Runtime/Networking/UNetTypes.h")] @@ -308,4 +309,5 @@ public void Dispose() [NativeProperty("m_MaxNetSimulatorTimeout", TargetType.Field)] private extern uint MaxNetSimulatorTimeout { set; } } +#pragma warning restore 618 } diff --git a/Runtime/Networking/ScriptBindings/UNETworking.bindings.cs b/Runtime/Networking/ScriptBindings/UNETworking.bindings.cs index c5eafd5400..0d8523ddf3 100644 --- a/Runtime/Networking/ScriptBindings/UNETworking.bindings.cs +++ b/Runtime/Networking/ScriptBindings/UNETworking.bindings.cs @@ -19,6 +19,7 @@ namespace UnityEngine.Networking [NativeHeader("Runtime/Networking/UNetTypes.h")] [NativeHeader("Runtime/Networking/UNETConfiguration.h")] [NativeConditional("ENABLE_NETWORK && ENABLE_UNET", true)] + [Obsolete("The UNET transport will be removed in the future as soon a replacement is ready.")] public sealed partial class NetworkTransport { private NetworkTransport() {} diff --git a/Runtime/ParticleSystem/Managed/ParticleSystem.deprecated.cs b/Runtime/ParticleSystem/Managed/ParticleSystem.deprecated.cs index 462a1bf79b..a0611e5bc6 100644 --- a/Runtime/ParticleSystem/Managed/ParticleSystem.deprecated.cs +++ b/Runtime/ParticleSystem/Managed/ParticleSystem.deprecated.cs @@ -44,7 +44,7 @@ public partial struct ShapeModule // Scale. (Meshes) [Obsolete("meshScale property is deprecated.Please use scale instead.", false)] public float meshScale { get { return scale.x; } set { scale = new Vector3(value, value, value); } } - [Obsolete("randomDirection property is deprecated.Use randomDirectionAmount instead.", false)] + [Obsolete("randomDirection property is deprecated. Use randomDirectionAmount instead.", false)] public bool randomDirection { get { return (randomDirectionAmount >= 0.5f); } set { randomDirectionAmount = value ? 1.0f : 0.0f; } } } @@ -82,11 +82,11 @@ public partial struct Particle { [Obsolete("Please use Particle.remainingLifetime instead. (UnityUpgradable) -> UnityEngine.ParticleSystem/Particle.remainingLifetime", false)] public float lifetime { get { return remainingLifetime; } set { remainingLifetime = value; } } - [Obsolete("randomValue property is deprecated.Use randomSeed instead to control random behavior of particles.", false)] + [Obsolete("randomValue property is deprecated. Use randomSeed instead to control random behavior of particles.", false)] public float randomValue { get { return BitConverter.ToSingle(BitConverter.GetBytes(m_RandomSeed), 0); } set { m_RandomSeed = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0); } } - [Obsolete("size property is deprecated.Use startSize or GetCurrentSize() instead.", false)] + [Obsolete("size property is deprecated. Use startSize or GetCurrentSize() instead.", false)] public float size { get { return startSize; } set { startSize = value; } } - [Obsolete("color property is deprecated.Use startColor or GetCurrentColor() instead.", false)] + [Obsolete("color property is deprecated. Use startColor or GetCurrentColor() instead.", false)] public Color32 color { get { return startColor; } set { startColor = value; } } } @@ -125,56 +125,59 @@ public void Emit(ParticleSystem.Particle particle) Internal_EmitOld(ref particle); } - [Obsolete("startDelay property is deprecated.Use main.startDelay or main.startDelayMultiplier instead.", false)] + [Obsolete("startDelay property is deprecated. Use main.startDelay or main.startDelayMultiplier instead.", false)] public float startDelay { get { return main.startDelayMultiplier; } set { var m = main; m.startDelayMultiplier = value; } } - [Obsolete("loop property is deprecated.Use main.loop instead.", false)] + [Obsolete("loop property is deprecated. Use main.loop instead.", false)] public bool loop { get { return main.loop; } set { var m = main; m.loop = value; } } - [Obsolete("playOnAwake property is deprecated.Use main.playOnAwake instead.", false)] + [Obsolete("playOnAwake property is deprecated. Use main.playOnAwake instead.", false)] public bool playOnAwake { get { return main.playOnAwake; } set { var m = main; m.playOnAwake = value; } } - [Obsolete("duration property is deprecated.Use main.duration instead.", false)] + [Obsolete("duration property is deprecated. Use main.duration instead.", false)] public float duration { get { return main.duration; } } - [Obsolete("playbackSpeed property is deprecated.Use main.simulationSpeed instead.", false)] + [Obsolete("playbackSpeed property is deprecated. Use main.simulationSpeed instead.", false)] public float playbackSpeed { get { return main.simulationSpeed; } set { var m = main; m.simulationSpeed = value; } } - [Obsolete("enableEmission property is deprecated.Use emission.enabled instead.", false)] + [Obsolete("enableEmission property is deprecated. Use emission.enabled instead.", false)] public bool enableEmission { get { return emission.enabled; } set { var em = emission; em.enabled = value; } } - [Obsolete("emissionRate property is deprecated.Use emission.rateOverTime, emission.rateOverDistance, emission.rateOverTimeMultiplier or emission.rateOverDistanceMultiplier instead.", false)] + [Obsolete("emissionRate property is deprecated. Use emission.rateOverTime, emission.rateOverDistance, emission.rateOverTimeMultiplier or emission.rateOverDistanceMultiplier instead.", false)] public float emissionRate { get { return emission.rateOverTimeMultiplier; } set { var em = emission; em.rateOverTime = value; } } - [Obsolete("startSpeed property is deprecated.Use main.startSpeed or main.startSpeedMultiplier instead.", false)] + [Obsolete("startSpeed property is deprecated. Use main.startSpeed or main.startSpeedMultiplier instead.", false)] public float startSpeed { get { return main.startSpeedMultiplier; } set { var m = main; m.startSpeedMultiplier = value; } } - [Obsolete("startSize property is deprecated.Use main.startSize or main.startSizeMultiplier instead.", false)] + [Obsolete("startSize property is deprecated. Use main.startSize or main.startSizeMultiplier instead.", false)] public float startSize { get { return main.startSizeMultiplier; } set { var m = main; m.startSizeMultiplier = value; } } - [Obsolete("startColor property is deprecated.Use main.startColor instead.", false)] + [Obsolete("startColor property is deprecated. Use main.startColor instead.", false)] public Color startColor { get { return main.startColor.color; } set { var m = main; m.startColor = value; } } - [Obsolete("startRotation property is deprecated.Use main.startRotation or main.startRotationMultiplier instead.", false)] + [Obsolete("startRotation property is deprecated. Use main.startRotation or main.startRotationMultiplier instead.", false)] public float startRotation { get { return main.startRotationMultiplier; } set { var m = main; m.startRotationMultiplier = value; } } - [Obsolete("startRotation3D property is deprecated.Use main.startRotationX, main.startRotationY and main.startRotationZ instead. (Or main.startRotationXMultiplier, main.startRotationYMultiplier and main.startRotationZMultiplier).", false)] + [Obsolete("startRotation3D property is deprecated. Use main.startRotationX, main.startRotationY and main.startRotationZ instead. (Or main.startRotationXMultiplier, main.startRotationYMultiplier and main.startRotationZMultiplier).", false)] public Vector3 startRotation3D { get { return new Vector3(main.startRotationXMultiplier, main.startRotationYMultiplier, main.startRotationZMultiplier); } set { var m = main; m.startRotationXMultiplier = value.x; m.startRotationYMultiplier = value.y; m.startRotationZMultiplier = value.z; } } - [Obsolete("startLifetime property is deprecated.Use main.startLifetime or main.startLifetimeMultiplier instead.", false)] + [Obsolete("startLifetime property is deprecated. Use main.startLifetime or main.startLifetimeMultiplier instead.", false)] public float startLifetime { get { return main.startLifetimeMultiplier; } set { var m = main; m.startLifetimeMultiplier = value; } } - [Obsolete("gravityModifier property is deprecated.Use main.gravityModifier or main.gravityModifierMultiplier instead.", false)] + [Obsolete("gravityModifier property is deprecated. Use main.gravityModifier or main.gravityModifierMultiplier instead.", false)] public float gravityModifier { get { return main.gravityModifierMultiplier; } set { var m = main; m.gravityModifierMultiplier = value; } } - [Obsolete("maxParticles property is deprecated.Use main.maxParticles instead.", false)] + [Obsolete("maxParticles property is deprecated. Use main.maxParticles instead.", false)] public int maxParticles { get { return main.maxParticles; } set { var m = main; m.maxParticles = value; } } - [Obsolete("simulationSpace property is deprecated.Use main.simulationSpace instead.", false)] + [Obsolete("simulationSpace property is deprecated. Use main.simulationSpace instead.", false)] public ParticleSystemSimulationSpace simulationSpace { get { return main.simulationSpace; } set { var m = main; m.simulationSpace = value; } } - [Obsolete("scalingMode property is deprecated.Use main.scalingMode instead.", false)] + [Obsolete("scalingMode property is deprecated. Use main.scalingMode instead.", false)] public ParticleSystemScalingMode scalingMode { get { return main.scalingMode; } set { var m = main; m.scalingMode = value; } } + + [Obsolete("automaticCullingEnabled property is deprecated. Use proceduralSimulationSupported instead (UnityUpgradable) -> proceduralSimulationSupported", true)] + public bool automaticCullingEnabled { get { return proceduralSimulationSupported; } } } public static partial class ParticlePhysicsExtensions diff --git a/Runtime/ParticleSystem/Managed/ParticleSystemEnums.cs b/Runtime/ParticleSystem/Managed/ParticleSystemEnums.cs index c1a37bb876..432ca9b435 100644 --- a/Runtime/ParticleSystem/Managed/ParticleSystemEnums.cs +++ b/Runtime/ParticleSystem/Managed/ParticleSystemEnums.cs @@ -188,6 +188,15 @@ public enum ParticleSystemStopAction Callback = 3 // Calls OnParticleSystemStopped. } + // The action to perform when a particle system is offscreen + public enum ParticleSystemCullingMode + { + Automatic = 0, + PauseAndCatchup = 1, + Pause = 2, + AlwaysSimulate = 3 + } + // The emitter velocity mode for particle systems public enum ParticleSystemEmitterVelocityMode { diff --git a/Runtime/ParticleSystem/Managed/ParticleSystemRenderer.deprecated.cs b/Runtime/ParticleSystem/Managed/ParticleSystemRenderer.deprecated.cs deleted file mode 100644 index 23ccf5629b..0000000000 --- a/Runtime/ParticleSystem/Managed/ParticleSystemRenderer.deprecated.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; - -namespace UnityEngine -{ - [Flags, Obsolete("ParticleSystemVertexStreams is deprecated. Please use ParticleSystemVertexStream instead.", false)] - public enum ParticleSystemVertexStreams - { - Position = 1 << 0, - Normal = 1 << 1, - Tangent = 1 << 2, - Color = 1 << 3, - UV = 1 << 4, - UV2BlendAndFrame = 1 << 5, - CenterAndVertexID = 1 << 6, - Size = 1 << 7, - Rotation = 1 << 8, - Velocity = 1 << 9, - Lifetime = 1 << 10, - Custom1 = 1 << 11, - Custom2 = 1 << 12, - Random = 1 << 13, - None = 0, - All = 0x7fffffff - } - - partial class ParticleSystemRenderer - { - [Obsolete("EnableVertexStreams is deprecated.Use SetActiveVertexStreams instead.", false)] - public void EnableVertexStreams(ParticleSystemVertexStreams streams) { Internal_SetVertexStreams(streams, true); } - [Obsolete("DisableVertexStreams is deprecated.Use SetActiveVertexStreams instead.", false)] - public void DisableVertexStreams(ParticleSystemVertexStreams streams) { Internal_SetVertexStreams(streams, false); } - [Obsolete("AreVertexStreamsEnabled is deprecated.Use GetActiveVertexStreams instead.", false)] - public bool AreVertexStreamsEnabled(ParticleSystemVertexStreams streams) { return Internal_GetEnabledVertexStreams(streams) == streams; } - [Obsolete("GetEnabledVertexStreams is deprecated.Use GetActiveVertexStreams instead.", false)] - public ParticleSystemVertexStreams GetEnabledVertexStreams(ParticleSystemVertexStreams streams) { return Internal_GetEnabledVertexStreams(streams); } - - [Obsolete("Internal_SetVertexStreams is deprecated.Use SetActiveVertexStreams instead.", false)] - internal void Internal_SetVertexStreams(ParticleSystemVertexStreams streams, bool enabled) - { - List streamList = new List(activeVertexStreamsCount); - GetActiveVertexStreams(streamList); - - if (enabled) - { - if ((streams & ParticleSystemVertexStreams.Position) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Position)) { streamList.Add(ParticleSystemVertexStream.Position); } } - if ((streams & ParticleSystemVertexStreams.Normal) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Normal)) { streamList.Add(ParticleSystemVertexStream.Normal); } } - if ((streams & ParticleSystemVertexStreams.Tangent) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Tangent)) { streamList.Add(ParticleSystemVertexStream.Tangent); } } - if ((streams & ParticleSystemVertexStreams.Color) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Color)) { streamList.Add(ParticleSystemVertexStream.Color); } } - if ((streams & ParticleSystemVertexStreams.UV) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.UV)) { streamList.Add(ParticleSystemVertexStream.UV); } } - if ((streams & ParticleSystemVertexStreams.UV2BlendAndFrame) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.UV2)) { streamList.Add(ParticleSystemVertexStream.UV2); streamList.Add(ParticleSystemVertexStream.AnimBlend); streamList.Add(ParticleSystemVertexStream.AnimFrame); } } - if ((streams & ParticleSystemVertexStreams.CenterAndVertexID) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Center)) { streamList.Add(ParticleSystemVertexStream.Center); streamList.Add(ParticleSystemVertexStream.VertexID); } } - if ((streams & ParticleSystemVertexStreams.Size) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.SizeXYZ)) { streamList.Add(ParticleSystemVertexStream.SizeXYZ); } } - if ((streams & ParticleSystemVertexStreams.Rotation) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Rotation3D)) { streamList.Add(ParticleSystemVertexStream.Rotation3D); } } - if ((streams & ParticleSystemVertexStreams.Velocity) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Velocity)) { streamList.Add(ParticleSystemVertexStream.Velocity); } } - if ((streams & ParticleSystemVertexStreams.Lifetime) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.AgePercent)) { streamList.Add(ParticleSystemVertexStream.AgePercent); streamList.Add(ParticleSystemVertexStream.InvStartLifetime); } } - if ((streams & ParticleSystemVertexStreams.Custom1) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Custom1XYZW)) { streamList.Add(ParticleSystemVertexStream.Custom1XYZW); } } - if ((streams & ParticleSystemVertexStreams.Custom2) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.Custom2XYZW)) { streamList.Add(ParticleSystemVertexStream.Custom2XYZW); } } - if ((streams & ParticleSystemVertexStreams.Random) != 0) { if (!streamList.Contains(ParticleSystemVertexStream.StableRandomXYZ)) { streamList.Add(ParticleSystemVertexStream.StableRandomXYZ); streamList.Add(ParticleSystemVertexStream.VaryingRandomX); } } - } - else - { - if ((streams & ParticleSystemVertexStreams.Position) != 0) { streamList.Remove(ParticleSystemVertexStream.Position); } - if ((streams & ParticleSystemVertexStreams.Normal) != 0) { streamList.Remove(ParticleSystemVertexStream.Normal); } - if ((streams & ParticleSystemVertexStreams.Tangent) != 0) { streamList.Remove(ParticleSystemVertexStream.Tangent); } - if ((streams & ParticleSystemVertexStreams.Color) != 0) { streamList.Remove(ParticleSystemVertexStream.Color); } - if ((streams & ParticleSystemVertexStreams.UV) != 0) { streamList.Remove(ParticleSystemVertexStream.UV); } - if ((streams & ParticleSystemVertexStreams.UV2BlendAndFrame) != 0) { streamList.Remove(ParticleSystemVertexStream.UV2); streamList.Remove(ParticleSystemVertexStream.AnimBlend); streamList.Remove(ParticleSystemVertexStream.AnimFrame); } - if ((streams & ParticleSystemVertexStreams.CenterAndVertexID) != 0) { streamList.Remove(ParticleSystemVertexStream.Center); streamList.Remove(ParticleSystemVertexStream.VertexID); } - if ((streams & ParticleSystemVertexStreams.Size) != 0) { streamList.Remove(ParticleSystemVertexStream.SizeXYZ); } - if ((streams & ParticleSystemVertexStreams.Rotation) != 0) { streamList.Remove(ParticleSystemVertexStream.Rotation3D); } - if ((streams & ParticleSystemVertexStreams.Velocity) != 0) { streamList.Remove(ParticleSystemVertexStream.Velocity); } - if ((streams & ParticleSystemVertexStreams.Lifetime) != 0) { streamList.Remove(ParticleSystemVertexStream.AgePercent); streamList.Remove(ParticleSystemVertexStream.InvStartLifetime); } - if ((streams & ParticleSystemVertexStreams.Custom1) != 0) { streamList.Remove(ParticleSystemVertexStream.Custom1XYZW); } - if ((streams & ParticleSystemVertexStreams.Custom2) != 0) { streamList.Remove(ParticleSystemVertexStream.Custom2XYZW); } - if ((streams & ParticleSystemVertexStreams.Random) != 0) { streamList.Remove(ParticleSystemVertexStream.StableRandomXYZW); streamList.Remove(ParticleSystemVertexStream.VaryingRandomX); } - } - - SetActiveVertexStreams(streamList); - } - - [Obsolete("Internal_GetVertexStreams is deprecated.Use GetActiveVertexStreams instead.", false)] - internal ParticleSystemVertexStreams Internal_GetEnabledVertexStreams(ParticleSystemVertexStreams streams) - { - List streamList = new List(activeVertexStreamsCount); - GetActiveVertexStreams(streamList); - - ParticleSystemVertexStreams deprecatedStreams = 0; - if (streamList.Contains(ParticleSystemVertexStream.Position)) deprecatedStreams |= ParticleSystemVertexStreams.Position; - if (streamList.Contains(ParticleSystemVertexStream.Normal)) deprecatedStreams |= ParticleSystemVertexStreams.Normal; - if (streamList.Contains(ParticleSystemVertexStream.Tangent)) deprecatedStreams |= ParticleSystemVertexStreams.Tangent; - if (streamList.Contains(ParticleSystemVertexStream.Color)) deprecatedStreams |= ParticleSystemVertexStreams.Color; - if (streamList.Contains(ParticleSystemVertexStream.UV)) deprecatedStreams |= ParticleSystemVertexStreams.UV; - if (streamList.Contains(ParticleSystemVertexStream.UV2)) deprecatedStreams |= ParticleSystemVertexStreams.UV2BlendAndFrame; - if (streamList.Contains(ParticleSystemVertexStream.Center)) deprecatedStreams |= ParticleSystemVertexStreams.CenterAndVertexID; - if (streamList.Contains(ParticleSystemVertexStream.SizeXYZ)) deprecatedStreams |= ParticleSystemVertexStreams.Size; - if (streamList.Contains(ParticleSystemVertexStream.Rotation3D)) deprecatedStreams |= ParticleSystemVertexStreams.Rotation; - if (streamList.Contains(ParticleSystemVertexStream.Velocity)) deprecatedStreams |= ParticleSystemVertexStreams.Velocity; - if (streamList.Contains(ParticleSystemVertexStream.AgePercent)) deprecatedStreams |= ParticleSystemVertexStreams.Lifetime; - if (streamList.Contains(ParticleSystemVertexStream.Custom1XYZW)) deprecatedStreams |= ParticleSystemVertexStreams.Custom1; - if (streamList.Contains(ParticleSystemVertexStream.Custom2XYZW)) deprecatedStreams |= ParticleSystemVertexStreams.Custom2; - if (streamList.Contains(ParticleSystemVertexStream.StableRandomXYZ)) deprecatedStreams |= ParticleSystemVertexStreams.Random; - - return (deprecatedStreams & streams); - } - } -} diff --git a/Runtime/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs b/Runtime/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs index cde478662b..532b49ce9f 100644 --- a/Runtime/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs +++ b/Runtime/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs @@ -21,30 +21,30 @@ public partial class ParticleSystem : Component // Properties extern public bool isPlaying { - [NativeName("SyncJobs()->IsPlaying")] get; + [NativeName("SyncJobs(false)->IsPlaying")] get; } extern public bool isEmitting { - [NativeName("SyncJobs()->IsEmitting")] get; + [NativeName("SyncJobs(false)->IsEmitting")] get; } extern public bool isStopped { - [NativeName("SyncJobs()->IsStopped")] get; + [NativeName("SyncJobs(false)->IsStopped")] get; } extern public bool isPaused { - [NativeName("SyncJobs()->IsPaused")] get; + [NativeName("SyncJobs(false)->IsPaused")] get; } extern public int particleCount { - [NativeName("SyncJobs()->GetParticleCount")] get; + [NativeName("SyncJobs(false)->GetParticleCount")] get; } extern public float time { - [NativeName("SyncJobs()->GetSecPosition")] + [NativeName("SyncJobs(false)->GetSecPosition")] get; - [NativeName("SyncJobs()->SetSecPosition")] + [NativeName("SyncJobs(false)->SetSecPosition")] set; } @@ -52,7 +52,7 @@ extern public UInt32 randomSeed { [NativeName("GetRandomSeed")] get; - [NativeName("SyncJobs()->SetRandomSeed")] + [NativeName("SyncJobs(false)->SetRandomSeed")] set; } @@ -60,11 +60,11 @@ extern public bool useAutoRandomSeed { [NativeName("GetAutoRandomSeed")] get; - [NativeName("SyncJobs()->SetAutoRandomSeed")] + [NativeName("SyncJobs(false)->SetAutoRandomSeed")] set; } - extern public bool automaticCullingEnabled + extern public bool proceduralSimulationSupported { get; } diff --git a/Runtime/Profiler/ScriptBindings/MemoryProfiling.bindings.cs b/Runtime/Profiler/ScriptBindings/MemoryProfiling.bindings.cs index dc9144cefa..38177b0d47 100644 --- a/Runtime/Profiler/ScriptBindings/MemoryProfiling.bindings.cs +++ b/Runtime/Profiler/ScriptBindings/MemoryProfiling.bindings.cs @@ -61,6 +61,7 @@ public static void TakeTempSnapshot(Action finishCallback, Captur TakeSnapshot(path, finishCallback, captureFlags); } + [RequiredByNativeCode] static byte[] PrepareMetadata() { if (createMetaData == null) @@ -71,6 +72,9 @@ static byte[] PrepareMetadata() MetaData data = new MetaData(); createMetaData(data); + if (data.content == null) data.content = ""; + if (data.platform == null) data.platform = ""; + int contentLength = sizeof(char) * data.content.Length; int platformLength = sizeof(char) * data.platform.Length; @@ -164,6 +168,7 @@ private static int WriteStringToByteArray(byte[] array, int offset, string value return offset; } + [RequiredByNativeCode] static void FinalizeSnapshot(string path, bool result) { if (snapshotFinished != null) diff --git a/Runtime/TerrainPhysics/TerrainPhysics.bindings.cs b/Runtime/TerrainPhysics/TerrainPhysics.bindings.cs deleted file mode 100644 index 95487b6edb..0000000000 --- a/Runtime/TerrainPhysics/TerrainPhysics.bindings.cs +++ /dev/null @@ -1,17 +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.Bindings; - - -namespace UnityEngine -{ - [NativeHeader("Runtime/TerrainPhysics/TerrainCollider.h")] - [NativeHeader("Modules/Terrain/Public/TerrainData.h")] - public class TerrainCollider : Collider - { - public extern TerrainData terrainData { get; set; } - } -} - diff --git a/Runtime/Transform/ScriptBindings/Transform.bindings.cs b/Runtime/Transform/ScriptBindings/Transform.bindings.cs index 79877fee02..3e3e121490 100644 --- a/Runtime/Transform/ScriptBindings/Transform.bindings.cs +++ b/Runtime/Transform/ScriptBindings/Transform.bindings.cs @@ -382,7 +382,10 @@ public int hierarchyCapacity [FreeFunction("SetHierarchyCapacity", HasExplicitThis = true)] private extern void internal_setHierarchyCapacity(int value); - public int hierarchyCount { get; } + public int hierarchyCount { get { return internal_getHierarchyCount(); } } + + [FreeFunction("GetHierarchyCount", HasExplicitThis = true)] + private extern int internal_getHierarchyCount(); [NativeConditional("UNITY_EDITOR")] [FreeFunction("IsNonUniformScaleTransform", HasExplicitThis = true)] diff --git a/Runtime/VR/HoloLens/ScriptBindings/HolographicSettings.deprecated.cs b/Runtime/VR/HoloLens/ScriptBindings/HolographicSettings.deprecated.cs deleted file mode 100644 index 008de0e340..0000000000 --- a/Runtime/VR/HoloLens/ScriptBindings/HolographicSettings.deprecated.cs +++ /dev/null @@ -1,25 +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 UnityEngine.XR.WSA -{ - partial class HolographicSettings - { - [Obsolete("Support for toggling latent frame presentation has been removed", true)] - static public void ActivateLatentFramePresentation(bool activated) - { - } - - [Obsolete("Support for toggling latent frame presentation has been removed, and IsLatentFramePresentation will always return true", false)] - static public bool IsLatentFramePresentation - { - get - { - return true; - } - } - } -} diff --git a/Runtime/VR/ScriptBindings/VRNode.deprecated.cs b/Runtime/VR/ScriptBindings/VRNode.deprecated.cs deleted file mode 100644 index 13f4afbec2..0000000000 --- a/Runtime/VR/ScriptBindings/VRNode.deprecated.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 - -namespace UnityEngine.VR -{ - // Matches UnityVRTrackedNodeType in IUnityVR.h - [System.Obsolete("VRNode has been moved and renamed. Use UnityEngine.XR.XRNode instead (UnityUpgradable) -> UnityEngine.XR.XRNode", true)] - public enum VRNode - { - LeftEye, - RightEye, - CenterEye, - Head, - LeftHand, - RightHand, - GameController, - TrackingReference, - HardwareTracker - } -} diff --git a/Tools/PackageManager/DataContract/IEditorModule.cs b/Tools/PackageManager/DataContract/IEditorModule.cs deleted file mode 100644 index fa1e7c1440..0000000000 --- a/Tools/PackageManager/DataContract/IEditorModule.cs +++ /dev/null @@ -1,36 +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; - -namespace Unity.DataContract -{ - public enum UpdateMode - { - Automatic, - Periodic, - Manual - } - - public interface IEditorModule : IDisposable - { - PackageInfo moduleInfo { get; set; } - void Initialize(); - void Shutdown(bool wait); - } - - public interface IPackageManagerModule : IEditorModule - { - string editorInstallPath { get; set; } - string unityVersion { get; set; } - UpdateMode updateMode { get; set; } - IEnumerable playbackEngines { get; } - IEnumerable unityExtensions { get; } - - void CheckForUpdates(); - void LoadPackage(PackageInfo package); - void SelectPackage(PackageInfo package); - } -} diff --git a/Tools/PackageManager/DataContract/PackageInfo.cs b/Tools/PackageManager/DataContract/PackageInfo.cs deleted file mode 100644 index df85cb74cd..0000000000 --- a/Tools/PackageManager/DataContract/PackageInfo.cs +++ /dev/null @@ -1,106 +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.Collections.Generic; - -namespace Unity.DataContract -{ - public class PackageInfo - { - public string organisation; - public string name; - public PackageVersion version; - public PackageVersion unityVersion; - public string basePath; - public PackageType type; - public string description; - public string releaseNotes; - public bool loaded; - - Dictionary m_FileDict; - public Dictionary files - { - get { return m_FileDict; } - set { m_FileDict = value; } - } - - public string packageName - { - get { return string.Format("{0}.{1}", organisation, name); } - } - - public override string ToString() - { - return string.Format("{0} {1} ({2}) v{3} for Unity v{4}", organisation, name, type, version != null ? version.text : null, unityVersion != null ? basePath : null); - } - - public override int GetHashCode() - { - var hash = 17; - hash = hash * 23 + organisation.GetHashCode(); - hash = hash * 23 + name.GetHashCode(); - hash = hash * 23 + type.GetHashCode(); - hash = hash * 23 + version.GetHashCode(); - hash = hash * 23 + unityVersion.GetHashCode(); - return hash; - } - - public override bool Equals(object other) - { - return this == (other as PackageInfo); - } - - public static bool operator==(PackageInfo a, PackageInfo z) - { - if ((object)a == null && (object)z == null) - return true; - if ((object)a == null || (object)z == null) - return false; - return a.GetHashCode() == z.GetHashCode(); - } - - public static bool operator!=(PackageInfo a, PackageInfo z) - { - return !(a == z); - } - } - - - public class PackageFileData - { - public PackageFileType type; - public string url; - public string guid; - - public PackageFileData() {} - public PackageFileData(PackageFileType type, string url) - { - this.type = type; - this.url = url; - } - - public PackageFileData(PackageFileType type, string url, string guid) : this(type, url) - { - this.guid = guid; - } - } - - public enum PackageType - { - Unknown = 0, - PlaybackEngine, - UnityExtension, - PackageManager - } - - public enum PackageFileType - { - None, - Package, - Ivy, - Dll, - ReleaseNotes, - DebugSymbols - } -} diff --git a/Tools/PackageManager/DataContract/Properties/AssemblyInfo.cs b/Tools/PackageManager/DataContract/Properties/AssemblyInfo.cs deleted file mode 100644 index 5cd60a30b8..0000000000 --- a/Tools/PackageManager/DataContract/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,29 +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.Reflection; -using System.Runtime.CompilerServices; - -// Information about this assembly is defined by the following attributes. -// Change them to the values specific to your project. - -[assembly: AssemblyTitle("Unity.DataContract")] -[assembly: AssemblyDescription("Package Manager data contract for package information")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Unity")] -[assembly: AssemblyProduct("Package Manager")] -[assembly: AssemblyCopyright("Copyright © Unity Technologies A/S 2013")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// The assembly version has the format "{Major}.{Minor}.{Micro}.{Revision}". - -[assembly: AssemblyVersion("1.0.2")] -[assembly: AssemblyFileVersion("1.0.2")] - -// The following attributes are used to specify the signing key for the assembly, -// if desired. See the Mono documentation for more information about signing. - -//[assembly: AssemblyDelaySign(false)] -//[assembly: AssemblyKeyFile("")] diff --git a/Tools/Unity.CecilTools/CecilUtils.cs b/Tools/Unity.CecilTools/CecilUtils.cs deleted file mode 100644 index a7e3cb0256..0000000000 --- a/Tools/Unity.CecilTools/CecilUtils.cs +++ /dev/null @@ -1,65 +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 Mono.Cecil; -using Unity.CecilTools.Extensions; - -namespace Unity.CecilTools -{ - public static class CecilUtils - { - public static MethodDefinition FindInTypeExplicitImplementationFor(MethodDefinition interfaceMethod, TypeDefinition typeDefinition) - { - return typeDefinition.Methods.SingleOrDefault(m => m.Overrides.Any(o => o.CheckedResolve().SameAs(interfaceMethod))); - } - - public static IEnumerable AllInterfacesImplementedBy(TypeDefinition typeDefinition) - { - return TypeAndBaseTypesOf(typeDefinition).SelectMany(t => t.Interfaces).Select(i => i.InterfaceType.CheckedResolve()).Distinct(); - } - - public static IEnumerable TypeAndBaseTypesOf(TypeReference typeReference) - { - while (typeReference != null) - { - var typeDefinition = typeReference.CheckedResolve(); - yield return typeDefinition; - typeReference = typeDefinition.BaseType; - } - } - - public static IEnumerable BaseTypesOf(TypeReference typeReference) - { - return TypeAndBaseTypesOf(typeReference).Skip(1); - } - - public static bool IsGenericList(TypeReference type) - { - return type.Name == "List`1" && type.SafeNamespace() == "System.Collections.Generic"; - } - - public static bool IsGenericDictionary(TypeReference type) - { - if (type is GenericInstanceType) - type = ((GenericInstanceType)type).ElementType; - - return type.Name == "Dictionary`2" && type.SafeNamespace() == "System.Collections.Generic"; - } - - public static TypeReference ElementTypeOfCollection(TypeReference type) - { - var at = type as ArrayType; - if (at != null) - return at.ElementType; - - if (IsGenericList(type)) - return ((GenericInstanceType)type).GenericArguments.Single(); - - throw new ArgumentException(); - } - } -} diff --git a/Tools/Unity.CecilTools/ElementType.cs b/Tools/Unity.CecilTools/ElementType.cs deleted file mode 100644 index a3d858d6d8..0000000000 --- a/Tools/Unity.CecilTools/ElementType.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; -using Mono.Cecil; - -namespace Unity.CecilTools -{ - static public class ElementType - { - public static TypeReference For(TypeReference byRefType) - { - var refType = byRefType as TypeSpecification; - if (refType != null) - return refType.ElementType; - - throw new ArgumentException(string.Format("TypeReference isn't a TypeSpecification {0} ", byRefType)); - } - } -} diff --git a/Tools/Unity.CecilTools/Extensions/MethodDefinitionExtensions.cs b/Tools/Unity.CecilTools/Extensions/MethodDefinitionExtensions.cs deleted file mode 100644 index c99d8e704e..0000000000 --- a/Tools/Unity.CecilTools/Extensions/MethodDefinitionExtensions.cs +++ /dev/null @@ -1,50 +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 Mono.Cecil; - -namespace Unity.CecilTools.Extensions -{ - static class MethodDefinitionExtensions - { - public static bool SameAs(this MethodDefinition self, MethodDefinition other) - { - // FIXME: should be able to compare MethodDefinition references directly - return self.FullName == other.FullName; - } - - public static string PropertyName(this MethodDefinition self) - { - return self.Name.Substring(4); - } - - public static bool IsConversionOperator(this MethodDefinition method) - { - if (!method.IsSpecialName) - return false; - - return method.Name == "op_Implicit" || method.Name == "op_Explicit"; - } - - public static bool IsSimpleSetter(this MethodDefinition original) - { - return original.IsSetter && original.Parameters.Count == 1; - } - - public static bool IsSimpleGetter(this MethodDefinition original) - { - return original.IsGetter && original.Parameters.Count == 0; - } - - public static bool IsSimplePropertyAccessor(this MethodDefinition method) - { - return method.IsSimpleGetter() || method.IsSimpleSetter(); - } - - public static bool IsDefaultConstructor(MethodDefinition m) - { - return m.IsConstructor && !m.IsStatic && m.Parameters.Count == 0; - } - } -} diff --git a/Tools/Unity.CecilTools/Extensions/ResolutionExtensions.cs b/Tools/Unity.CecilTools/Extensions/ResolutionExtensions.cs deleted file mode 100644 index 29d85065ff..0000000000 --- a/Tools/Unity.CecilTools/Extensions/ResolutionExtensions.cs +++ /dev/null @@ -1,36 +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 Mono.Cecil; - -namespace Unity.CecilTools.Extensions -{ - public static class ResolutionExtensions - { - public static TypeDefinition CheckedResolve(this TypeReference type) - { - return Resolve(type, reference => reference.Resolve()); - } - - public static MethodDefinition CheckedResolve(this MethodReference method) - { - return Resolve(method, reference => reference.Resolve()); - } - - private static TDefinition Resolve(TReference reference, Func resolve) - where TReference : MemberReference - where TDefinition : class, IMemberDefinition - { - if (reference.Module == null) - throw new ResolutionException(reference); - - var definition = resolve(reference); - if (definition == null) - throw new ResolutionException(reference); - - return definition; - } - } -} diff --git a/Tools/Unity.CecilTools/Extensions/TypeDefinitionExtensions.cs b/Tools/Unity.CecilTools/Extensions/TypeDefinitionExtensions.cs deleted file mode 100644 index 7b727ffd87..0000000000 --- a/Tools/Unity.CecilTools/Extensions/TypeDefinitionExtensions.cs +++ /dev/null @@ -1,30 +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 System.Text; -using Mono.Cecil; - -namespace Unity.CecilTools.Extensions -{ - public static class TypeDefinitionExtensions - { - public static bool IsSubclassOf(this TypeDefinition type, string baseTypeName) - { - var baseType = type.BaseType; - if (baseType == null) - return false; - if (baseType.FullName == baseTypeName) - return true; - - var baseTypeDef = baseType.Resolve(); - if (baseTypeDef == null) - return false; - - return IsSubclassOf(baseTypeDef, baseTypeName); - } - } -} diff --git a/Tools/Unity.CecilTools/Extensions/TypeReferenceExtensions.cs b/Tools/Unity.CecilTools/Extensions/TypeReferenceExtensions.cs deleted file mode 100644 index 65bf5013eb..0000000000 --- a/Tools/Unity.CecilTools/Extensions/TypeReferenceExtensions.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 Mono.Cecil; - -namespace Unity.CecilTools.Extensions -{ - public static class TypeReferenceExtensions - { - public static string SafeNamespace(this TypeReference type) - { - if (type.IsGenericInstance) - return ((GenericInstanceType)type).ElementType.SafeNamespace(); - if (type.IsNested) - return type.DeclaringType.SafeNamespace(); - return type.Namespace; - } - - public static bool IsAssignableTo(this TypeReference typeRef, string typeName) - { - try - { - if (typeRef.IsGenericInstance) - return ElementType.For(typeRef).IsAssignableTo(typeName); - - if (typeRef.FullName == typeName) - return true; - - return typeRef.CheckedResolve().IsSubclassOf(typeName); - } - catch (AssemblyResolutionException) // If we can't resolve our typeref or one of its base types, - { // let's assume it is not assignable to our target type - return false; - } - } - - public static bool IsEnum(this TypeReference type) - { - return type.IsValueType && !type.IsPrimitive && type.CheckedResolve().IsEnum; - } - - public static bool IsStruct(this TypeReference type) - { - return type.IsValueType && !type.IsPrimitive && !type.IsEnum() && !IsSystemDecimal(type); - } - - private static bool IsSystemDecimal(TypeReference type) - { - return type.FullName == "System.Decimal"; - } - } -} diff --git a/Tools/Unity.CecilTools/Properties/AssemblyInfo.cs b/Tools/Unity.CecilTools/Properties/AssemblyInfo.cs deleted file mode 100644 index ffc3916879..0000000000 --- a/Tools/Unity.CecilTools/Properties/AssemblyInfo.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 System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Unity.CecilTools")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Unity.CecilTools")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("dd4fb846-79f2-4cfe-81e9-07c7215c1fd8")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Tools/Unity.SerializationLogic/Properties/AssemblyInfo.cs b/Tools/Unity.SerializationLogic/Properties/AssemblyInfo.cs deleted file mode 100644 index 8e45ef61e8..0000000000 --- a/Tools/Unity.SerializationLogic/Properties/AssemblyInfo.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 System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Unity.SerializationLogic")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Unity.SerializationLogic")] -[assembly: AssemblyCopyright("Copyright © Microsoft 2012")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("b8090e7e-a5cc-4c4a-bfae-536379343f00")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Tools/Unity.SerializationLogic/UnityEngineTypePredicates.cs b/Tools/Unity.SerializationLogic/UnityEngineTypePredicates.cs deleted file mode 100644 index ebf9fc25b1..0000000000 --- a/Tools/Unity.SerializationLogic/UnityEngineTypePredicates.cs +++ /dev/null @@ -1,137 +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.Collections.Generic; -using Unity.CecilTools.Extensions; -using Mono.Cecil; - -namespace Unity.SerializationLogic -{ - public class UnityEngineTypePredicates - { - private static readonly HashSet TypesThatShouldHaveHadSerializableAttribute = new HashSet - { - "Vector3", - "Vector2", - "Vector4", - "Rect", - "RectInt", - "Quaternion", - "Matrix4x4", - "Color", - "Color32", - "LayerMask", - "Bounds", - "BoundsInt", - "Vector3Int", - "Vector2Int", - }; - - private const string AnimationCurve = "UnityEngine.AnimationCurve"; - private const string Gradient = "UnityEngine.Gradient"; - private const string GUIStyle = "UnityEngine.GUIStyle"; - private const string RectOffset = "UnityEngine.RectOffset"; - protected const string UnityEngineObject = "UnityEngine.Object"; - public const string MonoBehaviour = "UnityEngine.MonoBehaviour"; - public const string ScriptableObject = "UnityEngine.ScriptableObject"; - protected const string Matrix4x4 = "UnityEngine.Matrix4x4"; - protected const string Color32 = "UnityEngine.Color32"; - private const string SerializeFieldAttribute = "UnityEngine.SerializeField"; - - private static string[] serializableStructs = new[] - { - "UnityEngine.AnimationCurve", - "UnityEngine.Color32", - "UnityEngine.Gradient", - "UnityEngine.GUIStyle", - "UnityEngine.RectOffset", - "UnityEngine.Matrix4x4", - "UnityEngine.PropertyName" - }; - - public static bool IsMonoBehaviour(TypeReference type) - { - return IsMonoBehaviour(type.CheckedResolve()); - } - - private static bool IsMonoBehaviour(TypeDefinition typeDefinition) - { - return typeDefinition.IsSubclassOf(MonoBehaviour); - } - - public static bool IsScriptableObject(TypeReference type) - { - return IsScriptableObject(type.CheckedResolve()); - } - - private static bool IsScriptableObject(TypeDefinition temp) - { - return temp.IsSubclassOf(ScriptableObject); - } - - public static bool IsColor32(TypeReference type) - { - return type.IsAssignableTo(Color32); - } - - //Do NOT remove these, cil2as still depends on these in 4.x - public static bool IsMatrix4x4(TypeReference type) - { - return type.IsAssignableTo(Matrix4x4); - } - - public static bool IsGradient(TypeReference type) - { - return type.IsAssignableTo(Gradient); - } - - public static bool IsGUIStyle(TypeReference type) - { - return type.IsAssignableTo(GUIStyle); - } - - public static bool IsRectOffset(TypeReference type) - { - return type.IsAssignableTo(RectOffset); - } - - public static bool IsSerializableUnityStruct(TypeReference type) - { - foreach (var unityStruct in serializableStructs) - { - if (type.IsAssignableTo(unityStruct)) - return true; - } - return false; - } - - public static bool IsUnityEngineObject(TypeReference type) - { - //todo: somehow solve this elegantly. CheckedResolve() drops the [] of a type. - if (type.IsArray) - return false; - - var typeDefinition = type.Resolve(); - if (typeDefinition == null) - return false; - - return type.FullName == UnityEngineObject || typeDefinition.IsSubclassOf(UnityEngineObject); - } - - public static bool ShouldHaveHadSerializableAttribute(TypeReference type) - { - return IsUnityEngineValueType(type); - } - - public static bool IsUnityEngineValueType(TypeReference type) - { - return type.SafeNamespace() == "UnityEngine" && TypesThatShouldHaveHadSerializableAttribute.Contains(type.Name); - } - - public static bool IsSerializeFieldAttribute(TypeReference attributeType) - { - return attributeType.FullName == SerializeFieldAttribute; - } - } -} diff --git a/Tools/Unity.SerializationLogic/UnitySerializationLogic.cs b/Tools/Unity.SerializationLogic/UnitySerializationLogic.cs deleted file mode 100644 index 2673ce2cf5..0000000000 --- a/Tools/Unity.SerializationLogic/UnitySerializationLogic.cs +++ /dev/null @@ -1,564 +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 Mono.Cecil; -using Mono.Collections.Generic; -using Unity.CecilTools; -using Unity.CecilTools.Extensions; - -namespace Unity.SerializationLogic -{ - internal class GenericInstanceHolder - { - public int Count; - public IGenericInstance GenericInstance; - } - - public class TypeResolver - { - private readonly IGenericInstance _typeDefinitionContext; - private readonly IGenericInstance _methodDefinitionContext; - private readonly Dictionary _context = new Dictionary(); - - public TypeResolver() - { - } - - public TypeResolver(IGenericInstance typeDefinitionContext) - { - _typeDefinitionContext = typeDefinitionContext; - } - - public TypeResolver(GenericInstanceMethod methodDefinitionContext) - { - _methodDefinitionContext = methodDefinitionContext; - } - - public TypeResolver(IGenericInstance typeDefinitionContext, IGenericInstance methodDefinitionContext) - { - _typeDefinitionContext = typeDefinitionContext; - _methodDefinitionContext = methodDefinitionContext; - } - - public void Add(GenericInstanceType genericInstanceType) - { - Add(ElementTypeFor(genericInstanceType).FullName, genericInstanceType); - } - - public void Remove(GenericInstanceType genericInstanceType) - { - Remove(genericInstanceType.ElementType.FullName, genericInstanceType); - } - - public void Add(GenericInstanceMethod genericInstanceMethod) - { - Add(ElementTypeFor(genericInstanceMethod).FullName, genericInstanceMethod); - } - - private static MemberReference ElementTypeFor(TypeSpecification genericInstanceType) - { - return genericInstanceType.ElementType; - } - - private static MemberReference ElementTypeFor(MethodSpecification genericInstanceMethod) - { - return genericInstanceMethod.ElementMethod; - } - - public void Remove(GenericInstanceMethod genericInstanceMethod) - { - Remove(genericInstanceMethod.ElementMethod.FullName, genericInstanceMethod); - } - - public TypeReference Resolve(TypeReference typeReference) - { - var genericParameter = typeReference as GenericParameter; - if (genericParameter != null) - { - var resolved = ResolveGenericParameter(genericParameter); - if (genericParameter == resolved) // Resolving failed, return what we have. - return resolved; - - return Resolve(resolved); - } - - var arrayType = typeReference as ArrayType; - if (arrayType != null) - return new ArrayType(Resolve(arrayType.ElementType), arrayType.Rank); - - var pointerType = typeReference as PointerType; - if (pointerType != null) - return new PointerType(Resolve(pointerType.ElementType)); - - var byReferenceType = typeReference as ByReferenceType; - if (byReferenceType != null) - return new ByReferenceType(Resolve(byReferenceType.ElementType)); - - var genericInstanceType = typeReference as GenericInstanceType; - if (genericInstanceType != null) - { - var newGenericInstanceType = new GenericInstanceType(Resolve(genericInstanceType.ElementType)); - foreach (var genericArgument in genericInstanceType.GenericArguments) - newGenericInstanceType.GenericArguments.Add(Resolve(genericArgument)); - return newGenericInstanceType; - } - - var pinnedType = typeReference as PinnedType; - if (pinnedType != null) - return new PinnedType(Resolve(pinnedType.ElementType)); - - var reqModifierType = typeReference as RequiredModifierType; - if (reqModifierType != null) - return Resolve(reqModifierType.ElementType); - - var optModifierType = typeReference as OptionalModifierType; - if (optModifierType != null) - return new OptionalModifierType(Resolve(optModifierType.ModifierType), Resolve(optModifierType.ElementType)); - - var sentinelType = typeReference as SentinelType; - if (sentinelType != null) - return new SentinelType(Resolve(sentinelType.ElementType)); - - var funcPtrType = typeReference as FunctionPointerType; - if (funcPtrType != null) - throw new NotSupportedException("Function pointer types are not supported by the SerializationWeaver"); - - if (typeReference is TypeSpecification) - throw new NotSupportedException(); - - return typeReference; - } - - private TypeReference ResolveGenericParameter(GenericParameter genericParameter) - { - if (genericParameter.Owner == null) - throw new NotSupportedException(); - - var memberReference = genericParameter.Owner as MemberReference; - if (memberReference == null) - throw new NotSupportedException(); - - var key = memberReference.FullName; - if (!_context.ContainsKey(key)) - { - if (genericParameter.Type == GenericParameterType.Type) - { - if (_typeDefinitionContext != null) - return _typeDefinitionContext.GenericArguments[genericParameter.Position]; - - return genericParameter; - } - - if (_methodDefinitionContext != null) - return _methodDefinitionContext.GenericArguments[genericParameter.Position]; - - return genericParameter; - } - - return GenericArgumentAt(key, genericParameter.Position); - } - - private TypeReference GenericArgumentAt(string key, int position) - { - return _context[key].GenericInstance.GenericArguments[position]; - } - - private void Add(string key, IGenericInstance value) - { - GenericInstanceHolder oldValue; - - if (_context.TryGetValue(key, out oldValue)) - { - var memberReference = value as MemberReference; - if (memberReference == null) - throw new NotSupportedException(); - - var storedValue = (MemberReference)oldValue.GenericInstance; - - if (storedValue.FullName != memberReference.FullName) - throw new ArgumentException("Duplicate key!", "key"); - - oldValue.Count++; - return; - } - - _context.Add(key, new GenericInstanceHolder { Count = 1, GenericInstance = value }); - } - - private void Remove(string key, IGenericInstance value) - { - GenericInstanceHolder oldValue; - - if (_context.TryGetValue(key, out oldValue)) - { - var memberReference = value as MemberReference; - if (memberReference == null) - throw new NotSupportedException(); - - var storedValue = (MemberReference)oldValue.GenericInstance; - - if (storedValue.FullName != memberReference.FullName) - throw new ArgumentException("Invalid value!", "value"); - - oldValue.Count--; - if (oldValue.Count == 0) - _context.Remove(key); - - return; - } - - throw new ArgumentException("Invalid key!", "key"); - } - } - - public static class UnitySerializationLogic - { - public static bool WillUnitySerialize(FieldDefinition fieldDefinition) - { - return WillUnitySerialize(fieldDefinition, new TypeResolver(null)); - } - - public static bool WillUnitySerialize(FieldDefinition fieldDefinition, TypeResolver typeResolver) - { - if (fieldDefinition == null) - return false; - - //skip static, const and NotSerialized fields before even checking the type - if (fieldDefinition.IsStatic || IsConst(fieldDefinition) || fieldDefinition.IsNotSerialized || fieldDefinition.IsInitOnly) - return false; - - // Don't try to resolve types that come from Windows assembly, - // as serialization weaver will fail to resolve that (due to it being in platform specific SDKs) - if (ShouldNotTryToResolve(fieldDefinition.FieldType)) - return false; - - //AND, the field must have correct visibility/decoration to be serialized. - bool hasSerializeFieldAttribute = HasSerializeFieldAttribute(fieldDefinition); - if (!fieldDefinition.IsPublic && !hasSerializeFieldAttribute && - !ShouldHaveHadAllFieldsPublic(fieldDefinition)) - return false; - - if (fieldDefinition.FullName == "UnityScript.Lang.Array") - return false; - - // Resolving types is more complex and slower than checking their names or attributes, - // thus keep those checks below - - //the type of the field must be serializable in the first place. - if (!IsFieldTypeSerializable(typeResolver.Resolve(fieldDefinition.FieldType), fieldDefinition)) - return false; - - if (IsDelegate(typeResolver.Resolve(fieldDefinition.FieldType))) - return false; - - return true; - } - - private static bool IsDelegate(TypeReference typeReference) - { - return typeReference.IsAssignableTo("System.Delegate"); - } - - public static bool ShouldFieldBePPtrRemapped(FieldDefinition fieldDefinition) - { - return ShouldFieldBePPtrRemapped(fieldDefinition, new TypeResolver(null)); - } - - public static bool ShouldFieldBePPtrRemapped(FieldDefinition fieldDefinition, TypeResolver typeResolver) - { - if (!WillUnitySerialize(fieldDefinition, typeResolver)) - return false; - - return CanTypeContainUnityEngineObjectReference(typeResolver.Resolve(fieldDefinition.FieldType)); - } - - private static bool CanTypeContainUnityEngineObjectReference(TypeReference typeReference) - { - if (IsUnityEngineObject(typeReference)) - return true; - - if (typeReference.IsEnum()) - return false; - - if (IsSerializablePrimitive(typeReference)) - return false; - - if (IsSupportedCollection(typeReference)) - return CanTypeContainUnityEngineObjectReference(CecilUtils.ElementTypeOfCollection(typeReference)); - - var definition = typeReference.Resolve(); - if (definition == null) - return false; - - return HasFieldsThatCanContainUnityEngineObjectReferences(definition, new TypeResolver(typeReference as GenericInstanceType)); - } - - private static bool HasFieldsThatCanContainUnityEngineObjectReferences(TypeDefinition definition, TypeResolver typeResolver) - { - return AllFieldsFor(definition, typeResolver).Where(kv => kv.Value.Resolve(kv.Key.FieldType).Resolve() != definition).Any(kv => CanFieldContainUnityEngineObjectReference(definition, kv.Key, kv.Value)); - } - - private static IEnumerable> AllFieldsFor(TypeDefinition definition, TypeResolver typeResolver) - { - var baseType = definition.BaseType; - - if (baseType != null) - { - var genericBaseInstanceType = baseType as GenericInstanceType; - if (genericBaseInstanceType != null) - typeResolver.Add(genericBaseInstanceType); - foreach (var kv in AllFieldsFor(baseType.Resolve(), typeResolver)) - yield return kv; - if (genericBaseInstanceType != null) - typeResolver.Remove(genericBaseInstanceType); - } - - foreach (var fieldDefinition in definition.Fields) - yield return new KeyValuePair(fieldDefinition, typeResolver); - } - - private static bool CanFieldContainUnityEngineObjectReference(TypeReference typeReference, FieldDefinition t, TypeResolver typeResolver) - { - if (typeResolver.Resolve(t.FieldType) == typeReference) - return false; - - if (!WillUnitySerialize(t, typeResolver)) - return false; - - if (UnityEngineTypePredicates.IsUnityEngineValueType(typeReference)) - return false; - - return true; - } - - private static bool IsConst(FieldDefinition fieldDefinition) - { - return fieldDefinition.IsLiteral && !fieldDefinition.IsInitOnly; - } - - public static bool HasSerializeFieldAttribute(FieldDefinition field) - { - //return FieldAttributes(field).Any(UnityEngineTypePredicates.IsSerializeFieldAttribute); - foreach (var attribute in FieldAttributes(field)) - if (UnityEngineTypePredicates.IsSerializeFieldAttribute(attribute)) - return true; - return false; - } - - private static IEnumerable FieldAttributes(FieldDefinition field) - { - return field.CustomAttributes.Select(_ => _.AttributeType); - } - - public static bool ShouldNotTryToResolve(TypeReference typeReference) - { - if (typeReference.Scope.Name == "Windows") - { - return true; - } - - if (typeReference.Scope.Name == "mscorlib") - { - var resolved = typeReference.Resolve(); - return resolved == null; - } - - try - { // This will throw an exception if typereference thinks it's referencing a .dll, - // but actually there's .winmd file in the current directory. RRW will fix this - // at a later step, so we will not try to resolve this type. This is OK, as any - // type defined in a winmd cannot be serialized. - typeReference.Resolve(); - } - catch - { - return true; - } - - return false; - } - - private static bool IsFieldTypeSerializable(TypeReference typeReference, FieldDefinition fieldDefinition) - { - return IsTypeSerializable(typeReference) || IsSupportedCollection(typeReference) || IsFixedBuffer(fieldDefinition); - } - - private static bool IsTypeSerializable(TypeReference typeReference) - { - if (typeReference.IsAssignableTo("UnityScript.Lang.Array")) return false; - if (IsGenericDictionary(typeReference)) return false; - - return IsSerializablePrimitive(typeReference) - || typeReference.IsEnum() - || IsUnityEngineObject(typeReference) - || UnityEngineTypePredicates.IsSerializableUnityStruct(typeReference) - || ShouldImplementIDeserializable(typeReference); - } - - private static bool IsGenericDictionary(TypeReference typeReference) - { - var current = typeReference; - - if (current != null) - { - if (CecilUtils.IsGenericDictionary(current)) - return true; - } - - return false; - } - - public static bool IsFixedBuffer(FieldDefinition fieldDefinition) - { - return GetFixedBufferAttribute(fieldDefinition) != null; - } - - public static CustomAttribute GetFixedBufferAttribute(FieldDefinition fieldDefinition) - { - if (!fieldDefinition.HasCustomAttributes) - return null; - - return fieldDefinition.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == "System.Runtime.CompilerServices.FixedBufferAttribute"); - } - - public static int GetFixedBufferLength(FieldDefinition fieldDefinition) - { - var fixedBufferAttribute = GetFixedBufferAttribute(fieldDefinition); - - if (fixedBufferAttribute == null) - throw new ArgumentException(string.Format("Field '{0}' is not a fixed buffer field.", fieldDefinition.FullName)); - - var size = (Int32)fixedBufferAttribute.ConstructorArguments[1].Value; - - return size; - } - - public static int PrimitiveTypeSize(TypeReference type) - { - switch (type.MetadataType) - { - case MetadataType.Boolean: - case MetadataType.Byte: - case MetadataType.SByte: - return 1; - - case MetadataType.Char: - case MetadataType.Int16: - case MetadataType.UInt16: - return 2; - - case MetadataType.Int32: - case MetadataType.UInt32: - case MetadataType.Single: - return 4; - - case MetadataType.Int64: - case MetadataType.UInt64: - case MetadataType.Double: - return 8; - - default: - throw new ArgumentException(string.Format("Unsupported {0}", type.MetadataType)); - } - } - - private static bool IsSerializablePrimitive(TypeReference typeReference) - { - switch (typeReference.MetadataType) - { - case MetadataType.SByte: - case MetadataType.Byte: - case MetadataType.Char: - case MetadataType.Int16: - case MetadataType.UInt16: - case MetadataType.Int64: - case MetadataType.UInt64: - case MetadataType.Int32: - case MetadataType.UInt32: - case MetadataType.Single: - case MetadataType.Double: - case MetadataType.Boolean: - case MetadataType.String: - return true; - } - return false; - } - - public static bool IsSupportedCollection(TypeReference typeReference) - { - if (!(typeReference is ArrayType || CecilUtils.IsGenericList(typeReference))) - return false; - - // We don't support arrays like byte[,] etc - if (typeReference.IsArray && ((ArrayType)typeReference).Rank > 1) - return false; - - return IsTypeSerializable(CecilUtils.ElementTypeOfCollection(typeReference)); - } - - private static bool ShouldHaveHadAllFieldsPublic(FieldDefinition field) - { - return UnityEngineTypePredicates.IsUnityEngineValueType(field.DeclaringType); - } - - private static bool IsUnityEngineObject(TypeReference typeReference) - { - return UnityEngineTypePredicates.IsUnityEngineObject(typeReference); - } - - public static bool IsNonSerialized(TypeReference typeDeclaration) - { - if (typeDeclaration == null) - return true; - if (typeDeclaration.IsEnum()) - return true; - if (typeDeclaration.HasGenericParameters) - return true; - if (typeDeclaration.MetadataType == MetadataType.Object) - return true; - if (typeDeclaration.FullName.StartsWith("System.")) //can this be done better? - return true; - if (typeDeclaration.IsArray) - return true; - if (typeDeclaration.FullName == UnityEngineTypePredicates.MonoBehaviour) - return true; - if (typeDeclaration.FullName == UnityEngineTypePredicates.ScriptableObject) - return true; - return false; - } - - public static bool ShouldImplementIDeserializable(TypeReference typeDeclaration) - { - if (typeDeclaration.FullName == "UnityEngine.ExposedReference`1") - return true; - - if (IsNonSerialized(typeDeclaration)) - return false; - - var genericInstance = typeDeclaration as GenericInstanceType; - if (genericInstance != null) - { - if (genericInstance.ElementType.FullName == "UnityEngine.ExposedReference`1") - return true; - - return false; - } - - try - { - return UnityEngineTypePredicates.IsMonoBehaviour(typeDeclaration) - || UnityEngineTypePredicates.IsScriptableObject(typeDeclaration) - || (typeDeclaration.CheckedResolve().IsSerializable && !typeDeclaration.CheckedResolve().IsAbstract && !typeDeclaration.CheckedResolve().CustomAttributes.Any(a => a.AttributeType.FullName.Contains("System.Runtime.CompilerServices.CompilerGenerated"))) - || UnityEngineTypePredicates.ShouldHaveHadSerializableAttribute(typeDeclaration); - } - catch (Exception) - { - return false; - } - } - } -} diff --git a/artifacts/generated/bindings_old/common/AI/NavMeshAgentBindings.gen.cs b/artifacts/generated/bindings_old/common/AI/NavMeshAgentBindings.gen.cs deleted file mode 100644 index b4051023cc..0000000000 --- a/artifacts/generated/bindings_old/common/AI/NavMeshAgentBindings.gen.cs +++ /dev/null @@ -1,487 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Scripting.APIUpdating; - -namespace UnityEngine.AI -{ - - -[MovedFrom("UnityEngine")] -public enum ObstacleAvoidanceType -{ - - NoObstacleAvoidance = 0, - - LowQualityObstacleAvoidance = 1, - - MedQualityObstacleAvoidance = 2, - - GoodQualityObstacleAvoidance = 3, - - HighQualityObstacleAvoidance = 4 -} - -[MovedFrom("UnityEngine")] -public sealed partial class NavMeshAgent : Behaviour -{ - public bool SetDestination (Vector3 target) { - return INTERNAL_CALL_SetDestination ( this, ref target ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_SetDestination (NavMeshAgent self, ref Vector3 target); - public Vector3 destination - { - get { Vector3 tmp; INTERNAL_get_destination(out tmp); return tmp; } - set { INTERNAL_set_destination(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_destination (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_destination (ref Vector3 value) ; - - public extern float stoppingDistance - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public Vector3 velocity - { - get { Vector3 tmp; INTERNAL_get_velocity(out tmp); return tmp; } - set { INTERNAL_set_velocity(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_velocity (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_velocity (ref Vector3 value) ; - - public Vector3 nextPosition - { - get { Vector3 tmp; INTERNAL_get_nextPosition(out tmp); return tmp; } - set { INTERNAL_set_nextPosition(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_nextPosition (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_nextPosition (ref Vector3 value) ; - - public Vector3 steeringTarget - { - get { Vector3 tmp; INTERNAL_get_steeringTarget(out tmp); return tmp; } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_steeringTarget (out Vector3 value) ; - - - public Vector3 desiredVelocity - { - get { Vector3 tmp; INTERNAL_get_desiredVelocity(out tmp); return tmp; } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_desiredVelocity (out Vector3 value) ; - - - public extern float remainingDistance - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern float baseOffset - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool isOnOffMeshLink - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void ActivateCurrentOffMeshLink (bool activated) ; - - public OffMeshLinkData currentOffMeshLinkData { get { return GetCurrentOffMeshLinkDataInternal(); } } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal OffMeshLinkData GetCurrentOffMeshLinkDataInternal () ; - - public OffMeshLinkData nextOffMeshLinkData { get { return GetNextOffMeshLinkDataInternal(); } } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal OffMeshLinkData GetNextOffMeshLinkDataInternal () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void CompleteOffMeshLink () ; - - public extern bool autoTraverseOffMeshLink - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool autoBraking - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool autoRepath - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool hasPath - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern bool pathPending - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern bool isPathStale - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern NavMeshPathStatus pathStatus - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public Vector3 pathEndPosition - { - get { Vector3 tmp; INTERNAL_get_pathEndPosition(out tmp); return tmp; } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_pathEndPosition (out Vector3 value) ; - - - public bool Warp (Vector3 newPosition) { - return INTERNAL_CALL_Warp ( this, ref newPosition ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_Warp (NavMeshAgent self, ref Vector3 newPosition); - public void Move (Vector3 offset) { - INTERNAL_CALL_Move ( this, ref offset ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_Move (NavMeshAgent self, ref Vector3 offset); - [System.Obsolete ("Set isStopped to true instead")] -public void Stop() - { - StopInternal(); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void StopInternal () ; - - [System.Obsolete ("Set isStopped to true instead")] -public void Stop(bool stopUpdates) - { - StopInternal(); - } - - - [System.Obsolete ("Set isStopped to false instead")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Resume () ; - - public extern bool isStopped - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void ResetPath () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool SetPath (NavMeshPath path) ; - - public NavMeshPath path { get { NavMeshPath path = new NavMeshPath(); CopyPathTo(path); return path; } set { if (value == null) throw new NullReferenceException(); SetPath(value); } } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void CopyPathTo (NavMeshPath path) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool FindClosestEdge (out NavMeshHit hit) ; - - public bool Raycast (Vector3 targetPosition, out NavMeshHit hit) { - return INTERNAL_CALL_Raycast ( this, ref targetPosition, out hit ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_Raycast (NavMeshAgent self, ref Vector3 targetPosition, out NavMeshHit hit); - public bool CalculatePath(Vector3 targetPosition, NavMeshPath path) - { - path.ClearCorners(); - return CalculatePathInternal(targetPosition, path); - } - - - private bool CalculatePathInternal (Vector3 targetPosition, NavMeshPath path) { - return INTERNAL_CALL_CalculatePathInternal ( this, ref targetPosition, path ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_CalculatePathInternal (NavMeshAgent self, ref Vector3 targetPosition, NavMeshPath path); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool SamplePathPosition (int areaMask, float maxDistance, out NavMeshHit hit) ; - - [System.Obsolete ("Use SetAreaCost instead.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetLayerCost (int layer, float cost) ; - - [System.Obsolete ("Use GetAreaCost instead.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetLayerCost (int layer) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetAreaCost (int areaIndex, float areaCost) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetAreaCost (int areaIndex) ; - - public Object navMeshOwner { get { return GetOwnerInternal(); } } - - - public extern int agentTypeID - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private Object GetOwnerInternal () ; - - [System.Obsolete ("Use areaMask instead.")] - public extern int walkableMask - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern int areaMask - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float speed - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float angularSpeed - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float acceleration - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool updatePosition - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool updateRotation - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool updateUpAxis - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float radius - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float height - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern ObstacleAvoidanceType obstacleAvoidanceType - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern int avoidancePriority - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool isOnNavMesh - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - -} - -} diff --git a/artifacts/generated/bindings_old/common/AI/NavMeshBindings.gen.cs b/artifacts/generated/bindings_old/common/AI/NavMeshBindings.gen.cs deleted file mode 100644 index 4953192a12..0000000000 --- a/artifacts/generated/bindings_old/common/AI/NavMeshBindings.gen.cs +++ /dev/null @@ -1,538 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - - -using System; -using System.Collections.Generic; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Scripting.APIUpdating; - -namespace UnityEngine.AI -{ - - -[MovedFrom("UnityEngine")] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct NavMeshHit -{ - private Vector3 m_Position; - private Vector3 m_Normal; - private float m_Distance; - private int m_Mask; - private int m_Hit; - - - public Vector3 position { get { return m_Position; } set { m_Position = value; } } - - - public Vector3 normal { get { return m_Normal; } set { m_Normal = value; } } - - - public float distance { get { return m_Distance; } set { m_Distance = value; } } - - - public int mask { get { return m_Mask; } set { m_Mask = value; } } - - - public bool hit { get { return m_Hit != 0; } set { m_Hit = value ? 1 : 0; } } -} - -[UsedByNativeCode] -[MovedFrom("UnityEngine")] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct NavMeshTriangulation -{ - public Vector3[] vertices; - public int[] indices; - public int[] areas; - - - [System.Obsolete ("Use areas instead.")] - public int[] layers { get { return areas; } } -} - -public sealed partial class NavMeshData : Object -{ - public NavMeshData() - { - Internal_Create(this, 0); - } - - - public NavMeshData(int agentTypeID) - { - Internal_Create(this, agentTypeID); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void Internal_Create ([Writable] NavMeshData mono, int agentTypeID) ; - - public Bounds sourceBounds - { - get { Bounds tmp; INTERNAL_get_sourceBounds(out tmp); return tmp; } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_sourceBounds (out Bounds value) ; - - - public Vector3 position - { - get { Vector3 tmp; INTERNAL_get_position(out tmp); return tmp; } - set { INTERNAL_set_position(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_position (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_position (ref Vector3 value) ; - - public Quaternion rotation - { - get { Quaternion tmp; INTERNAL_get_rotation(out tmp); return tmp; } - set { INTERNAL_set_rotation(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_rotation (out Quaternion value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_rotation (ref Quaternion value) ; - -} - -public struct NavMeshDataInstance - { - private int m_Handle; - public bool valid { get { return m_Handle != 0 && NavMesh.IsValidNavMeshDataHandle(m_Handle); } } - internal int id { get { return m_Handle; } set { m_Handle = value; } } - - public void Remove() - { - NavMesh.RemoveNavMeshDataInternal(id); - } - - public Object owner - { - get - { - return NavMesh.InternalGetOwner(id); - } - set - { - var ownerID = value != null ? value.GetInstanceID() : 0; - if (!NavMesh.InternalSetOwner(id, ownerID)) - Debug.LogError("Cannot set 'owner' on an invalid NavMeshDataInstance"); - } - } - } - - -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct NavMeshLinkData -{ - private Vector3 m_StartPosition; - private Vector3 m_EndPosition; - private float m_CostModifier; - private int m_Bidirectional; - private float m_Width; - private int m_Area; - private int m_AgentTypeID; - - - public Vector3 startPosition { get { return m_StartPosition; } set { m_StartPosition = value; } } - public Vector3 endPosition { get { return m_EndPosition; } set { m_EndPosition = value; } } - public float costModifier { get { return m_CostModifier; } set { m_CostModifier = value; } } - public bool bidirectional { get { return m_Bidirectional != 0; } set { m_Bidirectional = value ? 1 : 0; } } - public float width { get { return m_Width; } set { m_Width = value; } } - public int area { get { return m_Area; } set { m_Area = value; } } - public int agentTypeID { get { return m_AgentTypeID; } set { m_AgentTypeID = value; } } -} - -public struct NavMeshLinkInstance - { - private int m_Handle; - public bool valid { get { return m_Handle != 0 && NavMesh.IsValidLinkHandle(m_Handle); } } - internal int id { get { return m_Handle; } set { m_Handle = value; } } - - public void Remove() - { - NavMesh.RemoveLinkInternal(id); - } - - public Object owner - { - get - { - return NavMesh.InternalGetLinkOwner(id); - } - set - { - var ownerID = value != null ? value.GetInstanceID() : 0; - if (!NavMesh.InternalSetLinkOwner(id, ownerID)) - Debug.LogError("Cannot set 'owner' on an invalid NavMeshLinkInstance"); - } - } - } - - -public struct NavMeshQueryFilter - { - private const int AREA_COST_ELEMENT_COUNT = 32; - private int m_AreaMask; - private int m_AgentTypeID; - private float[] m_AreaCost; - internal float[] costs { get { return m_AreaCost; } } - - public int areaMask { get { return m_AreaMask; } set { m_AreaMask = value; } } - public int agentTypeID { get { return m_AgentTypeID; } set { m_AgentTypeID = value; } } - - public float GetAreaCost(int areaIndex) - { - if (m_AreaCost == null) - { - if (areaIndex < 0 || areaIndex >= AREA_COST_ELEMENT_COUNT) - { - var msg = string.Format("The valid range is [0:{0}]", AREA_COST_ELEMENT_COUNT - 1); - throw new IndexOutOfRangeException(msg); - } - return 1.0f; - } - return m_AreaCost[areaIndex]; - } - - public void SetAreaCost(int areaIndex, float cost) - { - if (m_AreaCost == null) - { - m_AreaCost = new float[AREA_COST_ELEMENT_COUNT]; - for (int j = 0; j < AREA_COST_ELEMENT_COUNT; ++j) - m_AreaCost[j] = 1.0f; - } - m_AreaCost[areaIndex] = cost; - } - - } - - -[MovedFrom("UnityEngine")] -public static partial class NavMesh -{ - public const int AllAreas = ~0; - - - public static bool Raycast (Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int areaMask) { - return INTERNAL_CALL_Raycast ( ref sourcePosition, ref targetPosition, out hit, areaMask ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_Raycast (ref Vector3 sourcePosition, ref Vector3 targetPosition, out NavMeshHit hit, int areaMask); - public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path) - { - path.ClearCorners(); - return CalculatePathInternal(sourcePosition, targetPosition, areaMask, path); - } - - - internal static bool CalculatePathInternal (Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path) { - return INTERNAL_CALL_CalculatePathInternal ( ref sourcePosition, ref targetPosition, areaMask, path ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_CalculatePathInternal (ref Vector3 sourcePosition, ref Vector3 targetPosition, int areaMask, NavMeshPath path); - public static bool FindClosestEdge (Vector3 sourcePosition, out NavMeshHit hit, int areaMask) { - return INTERNAL_CALL_FindClosestEdge ( ref sourcePosition, out hit, areaMask ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_FindClosestEdge (ref Vector3 sourcePosition, out NavMeshHit hit, int areaMask); - public static bool SamplePosition (Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask) { - return INTERNAL_CALL_SamplePosition ( ref sourcePosition, out hit, maxDistance, areaMask ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_SamplePosition (ref Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask); - [System.Obsolete ("Use SetAreaCost instead.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SetLayerCost (int layer, float cost) ; - - [System.Obsolete ("Use GetAreaCost instead.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float GetLayerCost (int layer) ; - - [System.Obsolete ("Use GetAreaFromName instead.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetNavMeshLayerFromName (string layerName) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SetAreaCost (int areaIndex, float cost) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float GetAreaCost (int areaIndex) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetAreaFromName (string areaName) ; - - public static NavMeshTriangulation CalculateTriangulation() - { - NavMeshTriangulation tri = (NavMeshTriangulation)TriangulateInternal(); - return tri; - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static object TriangulateInternal () ; - - [System.Obsolete ("use NavMesh.CalculateTriangulation () instead.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void Triangulate (out Vector3[] vertices, out int[] indices) ; - - [System.Obsolete ("AddOffMeshLinks has no effect and is deprecated.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void AddOffMeshLinks () ; - - [System.Obsolete ("RestoreNavMesh has no effect and is deprecated.")] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void RestoreNavMesh () ; - - public static float avoidancePredictionTime { get { return GetAvoidancePredictionTime(); } set { SetAvoidancePredictionTime(value); } } - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void SetAvoidancePredictionTime (float t) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static float GetAvoidancePredictionTime () ; - - public static int pathfindingIterationsPerFrame { get { return GetPathfindingIterationsPerFrame(); } set { SetPathfindingIterationsPerFrame(value); } } - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void SetPathfindingIterationsPerFrame (int iter) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static int GetPathfindingIterationsPerFrame () ; - - public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData) - { - if (navMeshData == null) throw new ArgumentNullException("navMeshData"); - - var handle = new NavMeshDataInstance(); - handle.id = AddNavMeshDataInternal(navMeshData); - return handle; - } - - - public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData, Vector3 position, Quaternion rotation) - { - if (navMeshData == null) throw new ArgumentNullException("navMeshData"); - - var handle = new NavMeshDataInstance(); - handle.id = AddNavMeshDataTransformedInternal(navMeshData, position, rotation); - return handle; - } - - - public static void RemoveNavMeshData(NavMeshDataInstance handle) - { - RemoveNavMeshDataInternal(handle.id); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static bool IsValidNavMeshDataHandle (int handle) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static bool IsValidLinkHandle (int handle) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static Object InternalGetOwner (int dataID) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static bool InternalSetOwner (int dataID, int ownerID) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static Object InternalGetLinkOwner (int linkID) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static bool InternalSetLinkOwner (int linkID, int ownerID) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static int AddNavMeshDataInternal (NavMeshData navMeshData) ; - - internal static int AddNavMeshDataTransformedInternal (NavMeshData navMeshData, Vector3 position, Quaternion rotation) { - return INTERNAL_CALL_AddNavMeshDataTransformedInternal ( navMeshData, ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static int INTERNAL_CALL_AddNavMeshDataTransformedInternal (NavMeshData navMeshData, ref Vector3 position, ref Quaternion rotation); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void RemoveNavMeshDataInternal (int handle) ; - - public static NavMeshLinkInstance AddLink(NavMeshLinkData link) - { - var handle = new NavMeshLinkInstance(); - handle.id = AddLinkInternal(link, Vector3.zero, Quaternion.identity); - return handle; - } - - - public static NavMeshLinkInstance AddLink(NavMeshLinkData link, Vector3 position, Quaternion rotation) - { - var handle = new NavMeshLinkInstance(); - handle.id = AddLinkInternal(link, position, rotation); - return handle; - } - - - public static void RemoveLink(NavMeshLinkInstance handle) - { - RemoveLinkInternal(handle.id); - } - - - internal static int AddLinkInternal (NavMeshLinkData link, Vector3 position, Quaternion rotation) { - return INTERNAL_CALL_AddLinkInternal ( ref link, ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static int INTERNAL_CALL_AddLinkInternal (ref NavMeshLinkData link, ref Vector3 position, ref Quaternion rotation); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void RemoveLinkInternal (int handle) ; - - public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, NavMeshQueryFilter filter) - { - return SamplePositionFilter(sourcePosition, out hit, maxDistance, filter.agentTypeID, filter.areaMask); - } - - - private static bool SamplePositionFilter (Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int type, int mask) { - return INTERNAL_CALL_SamplePositionFilter ( ref sourcePosition, out hit, maxDistance, type, mask ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_SamplePositionFilter (ref Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int type, int mask); - public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, NavMeshQueryFilter filter) - { - return FindClosestEdgeFilter(sourcePosition, out hit, filter.agentTypeID, filter.areaMask); - } - - - private static bool FindClosestEdgeFilter (Vector3 sourcePosition, out NavMeshHit hit, int type, int mask) { - return INTERNAL_CALL_FindClosestEdgeFilter ( ref sourcePosition, out hit, type, mask ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_FindClosestEdgeFilter (ref Vector3 sourcePosition, out NavMeshHit hit, int type, int mask); - public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, NavMeshQueryFilter filter) - { - return RaycastFilter(sourcePosition, targetPosition, out hit, filter.agentTypeID, filter.areaMask); - } - - - private static bool RaycastFilter (Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int type, int mask) { - return INTERNAL_CALL_RaycastFilter ( ref sourcePosition, ref targetPosition, out hit, type, mask ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_RaycastFilter (ref Vector3 sourcePosition, ref Vector3 targetPosition, out NavMeshHit hit, int type, int mask); - public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, NavMeshQueryFilter filter, NavMeshPath path) - { - path.ClearCorners(); - return CalculatePathFilterInternal(sourcePosition, targetPosition, path, filter.agentTypeID, filter.areaMask, filter.costs); - } - - - internal static bool CalculatePathFilterInternal (Vector3 sourcePosition, Vector3 targetPosition, NavMeshPath path, int type, int mask, float[] costs) { - return INTERNAL_CALL_CalculatePathFilterInternal ( ref sourcePosition, ref targetPosition, path, type, mask, costs ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_CalculatePathFilterInternal (ref Vector3 sourcePosition, ref Vector3 targetPosition, NavMeshPath path, int type, int mask, float[] costs); - public static NavMeshBuildSettings CreateSettings () { - NavMeshBuildSettings result; - INTERNAL_CALL_CreateSettings ( out result ); - return result; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_CreateSettings (out NavMeshBuildSettings value); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void RemoveSettings (int agentTypeID) ; - - public static NavMeshBuildSettings GetSettingsByID (int agentTypeID) { - NavMeshBuildSettings result; - INTERNAL_CALL_GetSettingsByID ( agentTypeID, out result ); - return result; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_GetSettingsByID (int agentTypeID, out NavMeshBuildSettings value); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetSettingsCount () ; - - public static NavMeshBuildSettings GetSettingsByIndex (int index) { - NavMeshBuildSettings result; - INTERNAL_CALL_GetSettingsByIndex ( index, out result ); - return result; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_GetSettingsByIndex (int index, out NavMeshBuildSettings value); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string GetSettingsNameFromID (int agentTypeID) ; - -} - - -} diff --git a/artifacts/generated/bindings_old/common/AI/NavMeshObstacleBindings.gen.cs b/artifacts/generated/bindings_old/common/AI/NavMeshObstacleBindings.gen.cs deleted file mode 100644 index 9411e35400..0000000000 --- a/artifacts/generated/bindings_old/common/AI/NavMeshObstacleBindings.gen.cs +++ /dev/null @@ -1,150 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Scripting.APIUpdating; - -namespace UnityEngine.AI -{ - - -[MovedFrom("UnityEngine")] -public enum NavMeshObstacleShape -{ - - Capsule = 0, - - Box = 1, -} - -[MovedFrom("UnityEngine")] -public sealed partial class NavMeshObstacle : Behaviour -{ - public extern float height - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float radius - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public Vector3 velocity - { - get { Vector3 tmp; INTERNAL_get_velocity(out tmp); return tmp; } - set { INTERNAL_set_velocity(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_velocity (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_velocity (ref Vector3 value) ; - - public extern bool carving - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool carveOnlyStationary - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float carvingMoveThreshold - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float carvingTimeToStationary - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern NavMeshObstacleShape shape - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public Vector3 center - { - get { Vector3 tmp; INTERNAL_get_center(out tmp); return tmp; } - set { INTERNAL_set_center(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_center (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_center (ref Vector3 value) ; - - public Vector3 size - { - get { Vector3 tmp; INTERNAL_get_size(out tmp); return tmp; } - set { INTERNAL_set_size(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_size (out Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_size (ref Vector3 value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void FitExtents () ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/AI/NavMeshPathBindings.gen.cs b/artifacts/generated/bindings_old/common/AI/NavMeshPathBindings.gen.cs deleted file mode 100644 index 7760ce066b..0000000000 --- a/artifacts/generated/bindings_old/common/AI/NavMeshPathBindings.gen.cs +++ /dev/null @@ -1,93 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Scripting.APIUpdating; - -namespace UnityEngine.AI -{ - - -[MovedFrom("UnityEngine")] -public enum NavMeshPathStatus -{ - - PathComplete = 0, - - PathPartial = 1, - - PathInvalid = 2 -} - -[StructLayout(LayoutKind.Sequential)] -[MovedFrom("UnityEngine")] -public sealed partial class NavMeshPath -{ - internal IntPtr m_Ptr; - internal Vector3[] m_corners; - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public NavMeshPath () ; - - [ThreadAndSerializationSafe ()] - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void DestroyNavMeshPath () ; - - ~NavMeshPath() - { - DestroyNavMeshPath(); - m_Ptr = IntPtr.Zero; - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public int GetCornersNonAlloc (Vector3[] results) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private Vector3[] CalculateCornersInternal () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void ClearCornersInternal () ; - - public void ClearCorners() - { - ClearCornersInternal(); - m_corners = null; - } - - - private void CalculateCorners() - { - if (m_corners == null) - m_corners = CalculateCornersInternal(); - } - - - public Vector3[] corners { get { CalculateCorners(); return m_corners; } } - - - public extern NavMeshPathStatus status - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - -} - -} diff --git a/artifacts/generated/bindings_old/common/AI/OffMeshLinkBindings.gen.cs b/artifacts/generated/bindings_old/common/AI/OffMeshLinkBindings.gen.cs deleted file mode 100644 index 4dfe1582cb..0000000000 --- a/artifacts/generated/bindings_old/common/AI/OffMeshLinkBindings.gen.cs +++ /dev/null @@ -1,164 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using UnityEngine.Scripting.APIUpdating; - -namespace UnityEngine.AI -{ - - -[MovedFrom("UnityEngine")] -public enum OffMeshLinkType -{ - - LinkTypeManual = 0, - - LinkTypeDropDown = 1, - - LinkTypeJumpAcross = 2 -} - -[MovedFrom("UnityEngine")] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct OffMeshLinkData -{ - private int m_Valid; - private int m_Activated; - private int m_InstanceID; - private OffMeshLinkType m_LinkType; - private Vector3 m_StartPos; - private Vector3 m_EndPos; - - - public bool valid { get { return m_Valid != 0; } } - - - public bool activated { get { return m_Activated != 0; } } - - - public OffMeshLinkType linkType { get { return m_LinkType; } } - - - public Vector3 startPos { get { return m_StartPos; } } - - - public Vector3 endPos { get { return m_EndPos; } } - - - public OffMeshLink offMeshLink { get { return GetOffMeshLinkInternal(m_InstanceID); } } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal OffMeshLink GetOffMeshLinkInternal (int instanceID) ; - -} - -[MovedFrom("UnityEngine")] -public sealed partial class OffMeshLink : Behaviour -{ - public extern bool activated - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool occupied - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern float costOverride - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool biDirectional - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void UpdatePositions () ; - - [System.Obsolete ("Use area instead.")] - public extern int navMeshLayer - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern int area - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool autoUpdatePositions - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern Transform startTransform - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern Transform endTransform - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - -} - -} diff --git a/artifacts/generated/bindings_old/common/AIEditor/NavMeshBuilderBindings.gen.cs b/artifacts/generated/bindings_old/common/AIEditor/NavMeshBuilderBindings.gen.cs deleted file mode 100644 index d062761191..0000000000 --- a/artifacts/generated/bindings_old/common/AIEditor/NavMeshBuilderBindings.gen.cs +++ /dev/null @@ -1,112 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using UnityEngine.SceneManagement; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; -using System.Collections.Generic; -using System.IO; -using UnityEditor.SceneManagement; -using UnityEditor; -using UnityEditor.AI; -using UnityScript.Scripting; -using UnityEngine.Scripting.APIUpdating; - -namespace UnityEditor.AI -{ -[MovedFrom("UnityEditor")] -public sealed partial class NavMeshBuilder -{ - public extern static UnityEngine.Object navMeshSettingsObject - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void BuildNavMesh () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void BuildNavMeshAsync () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void ClearAllNavMeshes () ; - - public extern static bool isRunning - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void Cancel () ; - - internal extern static Object sceneNavMeshData - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public static void BuildNavMeshForMultipleScenes(string[] paths) - { - if (paths.Length == 0) - return; - - for (int i = 0; i < paths.Length; i++) - { - for (int j = i + 1; j < paths.Length; j++) - { - if (paths[i] == paths[j]) - throw new System.Exception("No duplicate scene names are allowed"); - } - } - - if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) - return; - - if (!EditorSceneManager.OpenScene(paths[0]).IsValid()) - { - throw new System.Exception("Could not open scene: " + paths[0]); - } - for (int i = 1; i < paths.Length; ++i) - EditorSceneManager.OpenScene(paths[i], OpenSceneMode.Additive); - - NavMeshBuilder.BuildNavMesh(); - Object asset = NavMeshBuilder.sceneNavMeshData; - - for (int i = 0; i < paths.Length; ++i) - { - if (EditorSceneManager.OpenScene(paths[i]).IsValid()) - { - NavMeshBuilder.sceneNavMeshData = asset; - EditorSceneManager.SaveScene(SceneManager.GetActiveScene()); - } - } - - } - - -} - -} diff --git a/artifacts/generated/bindings_old/common/AIEditor/NavMeshVisualizationSettingsBindings.gen.cs b/artifacts/generated/bindings_old/common/AIEditor/NavMeshVisualizationSettingsBindings.gen.cs deleted file mode 100644 index 8d87e88879..0000000000 --- a/artifacts/generated/bindings_old/common/AIEditor/NavMeshVisualizationSettingsBindings.gen.cs +++ /dev/null @@ -1,190 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; -using System.Collections.Generic; -using System.IO; -using UnityEditor; -using UnityEditor.AI; -using UnityEngine.AI; -using UnityEngine.Scripting.APIUpdating; -using UnityScript.Scripting; - -namespace UnityEditor.AI -{ -[MovedFrom("UnityEditor")] -public sealed partial class NavMeshVisualizationSettings -{ - public extern static int showNavigation - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showNavMesh - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showHeightMesh - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showNavMeshPortals - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showNavMeshLinks - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showProximityGrid - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showHeightMeshBVTree - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool hasHeightMesh - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - internal extern static bool showAgentPath - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showAgentPathInfo - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showAgentNeighbours - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showAgentWalls - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showAgentAvoidance - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool showObstacleCarveHull - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - internal extern static bool hasPendingAgentDebugInfo - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - -} - -public static partial class NavMeshEditorHelpers -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void DrawBuildDebug (NavMeshData navMeshData, [uei.DefaultValue("NavMeshBuildDebugFlags.All")] NavMeshBuildDebugFlags flags ) ; - - [uei.ExcludeFromDocs] - public static void DrawBuildDebug (NavMeshData navMeshData) { - NavMeshBuildDebugFlags flags = NavMeshBuildDebugFlags.All; - DrawBuildDebug ( navMeshData, flags ); - } - -} - -} diff --git a/artifacts/generated/bindings_old/common/Animation/AnimationsBindings.gen.cs b/artifacts/generated/bindings_old/common/Animation/AnimationsBindings.gen.cs deleted file mode 100644 index fb73ee2d28..0000000000 --- a/artifacts/generated/bindings_old/common/Animation/AnimationsBindings.gen.cs +++ /dev/null @@ -1,675 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using UnityEngine.Bindings; -using UnityEngine.Playables; - -namespace UnityEngine -{ - - -internal enum AnimationEventSource -{ - NoSource = 0, - Legacy = 1, - Animator = 2, -} - -[System.Serializable] -[StructLayout(LayoutKind.Sequential)] -[RequiredByNativeCode] -public sealed partial class AnimationEvent -{ - - internal float m_Time; - internal string m_FunctionName; - internal string m_StringParameter; - internal Object m_ObjectReferenceParameter; - internal float m_FloatParameter; - internal int m_IntParameter; - - internal int m_MessageOptions; - internal AnimationEventSource m_Source; - internal AnimationState m_StateSender; - internal AnimatorStateInfo m_AnimatorStateInfo; - internal AnimatorClipInfo m_AnimatorClipInfo; - - - public AnimationEvent() - { - m_Time = 0.0f; - m_FunctionName = ""; - m_StringParameter = ""; - m_ObjectReferenceParameter = null; - m_FloatParameter = 0.0f; - m_IntParameter = 0; - m_MessageOptions = 0; - m_Source = AnimationEventSource.NoSource; - m_StateSender = null; - } - - - [System.Obsolete ("Use stringParameter instead")] - public string data { get { return m_StringParameter; } set { m_StringParameter = value; } } - - - public string stringParameter { get { return m_StringParameter; } set { m_StringParameter = value; } } - - - public float floatParameter { get { return m_FloatParameter; } set { m_FloatParameter = value; } } - - - public int intParameter { get { return m_IntParameter; } set { m_IntParameter = value; } } - - - public Object objectReferenceParameter { get { return m_ObjectReferenceParameter; } set { m_ObjectReferenceParameter = value; } } - - - public string functionName { get { return m_FunctionName; } set { m_FunctionName = value; } } - - - public float time { get { return m_Time; } set { m_Time = value; } } - - - public SendMessageOptions messageOptions { get { return (SendMessageOptions)m_MessageOptions; } set { m_MessageOptions = (int)value; } } - - - public bool isFiredByLegacy { get { return m_Source == AnimationEventSource.Legacy; } } - public bool isFiredByAnimator { get { return m_Source == AnimationEventSource.Animator; } } - - - public AnimationState animationState - { - get - { - if (!isFiredByLegacy) - Debug.LogError("AnimationEvent was not fired by Animation component, you shouldn't use AnimationEvent.animationState"); - return m_StateSender; - } - } - - - public AnimatorStateInfo animatorStateInfo - { - get - { - if (!isFiredByAnimator) - Debug.LogError("AnimationEvent was not fired by Animator component, you shouldn't use AnimationEvent.animatorStateInfo"); - return m_AnimatorStateInfo; - } - } - - - public AnimatorClipInfo animatorClipInfo - { - get - { - if (!isFiredByAnimator) - Debug.LogError("AnimationEvent was not fired by Animator component, you shouldn't use AnimationEvent.animatorClipInfo"); - return m_AnimatorClipInfo; - } - } - - - internal int GetHash() - { - unchecked - { - int hash = 0; - hash = functionName.GetHashCode(); - hash = 33 * hash + time.GetHashCode(); - return hash; - } - } - - -} - -public sealed partial class AnimationClip : Motion -{ - public void AddEvent(AnimationEvent evt) - { - if (evt == null) - throw new ArgumentNullException("evt"); - - AddEventInternal(evt); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void AddEventInternal (object evt) ; - - public AnimationEvent[] events - { - get - { - return (AnimationEvent[])GetEventsInternal(); - } - set - { - SetEventsInternal(value); - } - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void SetEventsInternal (System.Array value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal System.Array GetEventsInternal () ; - -} - -public enum PlayMode -{ - - StopSameLayer = 0, - - StopAll = 4, -} - -public enum QueueMode -{ - - CompleteOthers = 0, - - PlayNow = 2 -} - -public enum AnimationBlendMode -{ - - Blend = 0, - - Additive = 1 -} - -public enum AnimationPlayMode { Stop = 0, Queue = 1, Mix = 2 } - - -public enum AnimationCullingType -{ - - AlwaysAnimate = 0, - - BasedOnRenderers = 1, - - [System.Obsolete ("Enum member AnimatorCullingMode.BasedOnClipBounds has been deprecated. Use AnimationCullingType.AlwaysAnimate or AnimationCullingType.BasedOnRenderers instead")] - BasedOnClipBounds = 2, - - [System.Obsolete ("Enum member AnimatorCullingMode.BasedOnUserBounds has been deprecated. Use AnimationCullingType.AlwaysAnimate or AnimationCullingType.BasedOnRenderers instead")] - BasedOnUserBounds = 3 -} - -public sealed partial class Animation : Behaviour, IEnumerable -{ - public extern AnimationClip clip - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool playAutomatically - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern WrapMode wrapMode - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public void Stop () { - INTERNAL_CALL_Stop ( this ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_Stop (Animation self); - public void Stop(string name) { Internal_StopByName(name); } - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void Internal_StopByName (string name) ; - - public void Rewind(string name) { Internal_RewindByName(name); } - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void Internal_RewindByName (string name) ; - - public void Rewind () { - INTERNAL_CALL_Rewind ( this ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_Rewind (Animation self); - public void Sample () { - INTERNAL_CALL_Sample ( this ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_Sample (Animation self); - public extern bool isPlaying - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool IsPlaying (string name) ; - - public AnimationState this[string name] - { - get { return GetState(name); } - } - - - [uei.ExcludeFromDocs] -public bool Play () { - PlayMode mode = PlayMode.StopSameLayer; - return Play ( mode ); -} - -public bool Play( [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode ) { return PlayDefaultAnimation(mode); } - - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool Play (string animation, [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode ) ; - - [uei.ExcludeFromDocs] - public bool Play (string animation) { - PlayMode mode = PlayMode.StopSameLayer; - return Play ( animation, mode ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void CrossFade (string animation, [uei.DefaultValue("0.3F")] float fadeLength , [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode ) ; - - [uei.ExcludeFromDocs] - public void CrossFade (string animation, float fadeLength ) { - PlayMode mode = PlayMode.StopSameLayer; - CrossFade ( animation, fadeLength, mode ); - } - - [uei.ExcludeFromDocs] - public void CrossFade (string animation) { - PlayMode mode = PlayMode.StopSameLayer; - float fadeLength = 0.3F; - CrossFade ( animation, fadeLength, mode ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Blend (string animation, [uei.DefaultValue("1.0F")] float targetWeight , [uei.DefaultValue("0.3F")] float fadeLength ) ; - - [uei.ExcludeFromDocs] - public void Blend (string animation, float targetWeight ) { - float fadeLength = 0.3F; - Blend ( animation, targetWeight, fadeLength ); - } - - [uei.ExcludeFromDocs] - public void Blend (string animation) { - float fadeLength = 0.3F; - float targetWeight = 1.0F; - Blend ( animation, targetWeight, fadeLength ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public AnimationState CrossFadeQueued (string animation, [uei.DefaultValue("0.3F")] float fadeLength , [uei.DefaultValue("QueueMode.CompleteOthers")] QueueMode queue , [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode ) ; - - [uei.ExcludeFromDocs] - public AnimationState CrossFadeQueued (string animation, float fadeLength , QueueMode queue ) { - PlayMode mode = PlayMode.StopSameLayer; - return CrossFadeQueued ( animation, fadeLength, queue, mode ); - } - - [uei.ExcludeFromDocs] - public AnimationState CrossFadeQueued (string animation, float fadeLength ) { - PlayMode mode = PlayMode.StopSameLayer; - QueueMode queue = QueueMode.CompleteOthers; - return CrossFadeQueued ( animation, fadeLength, queue, mode ); - } - - [uei.ExcludeFromDocs] - public AnimationState CrossFadeQueued (string animation) { - PlayMode mode = PlayMode.StopSameLayer; - QueueMode queue = QueueMode.CompleteOthers; - float fadeLength = 0.3F; - return CrossFadeQueued ( animation, fadeLength, queue, mode ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public AnimationState PlayQueued (string animation, [uei.DefaultValue("QueueMode.CompleteOthers")] QueueMode queue , [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode ) ; - - [uei.ExcludeFromDocs] - public AnimationState PlayQueued (string animation, QueueMode queue ) { - PlayMode mode = PlayMode.StopSameLayer; - return PlayQueued ( animation, queue, mode ); - } - - [uei.ExcludeFromDocs] - public AnimationState PlayQueued (string animation) { - PlayMode mode = PlayMode.StopSameLayer; - QueueMode queue = QueueMode.CompleteOthers; - return PlayQueued ( animation, queue, mode ); - } - - public void AddClip(AnimationClip clip, string newName) { AddClip(clip, newName, Int32.MinValue, Int32.MaxValue); } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void AddClip (AnimationClip clip, string newName, int firstFrame, int lastFrame, [uei.DefaultValue("false")] bool addLoopFrame ) ; - - [uei.ExcludeFromDocs] - public void AddClip (AnimationClip clip, string newName, int firstFrame, int lastFrame) { - bool addLoopFrame = false; - AddClip ( clip, newName, firstFrame, lastFrame, addLoopFrame ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void RemoveClip (AnimationClip clip) ; - - public void RemoveClip(string clipName) { RemoveClip2(clipName); } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public int GetClipCount () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void RemoveClip2 (string clipName) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private bool PlayDefaultAnimation (PlayMode mode) ; - - [System.Obsolete ("use PlayMode instead of AnimationPlayMode.")] -public bool Play(AnimationPlayMode mode) { return PlayDefaultAnimation((PlayMode)mode); } - [System.Obsolete ("use PlayMode instead of AnimationPlayMode.")] -public bool Play(string animation, AnimationPlayMode mode) { return Play(animation, (PlayMode)mode); } - - - - public void SyncLayer (int layer) { - INTERNAL_CALL_SyncLayer ( this, layer ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_SyncLayer (Animation self, int layer); - public IEnumerator GetEnumerator() - { - return new Animation.Enumerator(this); - } - - - private sealed partial class Enumerator : IEnumerator - { - - private Animation m_Outer; - private int m_CurrentIndex = -1; - - internal Enumerator(Animation outer) { m_Outer = outer; } - public object Current - { - get { return m_Outer.GetStateAtIndex(m_CurrentIndex); } - } - - public bool MoveNext() - { - int childCount = m_Outer.GetStateCount(); - m_CurrentIndex++; - return m_CurrentIndex < childCount; - } - - public void Reset() { m_CurrentIndex = -1; } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal AnimationState GetState (string name) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal AnimationState GetStateAtIndex (int index) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal int GetStateCount () ; - - public AnimationClip GetClip(string name) - { - AnimationState state = GetState(name); - if (state) - return state.clip; - else - return null; - } - - - public extern bool animatePhysics - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [System.Obsolete ("Use cullingType instead")] - public extern bool animateOnlyIfVisible - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AnimationCullingType cullingType - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public Bounds localBounds - { - get { Bounds tmp; INTERNAL_get_localBounds(out tmp); return tmp; } - set { INTERNAL_set_localBounds(ref value); } - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_get_localBounds (out Bounds value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void INTERNAL_set_localBounds (ref Bounds value) ; - -} - -[UsedByNativeCode] -public sealed partial class AnimationState : TrackedReference -{ - public extern bool enabled - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float weight - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern WrapMode wrapMode - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float time - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float normalizedTime - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float speed - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float normalizedSpeed - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern float length - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern int layer - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AnimationClip clip - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void AddMixingTransform (Transform mix, [uei.DefaultValue("true")] bool recursive ) ; - - [uei.ExcludeFromDocs] - public void AddMixingTransform (Transform mix) { - bool recursive = true; - AddMixingTransform ( mix, recursive ); - } - - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void RemoveMixingTransform (Transform mix) ; - - public extern string name - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AnimationBlendMode blendMode - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Audio/AudioMixerBindings.gen.cs b/artifacts/generated/bindings_old/common/Audio/AudioMixerBindings.gen.cs deleted file mode 100644 index 02ff0265ea..0000000000 --- a/artifacts/generated/bindings_old/common/Audio/AudioMixerBindings.gen.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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using UnityEngine; -using System; - -namespace UnityEngine.Audio -{ - - -public enum AudioMixerUpdateMode -{ - Normal = 0, - UnscaledTime = 1 -} - -[ExcludeFromPreset] -[ExcludeFromObjectFactory] -public partial class AudioMixer : Object -{ - - internal AudioMixer() {} - - - public extern AudioMixerGroup outputAudioMixerGroup - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public AudioMixerGroup[] FindMatchingGroups (string subPath) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public AudioMixerSnapshot FindSnapshot (string name) ; - - void TransitionToSnapshot(AudioMixerSnapshot snapshot, float timeToReach) - { - if (snapshot == null) - throw new ArgumentException("null Snapshot passed to AudioMixer.TransitionToSnapshot of AudioMixer '" + name + "'"); - - if (snapshot.audioMixer != this) - throw new ArgumentException("Snapshot '" + snapshot.name + "' passed to AudioMixer.TransitionToSnapshot is not a snapshot from AudioMixer '" + name + "'"); - - snapshot.TransitionTo(timeToReach); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void TransitionToSnapshots (AudioMixerSnapshot[] snapshots, float[] weights, float timeToReach) ; - - public extern AudioMixerUpdateMode updateMode - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool SetFloat (string name, float value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool ClearFloat (string name) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool GetFloat (string name, out float value) ; - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Cloth/ClothBindings.gen.cs b/artifacts/generated/bindings_old/common/Cloth/ClothBindings.gen.cs deleted file mode 100644 index 17ceace74a..0000000000 --- a/artifacts/generated/bindings_old/common/Cloth/ClothBindings.gen.cs +++ /dev/null @@ -1,182 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; - -#pragma warning disable 649 - -namespace UnityEngine -{ -[UsedByNativeCode] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct ClothSphereColliderPair -{ - public SphereCollider first - { get { return m_First; } set { m_First = value; } } - private SphereCollider m_First; - - - public SphereCollider second - { get { return m_Second; } set { m_Second = value; } } - private SphereCollider m_Second; - - public ClothSphereColliderPair(SphereCollider a) - { - m_First = null; - m_Second = null; - - first = a; - second = null; - } - - public ClothSphereColliderPair(SphereCollider a, SphereCollider b) - { - m_First = null; - m_Second = null; - - first = a; - second = b; - } - - -} - -[RequireComponent(typeof(Transform), typeof(SkinnedMeshRenderer))] -[NativeClass("Unity::Cloth")] -public sealed partial class Cloth : Component -{ - [System.Obsolete ("Deprecated. Cloth.selfCollisions is no longer supported since Unity 5.0.", true)] - public extern bool selfCollision - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern Vector3[] vertices - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern Vector3[] normals - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [Obsolete("useContinuousCollision is no longer supported, use enableContinuousCollision instead")] - public extern float useContinuousCollision - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public void ClearTransformMotion () { - INTERNAL_CALL_ClearTransformMotion ( this ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_ClearTransformMotion (Cloth self); - public extern ClothSkinningCoefficient[] coefficients - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetEnabledFading (bool enabled, [uei.DefaultValue("0.5f")] float interpolationTime ) ; - - [uei.ExcludeFromDocs] - public void SetEnabledFading (bool enabled) { - float interpolationTime = 0.5f; - SetEnabledFading ( enabled, interpolationTime ); - } - - [System.Obsolete ("Parameter solverFrequency is obsolete and no longer supported. Please use clothSolverFrequency instead.")] - public bool solverFrequency - { - get { return clothSolverFrequency > 0.0f ? true : false; } - set { clothSolverFrequency = value == true ? 120f : 0.0f; } - } - - - public extern CapsuleCollider[] capsuleColliders - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern ClothSphereColliderPair[] sphereColliders - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void GetVirtualParticleIndicesMono (object indicesOutList) ; - - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void SetVirtualParticleIndicesMono (object indicesInList) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void GetVirtualParticleWeightsMono (object weightsOutList) ; - - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void SetVirtualParticleWeightsMono (object weightsInList) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void GetSelfAndInterCollisionIndicesMono (object indicesOutList) ; - - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal void SetSelfAndInterCollisionIndicesMono (object indicesInList) ; - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AssetModificationProcessorBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AssetModificationProcessorBindings.gen.cs deleted file mode 100644 index 207c7629ac..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AssetModificationProcessorBindings.gen.cs +++ /dev/null @@ -1,23 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; -[System.Obsolete ("Use UnityEditor.AssetModificationProcessor")] -public partial class AssetModificationProcessor -{ -} - - -namespace UnityEditor -{ - - -public partial class AssetModificationProcessor -{ -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AssetStoreBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AssetStoreBindings.gen.cs deleted file mode 100644 index d1145c6f66..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AssetStoreBindings.gen.cs +++ /dev/null @@ -1,36 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using UnityEditor; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditorInternal -{ - - -public sealed partial class AssetStore -{ - public static void Open(string assetStoreURL) - { - if (assetStoreURL != "") - AssetStoreWindow.OpenURL(assetStoreURL); - else - AssetStoreWindow.Init(); - } - - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AssetStoreContextBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AssetStoreContextBindings.gen.cs deleted file mode 100644 index 579dfbef35..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AssetStoreContextBindings.gen.cs +++ /dev/null @@ -1,44 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -using UnityEditorInternal; - - -namespace UnityEditor -{ - - -internal sealed partial class AssetStoreContext -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SessionSetString (string key, string value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string SessionGetString (string key) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SessionRemoveString (string key) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool SessionHasString (string key) ; - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AssetStoreToolUtilsBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AssetStoreToolUtilsBindings.gen.cs deleted file mode 100644 index f83d049381..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AssetStoreToolUtilsBindings.gen.cs +++ /dev/null @@ -1,36 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngineInternal; -using UnityEditorInternal; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.IO; - -namespace UnityEditorInternal -{ - - -public sealed partial class AssetStoreToolUtils -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool BuildAssetStoreAssetBundle (Object targetObject, string targetPath) ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AssetStoreUtilsBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AssetStoreUtilsBindings.gen.cs deleted file mode 100644 index bc3ffc4d82..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AssetStoreUtilsBindings.gen.cs +++ /dev/null @@ -1,86 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngineInternal; -using UnityEditorInternal; -using System.Security.Cryptography; -using System.Text; -using System.Text.RegularExpressions; -using System.IO; - -namespace UnityEditor -{ - - -internal sealed partial class AssetStoreUtils -{ - private const string kAssetStoreUrl = "https://shawarma.unity3d.com"; - - - public delegate void DownloadDoneCallback(string package_id, string message, int bytes, int total); - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void Download (string id, string url, string[] destination, string key, string jsonData, bool resumeOK, [uei.DefaultValue("null")] DownloadDoneCallback doneCallback ) ; - - [uei.ExcludeFromDocs] - public static void Download (string id, string url, string[] destination, string key, string jsonData, bool resumeOK) { - DownloadDoneCallback doneCallback = null; - Download ( id, url, destination, key, jsonData, resumeOK, doneCallback ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string CheckDownload (string id, string url, string[] destination, string key) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void RegisterDownloadDelegate (ScriptableObject d) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void UnRegisterDownloadDelegate (ScriptableObject d) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string GetLoaderPath () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void UpdatePreloading () ; - - public static string GetOfflinePath() - { - return System.Uri.EscapeUriString(EditorApplication.applicationContentsPath + "/Resources/offline.html"); - } - - - public static string GetAssetStoreUrl() - { - return kAssetStoreUrl; - } - - - public static string GetAssetStoreSearchUrl() - { - return GetAssetStoreUrl().Replace("https", "http"); - } - - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AudioMixerControllerBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AudioMixerControllerBindings.gen.cs deleted file mode 100644 index 67019dbd80..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AudioMixerControllerBindings.gen.cs +++ /dev/null @@ -1,204 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using UnityEngine.Audio; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections.Generic; - -namespace UnityEditor.Audio -{ - - -[RequiredByNativeCode] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -internal partial struct ExposedAudioParameter -{ - public GUID guid; - public string name; -} - -[RequiredByNativeCode] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -internal partial struct MixerGroupView -{ - public GUID[] guids; - public string name; -} - -internal sealed partial class AudioMixerController : AudioMixer -{ - public AudioMixerController() - { - Internal_CreateAudioMixerController(this); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void Internal_CreateAudioMixerController (AudioMixerController mono) ; - - private static void GetGroupsRecurse(AudioMixerGroupController group, List groups) - { - groups.Add(group); - - AudioMixerGroupController[] children = group.children; - for (int i = 0; i < children.Length; i++) - GetGroupsRecurse(children[i], groups); - } - - - public AudioMixerGroupController[] allGroups - { - get - { - List groups = new List(); - GetGroupsRecurse(masterGroup, groups); - return groups.ToArray(); - } - } - - - public extern int numExposedParameters - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern ExposedAudioParameter[] exposedParameters - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AudioMixerGroupController masterGroup - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AudioMixerSnapshot startSnapshot - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AudioMixerSnapshotController TargetSnapshot - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AudioMixerSnapshotController[] snapshots - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public int GetGroupVUInfo (GUID group, bool fader, ref float[] vuLevel, ref float[] vuPeak) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void UpdateMuteSolo () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void UpdateBypass () ; - - [System.NonSerialized] public int m_HighlightEffectIndex = -1; - - - [System.NonSerialized] private List m_CachedSelection = null; - public List CachedSelection - { - get - { - if (m_CachedSelection == null) - m_CachedSelection = new List(); - return m_CachedSelection; - } - } - - - public extern int currentViewIndex - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool CurrentViewContainsGroup (GUID group) ; - - public extern MixerGroupView[] views - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static bool CheckForCyclicReferences (AudioMixer mixer, AudioMixerGroup group) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static float GetMaxVolume () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static float GetVolumeSplitPoint () ; - - public extern bool isSuspended - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool EditingTargetSnapshot () ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AudioMixerDescriptionBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AudioMixerDescriptionBindings.gen.cs deleted file mode 100644 index f16d1f4c09..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AudioMixerDescriptionBindings.gen.cs +++ /dev/null @@ -1,58 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; - -namespace UnityEditor.Audio -{ - - -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -internal partial struct MixerParameterDefinition -{ - public string name; - public string description; - public string units; - public float displayScale; - public float displayExponent; - public float minRange; - public float maxRange; - public float defaultValue; -} - -internal sealed partial class MixerEffectDefinitions -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void ClearDefinitionsRuntime () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void AddDefinitionRuntime (string name, MixerParameterDefinition[] parameters) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string[] GetAudioEffectNames () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static MixerParameterDefinition[] GetAudioEffectParameterDesc (string effectName) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool EffectCanBeSidechainTarget (AudioMixerEffectController effect) ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AudioMixerEffectControllerBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AudioMixerEffectControllerBindings.gen.cs deleted file mode 100644 index 3d7ea6b638..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AudioMixerEffectControllerBindings.gen.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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; - -namespace UnityEditor.Audio -{ -[RequiredByNativeCode] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -internal partial struct MixerEffectParameter -{ - public string parameterName; - public GUID GUID; -} - -internal sealed partial class AudioMixerEffectController : Object -{ - int m_LastCachedGroupDisplayNameID; - string m_DisplayName; - - - public AudioMixerEffectController(string name) - { - Internal_CreateAudioMixerEffectController(this, name); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void Internal_CreateAudioMixerEffectController (AudioMixerEffectController mono, string name) ; - - public extern GUID effectID - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern string effectName - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public bool IsSend() { return effectName == "Send"; } - public bool IsReceive() { return effectName == "Receive"; } - public bool IsDuckVolume() { return effectName == "Duck Volume"; } - public bool IsAttenuation() { return effectName == "Attenuation"; } - public bool DisallowsBypass() { return IsSend() || IsReceive() || IsDuckVolume() || IsAttenuation(); } - - - public void ClearCachedDisplayName() {m_DisplayName = null; } - - - public string GetDisplayString(Dictionary effectMap) - { - AudioMixerGroupController group = effectMap[this]; - if (group.GetInstanceID() != m_LastCachedGroupDisplayNameID || m_DisplayName == null) - { - m_DisplayName = group.GetDisplayString() + AudioMixerController.s_GroupEffectDisplaySeperator + AudioMixerController.FixNameForPopupMenu(effectName); - m_LastCachedGroupDisplayNameID = group.GetInstanceID(); - } - return m_DisplayName; - } - - - public string GetSendTargetDisplayString(Dictionary effectMap) { return (sendTarget != null) ? sendTarget.GetDisplayString(effectMap) : string.Empty; } - - - public extern AudioMixerEffectController sendTarget - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool enableWetMix - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool bypass - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void PreallocateGUIDs () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public GUID GetGUIDForMixLevel () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetValueForMixLevel (AudioMixerController controller, AudioMixerSnapshotController snapshot) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetValueForMixLevel (AudioMixerController controller, AudioMixerSnapshotController snapshot, float value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public GUID GetGUIDForParameter (string parameterName) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetValueForParameter (AudioMixerController controller, AudioMixerSnapshotController snapshot, string parameterName) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetValueForParameter (AudioMixerController controller, AudioMixerSnapshotController snapshot, string parameterName, float value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool GetFloatBuffer (AudioMixerController controller, string name, out float[] data, int numsamples) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetCPUUsage (AudioMixerController controller) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool ContainsParameterGUID (GUID guid) ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AudioMixerGroupControllerBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AudioMixerGroupControllerBindings.gen.cs deleted file mode 100644 index 8f177132a4..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AudioMixerGroupControllerBindings.gen.cs +++ /dev/null @@ -1,142 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using UnityEngine.Audio; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; - -namespace UnityEditor.Audio -{ - - -internal sealed partial class AudioMixerGroupController : AudioMixerGroup -{ - public AudioMixerGroupController(AudioMixer owner) - { - Internal_CreateAudioMixerGroupController(this, owner); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void Internal_CreateAudioMixerGroupController (AudioMixerGroupController mono, AudioMixer owner) ; - - public extern GUID groupID - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern int userColorIndex - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AudioMixerController controller - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void PreallocateGUIDs () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public GUID GetGUIDForVolume () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetValueForVolume (AudioMixerController controller, AudioMixerSnapshotController snapshot) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetValueForVolume (AudioMixerController controller, AudioMixerSnapshotController snapshot, float value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public GUID GetGUIDForPitch () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public float GetValueForPitch (AudioMixerController controller, AudioMixerSnapshotController snapshot) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetValueForPitch (AudioMixerController controller, AudioMixerSnapshotController snapshot, float value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool HasDependentMixers () ; - - public extern AudioMixerGroupController[] children - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern AudioMixerEffectController[] effects - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool mute - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool solo - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern bool bypassEffects - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AudioMixerSnapshotControllerBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AudioMixerSnapshotControllerBindings.gen.cs deleted file mode 100644 index 86ec10351c..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AudioMixerSnapshotControllerBindings.gen.cs +++ /dev/null @@ -1,88 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using UnityEngine.Audio; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; - -namespace UnityEditor.Audio -{ - - -internal enum ParameterTransitionType -{ - Lerp = 0, - Smoothstep = 1, - Squared = 2, - SquareRoot = 3, - BrickwallStart = 4, - BrickwallEnd = 5 -} - -internal sealed partial class AudioMixerSnapshotController : AudioMixerSnapshot -{ - public AudioMixerSnapshotController(AudioMixer owner) - { - Internal_CreateAudioMixerSnapshotController(this, owner); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void Internal_CreateAudioMixerSnapshotController (AudioMixerSnapshotController mono, AudioMixer owner) ; - - public extern GUID snapshotID - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public void SetValue (GUID guid, float value) { - INTERNAL_CALL_SetValue ( this, guid, value ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_SetValue (AudioMixerSnapshotController self, GUID guid, float value); - public bool GetValue (GUID guid, out float value) { - return INTERNAL_CALL_GetValue ( this, guid, out value ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_GetValue (AudioMixerSnapshotController self, GUID guid, out float value); - public void SetTransitionTypeOverride (GUID guid, ParameterTransitionType type) { - INTERNAL_CALL_SetTransitionTypeOverride ( this, guid, type ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_SetTransitionTypeOverride (AudioMixerSnapshotController self, GUID guid, ParameterTransitionType type); - public bool GetTransitionTypeOverride (GUID guid, out ParameterTransitionType type) { - return INTERNAL_CALL_GetTransitionTypeOverride ( this, guid, out type ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static bool INTERNAL_CALL_GetTransitionTypeOverride (AudioMixerSnapshotController self, GUID guid, out ParameterTransitionType type); - public void ClearTransitionTypeOverride (GUID guid) { - INTERNAL_CALL_ClearTransitionTypeOverride ( this, guid ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_ClearTransitionTypeOverride (AudioMixerSnapshotController self, GUID guid); -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/AudioUtilBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/AudioUtilBindings.gen.cs deleted file mode 100644 index 5c10d6ea0b..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/AudioUtilBindings.gen.cs +++ /dev/null @@ -1,215 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Reflection; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using UnityScript.Scripting; -using UnityEditor; - -namespace UnityEditor -{ - - -internal sealed partial class AudioUtil -{ - public extern static bool resetAllAudioClipPlayCountsOnPlay - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void PlayClip (AudioClip clip, [uei.DefaultValue("0")] int startSample , [uei.DefaultValue("false")] bool loop ) ; - - [uei.ExcludeFromDocs] - public static void PlayClip (AudioClip clip, int startSample ) { - bool loop = false; - PlayClip ( clip, startSample, loop ); - } - - [uei.ExcludeFromDocs] - public static void PlayClip (AudioClip clip) { - bool loop = false; - int startSample = 0; - PlayClip ( clip, startSample, loop ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void StopClip (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void PauseClip (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void ResumeClip (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void LoopClip (AudioClip clip, bool on) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool IsClipPlaying (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void StopAllClips () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float GetClipPosition (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetClipSamplePosition (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SetClipSamplePosition (AudioClip clip, int iSamplePosition) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetSampleCount (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetChannelCount (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetBitRate (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetBitsPerSample (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetFrequency (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetSoundSize (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static AudioCompressionFormat GetSoundCompressionFormat (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static AudioCompressionFormat GetTargetPlatformSoundCompressionFormat (AudioClip clip) ; - - public extern static bool canUseSpatializerEffect - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string[] GetAmbisonicDecoderPluginNames () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool HasPreview (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static AudioImporter GetImporterFromClip (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float[] GetMinMaxData (AudioImporter importer) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static double GetDuration (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetFMODMemoryAllocated () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float GetFMODCPUUsage () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool IsMovieAudio (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool IsTrackerFile (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetMusicChannelCount (AudioClip clip) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static AnimationCurve GetLowpassCurve (AudioLowPassFilter lowPassFilter) ; - - public static Vector3 GetListenerPos () { - Vector3 result; - INTERNAL_CALL_GetListenerPos ( out result ); - return result; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_GetListenerPos (out Vector3 value); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void UpdateAudio () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SetListenerTransform (Transform t) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool HasAudioCallback (MonoBehaviour behaviour) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetCustomFilterChannelCount (MonoBehaviour behaviour) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetCustomFilterProcessTime (MonoBehaviour behaviour) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float GetCustomFilterMaxIn (MonoBehaviour behaviour, int channel) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static float GetCustomFilterMaxOut (MonoBehaviour behaviour, int channel) ; - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Editor/FrameDebuggerBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/FrameDebuggerBindings.gen.cs deleted file mode 100644 index 0082471c02..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/FrameDebuggerBindings.gen.cs +++ /dev/null @@ -1,117 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; - -namespace UnityEditorInternal -{ - - -internal sealed partial class FrameDebuggerUtility -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void SetEnabled (bool enabled, int remotePlayerGUID) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool IsLocalEnabled () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static bool IsRemoteEnabled () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static int GetRemotePlayerGUID () ; - - public extern static bool receivingRemoteFrameEventData - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern static bool locallySupported - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern static int count - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern static int limit - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static int eventsHash - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public extern static uint eventDataHash - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - } - - public static void SetRenderTargetDisplayOptions (int rtIndex, Vector4 channels, float blackLevel, float whiteLevel) { - INTERNAL_CALL_SetRenderTargetDisplayOptions ( rtIndex, ref channels, blackLevel, whiteLevel ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_SetRenderTargetDisplayOptions (int rtIndex, ref Vector4 channels, float blackLevel, float whiteLevel); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static FrameDebuggerEvent[] GetFrameEvents () ; - - public static bool GetFrameEventData(int index, out FrameDebuggerEventData frameDebuggerEventData) - { - GetFrameEventDataInternal(out frameDebuggerEventData); - return frameDebuggerEventData.frameEventIndex == index; - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private static void GetFrameEventDataInternal (out FrameDebuggerEventData frameDebuggerEventData) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string GetFrameEventInfoName (int index) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static GameObject GetFrameEventGameObject (int index) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static string[] GetBatchBreakCauseStrings () ; - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Editor/HardwareBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/HardwareBindings.gen.cs deleted file mode 100644 index 320b370185..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/HardwareBindings.gen.cs +++ /dev/null @@ -1,154 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; - - -namespace UnityEditor.Hardware -{ - - - -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct UsbDevice -{ - readonly public int vendorId; - readonly public int productId; - readonly public int revision; - readonly public string udid; - readonly public string name; - - - public override string ToString() - { - return name + " (udid:" + udid + ", vid: " + vendorId.ToString("X4") + ", pid: " + productId.ToString("X4") + ", rev: " + revision.ToString("X4") + ")"; - } - - -} - -public sealed partial class Usb -{ - public delegate void OnDevicesChangedHandler(UsbDevice[] devices); - - - public static event OnDevicesChangedHandler DevicesChanged; - - - public static void OnDevicesChanged(UsbDevice[] devices) - { - if ((DevicesChanged != null) && (devices != null)) - DevicesChanged(devices); - } - - -} - -public sealed partial class DevDeviceList -{ - public delegate void OnChangedHandler(); - - - public static event OnChangedHandler Changed; - - - public static void OnChanged() - { - if (Changed != null) - Changed(); - } - - - public static bool FindDevice(string deviceId, out DevDevice device) - { - foreach (var d in GetDevices()) - { - if (d.id == deviceId) - { - device = d; - return true; - } - } - - device = new DevDevice(); - return false; - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static DevDevice[] GetDevices () ; - - internal static void Update(string target, DevDevice[] devices) - { - UpdateInternal(target, devices); - OnChanged(); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void UpdateInternal (string target, DevDevice[] devices) ; - -} - -public enum DevDeviceState -{ - Disconnected = 0, - Connected = 1, -} - -[Flags] -public enum DevDeviceFeatures -{ - None = 0, - PlayerConnection = 1 << 0, - RemoteConnection = 1 << 1, -} - -[RequiredByNativeCode] -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -public partial struct DevDevice -{ - readonly public string id; - readonly public string name; - readonly public string type; - readonly public string module; - readonly public DevDeviceState state; - readonly public DevDeviceFeatures features; - - - public bool isConnected { get { return state == DevDeviceState.Connected; } } - - - public static DevDevice none { get { return new DevDevice("None", "None", "none", "internal", DevDeviceState.Disconnected, DevDeviceFeatures.None); } } - - - public override string ToString() - { - return name + " (id:" + id + ", type: " + type + ", module: " + module + ", state: " + state + ", features: " + features + ")"; - } - - - public DevDevice(string id, string name, string type, string module, DevDeviceState state, DevDeviceFeatures features) - { - this.id = id; - this.name = name; - this.type = type; - this.module = module; - this.state = state; - this.features = features; - } - - -} - - -} diff --git a/artifacts/generated/bindings_old/common/Editor/LODUtilityBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/LODUtilityBindings.gen.cs deleted file mode 100644 index 9264ba2eef..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/LODUtilityBindings.gen.cs +++ /dev/null @@ -1,69 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; - -namespace UnityEditor -{ -[System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] -internal partial struct LODVisualizationInformation -{ - public int triangleCount; - public int vertexCount; - public int rendererCount; - public int submeshCount; - - - public int activeLODLevel; - public float activeLODFade; - public float activeDistance; - public float activeRelativeScreenSize; - public float activePixelSize; - public float worldSpaceSize; -} - -public sealed partial class LODUtility -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static LODVisualizationInformation CalculateVisualizationData (Camera camera, LODGroup group, int lodLevel) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static float CalculateDistance (Camera camera, float relativeScreenHeight, LODGroup group) ; - - internal static Vector3 CalculateWorldReferencePoint (LODGroup group) { - Vector3 result; - INTERNAL_CALL_CalculateWorldReferencePoint ( group, out result ); - return result; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_CalculateWorldReferencePoint (LODGroup group, out Vector3 value); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static bool NeedUpdateLODGroupBoundingBox (LODGroup group) ; - - public static void CalculateLODGroupBoundingBox(LODGroup group) - { - if (group == null) - throw new ArgumentNullException("group"); - group.RecalculateBounds(); - } - - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/ModuleMetadataBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/ModuleMetadataBindings.gen.cs index 91ff96bb6b..51484d3ada 100644 --- a/artifacts/generated/bindings_old/common/Editor/ModuleMetadataBindings.gen.cs +++ b/artifacts/generated/bindings_old/common/Editor/ModuleMetadataBindings.gen.cs @@ -54,6 +54,14 @@ public static UnityType[] GetModuleTypes(string moduleName) [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] extern internal static ModuleIncludeSetting GetModuleIncludeSettingForObject (Object o) ; + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern internal static string GetExcludingModuleForObject (Object o) ; + + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern internal static string GetExcludingModule (string module) ; + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] extern internal static uint[] GetModuleTypeIndices (string moduleName) ; diff --git a/artifacts/generated/bindings_old/common/Editor/PlayerSettingsVRGoogleBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/PlayerSettingsVRGoogleBindings.gen.cs deleted file mode 100644 index 0de816ac2a..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/PlayerSettingsVRGoogleBindings.gen.cs +++ /dev/null @@ -1,125 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using System.Linq; -using System.Text.RegularExpressions; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections.Generic; - -using UnityEngine; - -namespace UnityEditor.XR.Daydream -{ -public enum SupportedHeadTracking -{ - - ThreeDoF = 0, - - SixDoF = 1 -} - -} - -namespace UnityEditor -{ -public sealed partial class PlayerSettings : UnityEngine.Object -{ - public static partial class VRCardboard - { - public extern static int depthFormat - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - } - - public static partial class VRDaydream - { - public extern static Texture2D daydreamIcon - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static Texture2D daydreamIconBackground - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static int depthFormat - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static XR.Daydream.SupportedHeadTracking minimumSupportedHeadTracking - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static XR.Daydream.SupportedHeadTracking maximumSupportedHeadTracking - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static bool enableVideoSurface - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - public extern static bool enableVideoSurfaceProtectedMemory - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - } - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/SpritesEditorBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/SpritesEditorBindings.gen.cs deleted file mode 100644 index 0adf35af41..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/SpritesEditorBindings.gen.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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using UnityEngine; -using System; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; - -namespace UnityEditor.Sprites -{ -public sealed partial class SpriteUtility -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static Texture2D GetSpriteTexture (Sprite sprite, bool getAtlasData) ; - - [System.Obsolete ("Use Sprite.vertices API instead. This data is the same for packed and unpacked sprites.")] -static public Vector2[] GetSpriteMesh(Sprite sprite, bool getAtlasData) - { - return sprite.vertices; - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static Vector2[] GetSpriteUVs (Sprite sprite, bool getAtlasData) ; - - [System.Obsolete ("Use Sprite.triangles API instead. This data is the same for packed and unpacked sprites.")] -static public UInt16[] GetSpriteIndices(Sprite sprite, bool getAtlasData) - { - return sprite.triangles; - } - - - internal static void GenerateOutline (Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths) { - INTERNAL_CALL_GenerateOutline ( texture, ref rect, detail, alphaTolerance, holeDetection, out paths ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_GenerateOutline (Texture2D texture, ref Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void GenerateOutlineFromSprite (Sprite sprite, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static Vector2[] GeneratePolygonOutlineVerticesOfSize (int sides, int width, int height) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void CreateSpritePolygonAssetAtPath (string pathName, int sides) ; - -} - -[System.Obsolete ("Use UnityEditor.Sprites.SpriteUtility instead (UnityUpgradable)", true)] -public sealed partial class DataUtility -{ -} - -} - -namespace UnityEditorInternal -{ -public sealed partial class InternalSpriteUtility -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static Rect[] GenerateAutomaticSpriteRectangles (Texture2D texture, int minRectSize, int extrudeSize) ; - - public static Rect[] GenerateGridSpriteRectangles (Texture2D texture, Vector2 offset, Vector2 size, Vector2 padding) { - return INTERNAL_CALL_GenerateGridSpriteRectangles ( texture, ref offset, ref size, ref padding ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static Rect[] INTERNAL_CALL_GenerateGridSpriteRectangles (Texture2D texture, ref Vector2 offset, ref Vector2 size, ref Vector2 padding); -} - -internal static partial class SpriteExtensions -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static Texture GetTextureForPlayMode (this Sprite sprite) ; - -} - - -} - - - -namespace UnityEditor.Experimental.U2D -{ - internal static class SpriteUtility - { - public static void GenerateOutline(Texture2D texture, Rect rect, float detail, byte alphaTolerance, bool holeDetection, out Vector2[][] paths) - { - UnityEditor.Sprites.SpriteUtility.GenerateOutline(texture, rect, detail, alphaTolerance, holeDetection, out paths); - } - - } - -} diff --git a/artifacts/generated/bindings_old/common/Editor/StateMachineBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/StateMachineBindings.gen.cs deleted file mode 100644 index d7e42e7c59..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/StateMachineBindings.gen.cs +++ /dev/null @@ -1,56 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using UnityEngineInternal; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; - -namespace UnityEditor.Animations -{ -public sealed partial class AnimatorState : Object -{ - public extern StateMachineBehaviour[] behaviours - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal MonoScript GetBehaviourMonoScript (int index) ; - -} - -public sealed partial class AnimatorStateMachine : Object -{ - public extern StateMachineBehaviour[] behaviours - { - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - get; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - set; - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal MonoScript GetBehaviourMonoScript (int index) ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/Editor/WebViewBindings.gen.cs b/artifacts/generated/bindings_old/common/Editor/WebViewBindings.gen.cs deleted file mode 100644 index 519b5f3095..0000000000 --- a/artifacts/generated/bindings_old/common/Editor/WebViewBindings.gen.cs +++ /dev/null @@ -1,159 +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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using System; -using UnityEngine; -using Object = UnityEngine.Object; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Collections; -using System.Collections.Generic; -using UnityEngineInternal; -using UnityEditorInternal; - -namespace UnityEditor -{ - - -[StructLayout(LayoutKind.Sequential)] -internal sealed partial class WebView : ScriptableObject -{ - [SerializeField] - private MonoReloadableIntPtr WebViewWindow; - - - public void OnDestroy() - { - DestroyWebView(); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void DestroyWebView () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void InitWebView (GUIView host, int x, int y, int width, int height, bool showResizeHandle) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void ExecuteJavascript (string scriptCode) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void LoadURL (string url) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void LoadFile (string path) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool DefineScriptObject (string path, ScriptableObject obj) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetDelegateObject (ScriptableObject value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetHostView (GUIView view) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetSizeAndPosition (int x, int y, int width, int height) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetFocus (bool value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public bool HasApplicationFocus () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SetApplicationFocus (bool applicationFocus) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Show () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Hide () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Back () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Forward () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void SendOnEvent (string jsonStr) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Reload () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void AllowRightClickMenu (bool allowRightClickMenu) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void ShowDevTools () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void ToggleMaximize () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern internal static void OnDomainReload () ; - - public static implicit operator bool(WebView exists) - { - return exists != null && !exists.IntPtrIsNull(); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private bool IntPtrIsNull () ; - -} - -[System.Serializable] -internal sealed partial class WebViewV8CallbackCSharp -{ - [SerializeField] - #pragma warning disable 169 - IntPtr m_thisDummy; - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public void Callback (string result) ; - - public void OnDestroy() - { - DestroyCallBack(); - } - - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern private void DestroyCallBack () ; - -} - -} diff --git a/artifacts/generated/bindings_old/common/ParticleSystem/ParticleSystemBindings.gen.cs b/artifacts/generated/bindings_old/common/ParticleSystem/ParticleSystemBindings.gen.cs index a95bdccce4..8e66c9141b 100644 --- a/artifacts/generated/bindings_old/common/ParticleSystem/ParticleSystemBindings.gen.cs +++ b/artifacts/generated/bindings_old/common/ParticleSystem/ParticleSystemBindings.gen.cs @@ -63,6 +63,7 @@ public partial struct MainModule public int maxParticles { get { return GetMaxParticles(m_ParticleSystem); } set { SetMaxParticles(m_ParticleSystem, value); } } public ParticleSystemEmitterVelocityMode emitterVelocityMode { get { return GetUseRigidbodyForVelocity(m_ParticleSystem) ? ParticleSystemEmitterVelocityMode.Rigidbody : ParticleSystemEmitterVelocityMode.Transform; } set { SetUseRigidbodyForVelocity(m_ParticleSystem, value == ParticleSystemEmitterVelocityMode.Rigidbody); } } public ParticleSystemStopAction stopAction { get { return GetStopAction(m_ParticleSystem); } set { SetStopAction(m_ParticleSystem, value); } } + public ParticleSystemCullingMode cullingMode { get { return GetCullingMode(m_ParticleSystem); } set { SetCullingMode(m_ParticleSystem, value); } } public ParticleSystemRingBufferMode ringBufferMode { get { return GetRingBufferMode(m_ParticleSystem); } set { SetRingBufferMode(m_ParticleSystem, value); } } public Vector2 ringBufferLoopRange { get { return GetRingBufferLoopRange(m_ParticleSystem); } set { SetRingBufferLoopRange(m_ParticleSystem, value); } } @@ -363,6 +364,14 @@ public partial struct MainModule [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] extern private static ParticleSystemStopAction GetStopAction (ParticleSystem system) ; + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern private static void SetCullingMode (ParticleSystem system, ParticleSystemCullingMode value) ; + + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern private static ParticleSystemCullingMode GetCullingMode (ParticleSystem system) ; + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] extern private static void SetRingBufferMode (ParticleSystem system, ParticleSystemRingBufferMode value) ; @@ -2962,6 +2971,8 @@ public partial struct TrailModule public bool generateLightingData { set { SetGenerateLightingData(m_ParticleSystem, value); } get { return GetGenerateLightingData(m_ParticleSystem); } } public int ribbonCount { get { return GetRibbonCount(m_ParticleSystem); } set { SetRibbonCount(m_ParticleSystem, value); } } public float shadowBias { set { SetShadowBias(m_ParticleSystem, value); } get { return GetShadowBias(m_ParticleSystem); } } + public bool splitSubEmitterRibbons { set { SetSplitSubEmitterRibbons(m_ParticleSystem, value); } get { return GetSplitSubEmitterRibbons(m_ParticleSystem); } } + public bool attachRibbonsToTransform { set { SetAttachRibbonsToTransform(m_ParticleSystem, value); } get { return GetAttachRibbonsToTransform(m_ParticleSystem); } } [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration @@ -3116,6 +3127,22 @@ public partial struct TrailModule [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] extern private static float GetShadowBias (ParticleSystem system) ; + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern private static void SetSplitSubEmitterRibbons (ParticleSystem system, bool value) ; + + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern private static bool GetSplitSubEmitterRibbons (ParticleSystem system) ; + + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern private static void SetAttachRibbonsToTransform (ParticleSystem system, bool value) ; + + [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration + [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] + extern private static bool GetAttachRibbonsToTransform (ParticleSystem system) ; + } [System.Runtime.InteropServices.StructLayout (System.Runtime.InteropServices.LayoutKind.Sequential)] diff --git a/artifacts/generated/bindings_old/common/VR/VRTestBindings.gen.cs b/artifacts/generated/bindings_old/common/VR/VRTestBindings.gen.cs deleted file mode 100644 index 1686cd28cb..0000000000 --- a/artifacts/generated/bindings_old/common/VR/VRTestBindings.gen.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 scm=System.ComponentModel; -using uei=UnityEngine.Internal; -using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute; -using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute; - -using UnityEngine.XR; - -namespace UnityEngine.Internal.VR -{ - - -public static partial class VRTestMock -{ - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void Reset () ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void AddTrackedDevice (XRNode nodeType) ; - - public static void UpdateTrackedDevice (XRNode nodeType, Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateTrackedDevice ( nodeType, ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateTrackedDevice (XRNode nodeType, ref Vector3 position, ref Quaternion rotation); - public static void UpdateLeftEye (Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateLeftEye ( ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateLeftEye (ref Vector3 position, ref Quaternion rotation); - public static void UpdateRightEye (Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateRightEye ( ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateRightEye (ref Vector3 position, ref Quaternion rotation); - public static void UpdateCenterEye (Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateCenterEye ( ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateCenterEye (ref Vector3 position, ref Quaternion rotation); - public static void UpdateHead (Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateHead ( ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateHead (ref Vector3 position, ref Quaternion rotation); - public static void UpdateLeftHand (Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateLeftHand ( ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateLeftHand (ref Vector3 position, ref Quaternion rotation); - public static void UpdateRightHand (Vector3 position, Quaternion rotation) { - INTERNAL_CALL_UpdateRightHand ( ref position, ref rotation ); - } - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - private extern static void INTERNAL_CALL_UpdateRightHand (ref Vector3 position, ref Quaternion rotation); - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void AddController (string controllerName) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void UpdateControllerAxis (string controllerName, int axis, float value) ; - - [UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute] // Temporarily necessary for bindings migration - [System.Runtime.CompilerServices.MethodImplAttribute((System.Runtime.CompilerServices.MethodImplOptions)0x1000)] - extern public static void UpdateControllerButton (string controllerName, int button, bool pressed) ; - -} - - -} diff --git a/third-party-notices.txt b/third-party-notices.txt deleted file mode 100644 index 58be63b7b4..0000000000 --- a/third-party-notices.txt +++ /dev/null @@ -1,95 +0,0 @@ -Files under External/ folder are third party code under their own -respective licenses: - -External/CSSLayout and/or External/Yoga: - - https://github.com/facebook/yoga - Copyright (c) 2014-present, Facebook, Inc. All rights reserved - BSD 3-Clause License - -External/JsonParsers/MiniJson - - https://gist.github.com/darktable/1411710 - Copyright (c) 2013 Calvin Rien - MIT license - -External/JsonParsers/SimpleJson - - https://github.com/facebook-csharp-sdk/simple-json - Copyright (c) 2011, The Outercurve Foundation - MIT license - -External/Mono.Cecil - - https://github.com/jbevain/cecil - Copyright (c) 2008-2015 Jb Evain. Copyright (c) 2008-2011 Novell, Inc. - MIT license - -External/Mono: - - https://github.com/boo-lang/boo - Copyright (c) 2003-2008 Rodrigo B. Oliveira - BSD 3-Clause License - - https://github.com/mono/mono/tree/master/mcs - Copyright (c) 2005-2008 Novell, Inc. - MIT License - - https://github.com/bamboo/unityscript - Copyright (c) 2005-2008 Rodrigo B. Oliveira - BSD 3-Clause License - -External/NRefactory: - https://github.com/icsharpcode/NRefactory - Copyright (c) 2010-2014 AlphaSierraPapa, Xamarin - MIT license - -Appendix: Referenced Licenses - -BSD 3-Clause License - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holder nor the names of its - contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS - FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE - COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS - OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE - USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -MIT License - - Permission is hereby granted, free of charge, to any person obtaining a - copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to permit - persons to whom the Software is furnished to do so, subject to the - following conditions: - - The above copyright notice and this permission notice shall be included - in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY - CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT - OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR - THE USE OR OTHER DEALINGS IN THE SOFTWARE.