text
stringlengths 7
35.3M
| id
stringlengths 11
185
| metadata
dict | __index_level_0__
int64 0
2.14k
|
---|---|---|---|
// Unity 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.Text;
using UnityEditor.AddComponent;
using UnityEditor.VersionControl;
using UnityEngine;
using UnityEngine.Scripting;
using UnityEditorInternal;
using UnityEditorInternal.VersionControl;
using UnityEditor.StyleSheets;
using UnityEngine.Assertions.Comparers;
using UnityEngine.UIElements;
using UnityEditor.SceneManagement;
using Object = UnityEngine.Object;
using AssetImporterEditor = UnityEditor.AssetImporters.AssetImporterEditor;
using JetBrains.Annotations;
using Unity.Profiling;
using UnityEditor.UIElements;
namespace UnityEditor
{
interface IPropertyView
{
ActiveEditorTracker tracker { get; }
InspectorMode inspectorMode { get; }
HashSet<int> editorsWithImportedObjectLabel { get; }
Editor lastInteractedEditor { get; set; }
GUIView parent { get; }
EditorDragging editorDragging { get; }
IMGUIContainer CreateIMGUIContainer(Action headerOnGUI, string v);
bool WasEditorVisible(Editor[] editors, int editorIndex, Object target);
bool ShouldCullEditor(Editor[] editors, int editorIndex);
void Repaint();
void UnsavedChangesStateChanged(Editor editor, bool value);
}
interface IPropertySourceOpener
{
Object hoveredObject { get; }
}
class PropertyEditor : EditorWindow, IPropertyView, IHasCustomMenu
{
internal const string k_AssetPropertiesMenuItemName = "Assets/Properties... _&P";
protected const string s_MultiEditClassName = "unity-inspector-no-multi-edit-warning";
protected const string s_EditorListClassName = "unity-inspector-editors-list";
protected const string s_AddComponentClassName = "unity-inspector-add-component-button";
protected const string s_HeaderInfoClassName = "unity-inspector-header-info";
protected const string s_FooterInfoClassName = "unity-inspector-footer-info";
internal const string s_MainContainerClassName = "unity-inspector-main-container";
protected const string s_PreviewContainer = "preview-container";
protected const string s_Footer = "footer";
protected const string s_dragline = "unity-dragline";
protected const string s_draglineAnchor = "unity-dragline-anchor";
protected const float kBottomToolbarHeight = 21f;
protected const float kAddComponentButtonHeight = 45f;
internal const float kEditorElementPaddingBottom = 2f;
protected const float k_MinAreaAbovePreview = 130;
protected const float k_InspectorPreviewMinHeight = 130;
protected const float k_InspectorPreviewMinTotalHeight = k_InspectorPreviewMinHeight + kBottomToolbarHeight;
protected const int k_MinimumRootVisualHeight = 81;
protected const int k_MinimumWindowWidth = 275;
protected const int k_AutoScrollZoneHeight = 24;
const float m_PreviewDefaultHeight = 200;
const float m_PreviewMinHeight = 20;
float m_CachedPreviewHeight = m_PreviewDefaultHeight;
protected const long delayRepaintWhilePlayingAnimation = 150; // Delay between repaints in milliseconds while playing animation
protected long m_LastUpdateWhilePlayingAnimation = 0;
/// <summary>
/// The number of inspector elements to create on the initial draw.
/// </summary>
const int k_CreateInspectorElementMinCount = 2;
/// <summary>
/// The target number of milliseconds to spend on creating inspector elements per update.
/// </summary>
const int k_CreateInspectorElementTargetUpdateTime = 5;
[SerializeField] protected List<Object> m_ObjectsLockedBeforeSerialization = new List<Object>();
[SerializeField] protected List<int> m_InstanceIDsLockedBeforeSerialization = new List<int>();
[SerializeField] protected PreviewResizer m_PreviewResizer = new PreviewResizer();
[SerializeField] protected LabelGUI m_LabelGUI = new LabelGUI();
[SerializeField] protected int m_LastInspectedObjectInstanceID = -1;
[SerializeField] protected float m_LastVerticalScrollValue = 0;
[SerializeField] protected string m_GlobalObjectId = "";
[SerializeField] protected InspectorMode m_InspectorMode = InspectorMode.Normal;
private static readonly List<PropertyEditor> m_AllPropertyEditors = new List<PropertyEditor>();
private Object m_InspectedObject;
private static PropertyEditor s_LastPropertyEditor;
protected int m_LastInitialEditorInstanceID;
protected Component[] m_ComponentsInPrefabSource;
protected HashSet<Component> m_RemovedComponents;
protected HashSet<Component> m_SuppressedComponents;
// Map that maps from editorIndex to list of removed asset components
// This is later used to determine if removed components visual elements need to be added to some editor at some index
protected Dictionary<int, List<Component>> m_RemovedComponentDict;
// List of removed components at the end of the editor list that needs to have visual elements append to the editor list
protected List<Component> m_AdditionalRemovedComponents;
protected bool m_ResetKeyboardControl;
internal bool m_OpenAddComponentMenu = false;
protected ActiveEditorTracker m_Tracker;
protected AssetBundleNameGUI m_AssetBundleNameGUI = new AssetBundleNameGUI();
protected TypeSelectionList m_TypeSelectionList = null;
protected double m_lastRenderedTime;
protected List<IPreviewable> m_Previews;
protected Dictionary<Type, List<Type>> m_PreviewableTypes;
protected IPreviewable m_SelectedPreview;
protected VisualElement m_EditorsElement;
protected VisualElement editorsElement => m_EditorsElement ?? (m_EditorsElement = FindVisualElementInTreeByClassName(s_EditorListClassName));
protected VisualElement m_RemovedPrefabComponentsElement;
protected VisualElement m_PreviewAndLabelElement;
protected VisualElement previewAndLabelElement => m_PreviewAndLabelElement ?? (m_PreviewAndLabelElement = FindVisualElementInTreeByClassName(s_FooterInfoClassName));
protected VisualElement m_VersionControlElement;
protected VisualElement versionControlElement => m_VersionControlElement ?? (m_VersionControlElement = FindVisualElementInTreeByClassName(s_HeaderInfoClassName));
protected static Dictionary<Editor, VersionControlBarState> m_VersionControlBarState = new Dictionary<Editor, VersionControlBarState>();
protected VisualElement m_MultiEditLabel;
protected ScrollView m_ScrollView;
protected bool m_TrackerResetInserted;
internal bool m_FirstInitialize;
protected float m_PreviousFooterHeight = -1;
protected bool m_PreviousPreviewExpandedState;
protected bool m_HasPreview;
protected HashSet<int> m_DrawnSelection = new HashSet<int>();
internal bool hasFloatingPreviewWindow { get; set; }
readonly List<Type> m_EditorTargetTypes = new List<Type>();
List<DataMode> m_SupportedDataModes = new(4);
static readonly List<DataMode> k_DisabledDataModes = new() {DataMode.Disabled};
public GUIView parent => m_Parent;
public HashSet<int> editorsWithImportedObjectLabel { get; } = new HashSet<int>();
public EditorDragging editorDragging { get; }
public Editor lastInteractedEditor { get; set; }
internal static PropertyEditor HoveredPropertyEditor { get; private set; }
internal static PropertyEditor FocusedPropertyEditor { get; private set; }
EditorElementUpdater m_EditorElementUpdater;
IPreviewable m_cachedPreviewEditor;
public InspectorMode inspectorMode
{
get { return m_InspectorMode; }
set { SetMode(value); }
}
public ActiveEditorTracker tracker
{
get
{
CreateTracker();
return m_Tracker;
}
}
protected Rect bottomAreaDropRectangle
{
get
{
var worldEditorRect = editorsElement.LocalToWorld(editorsElement.rect);
var worldRootRect = rootVisualElement.LocalToWorld(rootVisualElement.rect);
return new Rect(
worldEditorRect.x,
worldEditorRect.y + worldEditorRect.height,
worldEditorRect.width,
worldRootRect.y + worldRootRect.height - worldEditorRect.height - worldEditorRect.y);
}
}
internal Rect scrollViewportRect => m_ScrollView.contentViewport.rect;
protected static class Styles
{
public static readonly GUIStyle preToolbar = "preToolbar";
public static readonly GUIStyle preToolbar2 = "preToolbar2";
public static readonly GUIStyle preToolbarLabel = "ToolbarBoldLabel";
public static readonly GUIStyle preDropDown = "preDropDown";
public static readonly GUIStyle dragHandle = "RL DragHandle";
public static readonly GUIStyle lockButton = "IN LockButton";
public static readonly GUIStyle insertionMarker = "InsertionMarker";
public static readonly GUIContent preTitle = EditorGUIUtility.TrTextContent("Preview");
public static readonly GUIContent labelTitle = EditorGUIUtility.TrTextContent("Asset Labels");
public static readonly GUIContent addComponentLabel = EditorGUIUtility.TrTextContent("Add Component");
public static GUIStyle preBackground = "preBackground";
public static GUIStyle footer = "IN Footer";
public static GUIStyle preMargins = new GUIStyle() {margin = new RectOffset(0, 0, 0, 4)};
public static GUIStyle preOptionsButton = new GUIStyle(EditorStyles.toolbarButtonRight) { padding = new RectOffset(), contentOffset = new Vector2(1, 0) };
public static GUIStyle addComponentArea = EditorStyles.inspectorTitlebar;
public static GUIStyle addComponentButtonStyle = "AC Button";
public static readonly GUIContent menuIcon = EditorGUIUtility.TrIconContent("_Menu");
public static GUIStyle previewMiniLabel = EditorStyles.whiteMiniLabel;
public static GUIStyle typeSelection = "IN TypeSelection";
public static readonly GUIContent vcsCheckoutHint = EditorGUIUtility.TrTextContent("Under Version Control\nCheck out this asset in order to make changes.", EditorGUIUtility.GetHelpIcon(MessageType.Info));
public static readonly GUIContent vcsNotConnected = EditorGUIUtility.TrTextContent("VCS ({0}) is not connected");
public static readonly GUIContent vcsOffline = EditorGUIUtility.TrTextContent("Work Offline option is active");
public static readonly GUIContent vcsSettings = EditorGUIUtility.TrTextContent("Settings");
public static readonly GUIContent vcsCheckout = EditorGUIUtility.TrTextContent("Check Out");
public static readonly GUIContent vcsCheckoutMeta = EditorGUIUtility.TrTextContent("Check Out Meta");
public static readonly GUIContent vcsAdd = EditorGUIUtility.TrTextContent("Add");
public static readonly GUIContent vcsLock = EditorGUIUtility.TrTextContent("Lock");
public static readonly GUIContent vcsUnlock = EditorGUIUtility.TrTextContent("Unlock");
public static readonly GUIContent vcsSubmit = EditorGUIUtility.TrTextContent("Submit");
public static readonly GUIContent vcsRevert = EditorGUIUtility.TrTextContent("Revert");
public static readonly GUIContent vcsRevertUnchanged = EditorGUIUtility.TrTextContent("Revert Unchanged");
public static readonly GUIContent[] vcsRevertMenuNames = {vcsRevertUnchanged};
public static readonly GenericMenu.MenuFunction2[] vcsRevertMenuActions = {DoRevertUnchanged};
public static readonly GUIStyle vcsButtonStyle = EditorStyles.miniButton;
public static GUIStyle vcsRevertStyle = new GUIStyle(EditorStyles.dropDownList);
public static readonly GUIStyle vcsBarStyleOneRow = EditorStyles.toolbar;
public static GUIStyle vcsBarStyleTwoRows = new GUIStyle(EditorStyles.toolbar);
public static readonly string objectDisabledModuleWarningFormat = L10n.Tr(
"The built-in package '{0}', 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."
);
public static readonly string objectDisabledModuleWithDependencyWarningFormat = L10n.Tr(
"The built-in package '{0}', which is required by the package '{1}', 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."
);
public static SVC<float> lineSeparatorOffset = new SVC<float>("AC-Button", "--separator-line-top-offset");
public static SVC<Color> lineSeparatorColor = new SVC<Color>("--theme-line-separator-color", Color.red);
static Styles()
{
vcsRevertStyle.padding.right = 15;
vcsBarStyleTwoRows.fixedHeight *= 2;
}
}
protected class VersionControlBarState
{
public bool settings;
public bool revert;
public bool revertUnchanged;
public bool checkout;
public bool add;
public bool submit;
public bool @lock;
public bool unlock;
Editor m_Editor;
public Editor Editor
{
get
{
if (m_Editor == null && editors != null) m_Editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(editors);
return m_Editor;
}
private set
{
m_Editor = value;
}
}
public Editor[] editors;
public AssetList assets = new AssetList();
public int GetButtonCount()
{
var c = 0;
if (settings) ++c;
if (revert) ++c; // revertUnchanged is same button in a drop-down
if (checkout) ++c;
if (add) ++c;
if (submit) ++c;
if (@lock) ++c;
if (unlock) ++c;
return c;
}
public static VersionControlBarState Calculate(Editor[] assetEditors, Asset asset, bool connected)
{
var res = new VersionControlBarState();
if (!connected)
{
res.settings = true;
return res;
}
var isFolder = asset.isFolder && !Provider.isVersioningFolders;
res.editors = assetEditors;
res.assets.AddRange(res.Editor.targets.Select(o => Provider.GetAssetByPath(AssetDatabase.GetAssetPath(o))));
res.assets = Provider.ConsolidateAssetList(res.assets, CheckoutMode.Both);
res.revert = Provider.RevertIsValid(res.assets, RevertMode.Normal);
res.revertUnchanged = Provider.RevertIsValid(res.assets, RevertMode.Unchanged);
bool checkoutBoth = res.Editor.target == null || AssetDatabase.CanOpenAssetInEditor(res.Editor.target.GetInstanceID());
res.checkout = isFolder || Provider.CheckoutIsValid(res.assets, checkoutBoth ? CheckoutMode.Both : CheckoutMode.Meta);
res.add = Provider.AddIsValid(res.assets);
res.submit = Provider.SubmitIsValid(null, res.assets);
res.@lock = Provider.hasLockingSupport && !isFolder && Provider.LockIsValid(res.assets);
res.unlock = Provider.hasLockingSupport && !isFolder && Provider.UnlockIsValid(res.assets);
return res;
}
}
internal PropertyEditor()
{
editorDragging = new EditorDragging(this);
minSize = new Vector2(k_MinimumWindowWidth, minSize.y);
m_EditorElementUpdater = new EditorElementUpdater(this);
hasFloatingPreviewWindow = false;
}
[UsedImplicitly]
protected virtual void OnDestroy()
{
if (m_Tracker != null)
m_Tracker.Destroy();
}
[UsedImplicitly]
protected virtual void OnFocusChanged(bool focus)
{
// focusing away from the editor flushes VCS state cache and might get
// updated states from external clients; make sure to recalculate which VCS
// buttons should be visible
ClearVersionControlBarState();
}
[UsedImplicitly]
protected virtual void OnEnable()
{
LoadVisualTreeFromUxml();
m_PreviewResizer.localFrame = true;
m_PreviewResizer.Init("InspectorPreview");
m_LabelGUI.OnEnable();
m_FirstInitialize = true;
var shouldUpdateSupportedDataModes = m_SerializedDataModeController == null;
CreateTracker();
EditorApplication.focusChanged += OnFocusChanged;
Undo.undoRedoEvent += OnUndoRedoPerformed;
PrefabUtility.prefabInstanceUnpacked += OnPrefabInstanceUnpacked;
ObjectChangeEvents.changesPublished += OnObjectChanged;
rootVisualElement.RegisterCallback<DragUpdatedEvent>(DragOverBottomArea);
rootVisualElement.RegisterCallback<DragPerformEvent>(DragPerformInBottomArea);
rootVisualElement.RegisterCallback<MouseEnterEvent>(OnMouseEnter);
rootVisualElement.RegisterCallback<MouseLeaveEvent>(OnMouseLeave);
rootVisualElement.RegisterCallback<FocusInEvent>(OnFocusIn);
rootVisualElement.RegisterCallback<FocusOutEvent>(OnFocusOut);
dataModeController.dataModeChanged += OnDataModeChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
if (shouldUpdateSupportedDataModes)
EditorApplication.CallDelayed(UpdateSupportedDataModesList);
if (!m_AllPropertyEditors.Contains(this)) m_AllPropertyEditors.Add(this);
}
[UsedImplicitly]
protected virtual void OnDisable()
{
hasFloatingPreviewWindow = false;
ClearPreviewables();
// save vertical scroll position
m_LastInspectedObjectInstanceID = GetInspectedObject()?.GetInstanceID() ?? -1;
m_LastVerticalScrollValue = m_ScrollView?.verticalScroller.value ?? 0;
EditorApplication.focusChanged -= OnFocusChanged;
Undo.undoRedoEvent -= OnUndoRedoPerformed;
PrefabUtility.prefabInstanceUnpacked -= OnPrefabInstanceUnpacked;
ObjectChangeEvents.changesPublished -= OnObjectChanged;
rootVisualElement.UnregisterCallback<DragUpdatedEvent>(DragOverBottomArea);
rootVisualElement.UnregisterCallback<DragPerformEvent>(DragPerformInBottomArea);
rootVisualElement.UnregisterCallback<MouseEnterEvent>(OnMouseEnter);
rootVisualElement.UnregisterCallback<MouseLeaveEvent>(OnMouseLeave);
rootVisualElement.UnregisterCallback<FocusInEvent>(OnFocusIn);
rootVisualElement.UnregisterCallback<FocusOutEvent>(OnFocusOut);
dataModeController.dataModeChanged -= OnDataModeChanged;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
m_AllPropertyEditors.Remove(this);
}
private void OnMouseEnter(MouseEnterEvent e) => HoveredPropertyEditor = this;
private void OnMouseLeave(MouseLeaveEvent e) => HoveredPropertyEditor = null;
private void OnFocusIn(FocusInEvent e) => FocusedPropertyEditor = this;
private void OnFocusOut(FocusOutEvent e) => FocusedPropertyEditor = null;
[UsedImplicitly]
protected virtual void OnLostFocus()
{
m_LabelGUI.OnLostFocus();
}
protected virtual bool CloseIfEmpty()
{
// We can rely on the tracker to always keep valid Objects
// even after an assemblyreload or assetdatabase refresh.
List<Object> locked = new List<Object>();
tracker.GetObjectsLockedByThisTracker(locked);
if (locked.Any(o => o != null))
return false;
EditorApplication.delayCall += Close;
return true;
}
[UsedImplicitly]
protected virtual void OnInspectorUpdate()
{
if (CloseIfEmpty())
return;
// Check if scripts have changed without calling set dirty
tracker.VerifyModifiedMonoBehaviours();
InspectorUtility.DirtyLivePropertyChanges(tracker);
if(previewWindow != null)
UpdateLabel(previewWindow);
if (!tracker.isDirty || !ReadyToRepaint())
return;
Repaint();
}
[UsedImplicitly]
protected virtual void OnGUI()
{
if (m_FirstInitialize)
RebuildContentsContainers();
}
static Editor[] s_Editors = new Editor[10];
[UsedImplicitly]
protected virtual void Update()
{
ActiveEditorTracker.Internal_GetActiveEditorsNonAlloc(tracker, s_Editors);
if (s_Editors.Length == 0)
return;
bool wantsRepaint = false;
foreach (var myEditor in s_Editors)
{
if (myEditor != null && myEditor.RequiresConstantRepaint() && !EditorUtility.IsHiddenInInspector(myEditor))
wantsRepaint = true;
}
m_EditorElementUpdater.CreateInspectorElementsForMilliseconds(k_CreateInspectorElementTargetUpdateTime);
if (wantsRepaint && m_lastRenderedTime + 0.033f < EditorApplication.timeSinceStartup)
{
m_lastRenderedTime = EditorApplication.timeSinceStartup;
Repaint();
}
if (m_InspectedObject && !string.Equals(m_InspectedObject.name, titleContent.text))
UpdateWindowObjectNameTitle();
}
internal static IEnumerable<PropertyEditor> GetPropertyEditors()
{
return m_AllPropertyEditors.AsEnumerable();
}
protected virtual void EnsureAppropriateTrackerIsInUse()
{
if (m_InspectorMode == InspectorMode.Normal)
m_Tracker = ActiveEditorTracker.sharedTracker;
else if (m_Tracker is null || m_Tracker.Equals(ActiveEditorTracker.sharedTracker))
m_Tracker = new ActiveEditorTracker();
}
protected void SetMode(InspectorMode mode)
{
if (m_InspectorMode != mode)
{
m_InspectorMode = mode;
RefreshTitle();
// Clear the editors Element so that a real rebuild is done
editorsElement.Clear();
m_EditorElementUpdater.Clear();
EnsureAppropriateTrackerIsInUse();
m_Tracker.inspectorMode = m_InspectorMode;
m_Tracker.ForceRebuild();
m_ResetKeyboardControl = true;
SceneView.SetActiveEditorsDirty(true);
}
}
protected void SetTitle(Object obj)
{
var objTitle = ObjectNames.GetInspectorTitle(obj);
var titleTooltip = objTitle;
if (obj is GameObject go)
titleTooltip = EditorUtility.GetHierarchyPath(go);
else if (obj is Component c)
titleTooltip = $"{EditorUtility.GetHierarchyPath(c.gameObject)} ({objTitle})";
else if (GlobalObjectId.TryParse(m_GlobalObjectId, out var gid))
titleTooltip = AssetDatabase.GUIDToAssetPath(gid.assetGUID);
titleContent = new GUIContent(obj.name, EditorGUIUtility.LoadIconRequired("UnityEditor.InspectorWindow"), titleTooltip);
titleContent.image = AssetPreview.GetMiniThumbnail(obj);
}
protected virtual void RefreshTitle()
{
var obj = GetInspectedObject();
if (!obj)
return;
SetTitle(obj);
}
private VisualElement FindVisualElementInTreeByClassName(string elementClassName)
{
return rootVisualElement.Q(className: elementClassName);
}
internal static void ClearVersionControlBarState()
{
var vco = VersionControlManager.activeVersionControlObject;
if (vco != null)
vco.GetExtension<IInspectorWindowExtension>()?.InvalidateVersionControlBarState();
m_VersionControlBarState.Clear();
}
protected void LoadVisualTreeFromUxml()
{
var tpl = EditorGUIUtility.Load("UXML/InspectorWindow/InspectorWindow.uxml") as VisualTreeAsset;
var fContainer = rootVisualElement.Query(null, s_MainContainerClassName).First();
VisualElement container = fContainer ?? tpl.Instantiate();
container.AddToClassList(s_MainContainerClassName);
rootVisualElement.hierarchy.Add(container);
m_ScrollView = container.Q<ScrollView>();
// We need to disable view-data persistence on the scrollbars of the ScrollView.
// There are a bunch of places that assume the Inspector will always refresh
// fully scrolled up. Users also had this behaviour since the beginning of time.
// While we need m_ScrollView to have a view data key so users inside of an Editor
// can use view data persistence, adding a key will enable persistence of the
// scrollbars.
m_ScrollView.verticalScroller.viewDataKey = null;
m_ScrollView.horizontalScroller.viewDataKey = null;
m_ScrollView.verticalScroller.slider.viewDataKey = null;
m_ScrollView.horizontalScroller.slider.viewDataKey = null;
var multiContainer = rootVisualElement.Q(className: s_MultiEditClassName);
multiContainer.Query<TextElement>().ForEach((label) => label.text = L10n.Tr(label.text));
multiContainer.RemoveFromHierarchy();
m_MultiEditLabel = multiContainer;
rootVisualElement.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
rootVisualElement.AddStyleSheetPath("StyleSheets/InspectorWindow/InspectorWindow.uss");
}
private void OnGeometryChanged(GeometryChangedEvent e)
{
if (m_PreviewResizer.GetExpanded())
{
if (previewAndLabelElement.layout.height > 0 &&
rootVisualElement.layout.height <= k_MinimumRootVisualHeight + m_PreviewResizer.containerMinimumHeightExpanded)
{
m_PreviewResizer.SetExpanded(false);
}
}
RestoreVerticalScrollIfNeeded();
}
internal static void ClearAndRebuildAll()
{
// Needs to be delayCall because it forces redrawing of UI which messes with the current IMGUI context of the Settings window.
EditorApplication.delayCall += ClearAndRebuildAllDelayed;
}
static void ClearAndRebuildAllDelayed()
{
// Cannot use something like EditorUtility.ForceRebuildInspectors() because this only refreshes
// the inspector's values and IMGUI state, but otherwise, if the target did not change we
// re-use the Editors. We need a special clear function to properly recreate the UI using
// the new setting.
var propertyEditors = Resources.FindObjectsOfTypeAll<PropertyEditor>();
foreach (var propertyEditor in propertyEditors)
propertyEditor.ClearEditorsAndRebuild();
}
internal void ClearEditorsAndRebuild()
{
// Clear the editors Element so that a real rebuild is done
editorsElement.Clear();
m_EditorElementUpdater.Clear();
RebuildContentsContainers();
}
private void SetDebug()
{
inspectorMode = InspectorMode.Debug;
}
private void SetNormal()
{
inspectorMode = InspectorMode.Normal;
}
private void SetDebugInternal()
{
inspectorMode = InspectorMode.DebugInternal;
}
public virtual void AddDebugItemsToMenu(GenericMenu menu)
{
menu.AddItem(EditorGUIUtility.TrTextContent("Normal"), m_InspectorMode == InspectorMode.Normal, SetNormal);
menu.AddItem(EditorGUIUtility.TrTextContent("Debug"), m_InspectorMode == InspectorMode.Debug, SetDebug);
if (Unsupported.IsDeveloperMode())
{
menu.AddItem(EditorGUIUtility.TrTextContent("Debug-Internal"), m_InspectorMode == InspectorMode.DebugInternal, SetDebugInternal);
}
}
public virtual void AddItemsToMenu(GenericMenu menu)
{
AddDebugItemsToMenu(menu);
menu.AddSeparator(String.Empty);
if (IsAnyComponentCollapsed())
menu.AddItem(EditorGUIUtility.TrTextContent("Expand All Components"), false, ExpandAllComponents);
else
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Expand All Components"));
if (IsAnyComponentExpanded())
menu.AddItem(EditorGUIUtility.TrTextContent("Collapse All Components"), false, CollapseAllComponents);
else
menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Collapse All Components"));
if (m_Tracker != null)
{
bool addedSeparator = false;
foreach (var editor in m_Tracker.activeEditors)
{
var menuContainer = editor as IHasCustomMenu;
if (menuContainer != null)
{
if (!addedSeparator)
{
menu.AddSeparator(String.Empty);
addedSeparator = true;
}
menuContainer.AddItemsToMenu(menu);
}
}
}
menu.AddSeparator("");
menu.AddItem(EditorGUIUtility.TrTextContent("Ping"), false, () => EditorGUIUtility.PingObject(GetInspectedObject()));
menu.AddItem(EditorGUIUtility.TrTextContent("Open in Import Activity Window"), false, () => ImportActivityWindow.OpenFromPropertyEditor(GetInspectedObject()));
}
private void SetTrackerExpandedState(ActiveEditorTracker tracker, int editorIndex, bool expanded)
{
tracker.SetVisible(editorIndex, expanded ? 1 : 0);
InternalEditorUtility.SetIsInspectorExpanded(tracker.activeEditors[editorIndex].target, expanded);
}
protected void ExpandAllComponents()
{
var editors = tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
SetTrackerExpandedState(tracker, i, expanded: true);
}
protected bool IsAnyComponentCollapsed()
{
if (Selection.activeGameObject == null)
return false; // If the selection is not a game object then disable the option.
var editors = tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
{
if (tracker.GetVisible(i) == 0)
return true;
}
return false;
}
protected void CollapseAllComponents()
{
var editors = tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
SetTrackerExpandedState(tracker, i, expanded: false);
}
protected bool IsAnyComponentExpanded()
{
if (Selection.activeGameObject == null)
return false;
var editors = this.tracker.activeEditors;
for (int i = 1; i < editors.Length; i++)
{
if (this.tracker.GetVisible(i) == 1)
return true;
}
return false;
}
protected bool LoadPersistedObject()
{
if (String.IsNullOrEmpty(m_GlobalObjectId))
return false;
if (!GlobalObjectId.TryParse(m_GlobalObjectId, out var gid))
return false;
m_InspectedObject = GlobalObjectId.GlobalObjectIdentifierToObjectSlow(gid);
if (m_InspectedObject)
{
SetTitle(m_InspectedObject);
m_Tracker.SetObjectsLockedByThisTracker(new List<Object> { m_InspectedObject });
}
else
{
// Failed to load object, lets close this property editor.
EditorApplication.delayCall += Close;
return false;
}
return true;
}
protected virtual void CreateTracker()
{
if (m_Tracker != null)
return;
m_Tracker = new ActiveEditorTracker { inspectorMode = InspectorMode.Normal };
if (LoadPersistedObject())
{
m_Tracker.ForceRebuild();
}
}
private void OnTrackerRebuilt()
{
ExtractPrefabComponents();
// tracker gets rebuilt when selection or objects change; make sure to recalc which VCS
// buttons are shown
ClearVersionControlBarState();
}
private void OnObjectChanged(ref ObjectChangeEventStream stream)
{
var inspectedObject = GetInspectedObject();
if (inspectedObject == null)
return;
var inspectedInstanceId = inspectedObject.GetInstanceID();
for (int i = 0; i < stream.length; ++i)
{
var eventType = stream.GetEventType(i);
if (eventType == ObjectChangeKind.ChangeGameObjectOrComponentProperties)
{
stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var e);
if (e.instanceId == inspectedInstanceId)
{
UpdateWindowObjectNameTitle();
return;
}
}
}
}
protected virtual void UpdateWindowObjectNameTitle()
{
titleContent.text = GetInspectedObject()?.name ?? titleContent.text;
Repaint();
}
void OnUndoRedoPerformed(in UndoRedoInfo info)
{
// Fix for a swapping an `m_Script` field in debug mode followed by an undo/redo. This causes the serialized object
// to be reset back to it's previous type. The editor instance remains the same, the serialized object remains the same and property iterators return
// the previous type properties. This breaks most assumptions in the inspectors and property drawers and causes numerous errors. As a patch we do a nuclear
// rebuild of everything if this state is detected.
var editors = tracker.activeEditors;
for (var i = 0; i < m_EditorTargetTypes.Count && i < editors.Length; i++)
{
var targetType = editors[i].target ? editors[i].target.GetType() : null;
if (targetType == m_EditorTargetTypes[i])
continue;
ActiveEditorTracker.sharedTracker.ForceRebuild();
}
// We need to detect and rebuild removed or suppressed component titlebars if the
// backend changes. Situations where this detection is needed is when:
// 1) Undo could cause a removed component to become a suppressed component and vice versa
// 2) Undo after replacing with a new prefab instance that has the same component count but the previous had a removed component.
// Other cases will cause the number of Editors to change which will result in the tracker being rebuilt already.
var prevRemovedComponents = new HashSet<Component>(m_RemovedComponents ?? new HashSet<Component>());
var prevSuppressedComponents = new HashSet<Component>(m_SuppressedComponents ?? new HashSet<Component>());
var prevComponentsInPrefabSource = new HashSet<Component>(m_ComponentsInPrefabSource ?? new Component[0]);
ExtractPrefabComponents();
if (!prevRemovedComponents.SetEquals(m_RemovedComponents ?? new HashSet<Component>()) ||
!prevSuppressedComponents.SetEquals(m_SuppressedComponents ?? new HashSet<Component>()) ||
!prevComponentsInPrefabSource.SetEquals(m_ComponentsInPrefabSource ?? new Component[0]))
{
RebuildContentsContainers();
}
}
private void DetermineInsertionPointOfVisualElementForRemovedComponent(int targetGameObjectIndex, Editor[] editors)
{
// Calculate which editor should have the removed component visual element added, if any.
// The visual element for removed components is added to the top of the chosen editor.
// It is assumed the asset components comes in the same order in the editors list, but there can be additional added
// components in the editors list, i.e. the editors for assets components can't be moved by the user
// Added components can appear anywhere in the editors list
if (m_RemovedComponentDict == null)
m_RemovedComponentDict = new Dictionary<int, List<Component>>();
if (m_AdditionalRemovedComponents == null)
m_AdditionalRemovedComponents = new List<Component>();
m_RemovedComponentDict.Clear();
m_AdditionalRemovedComponents.Clear();
int editorIndex = targetGameObjectIndex + 1;
foreach(var sourceComponent in m_ComponentsInPrefabSource)
{
// editorCounter is used to look forward in the list of editor, this is because added components might have be inserted between prefab components
// it starts at editorIndex because there is no need to look at the previous editors, based on the assumption that asset components and instance components
// always comes in the same order
int editorCounter = editorIndex;
// Move forwards through the list of editors to find one that matches the asset component
while (editorCounter < editors.Length)
{
Object editorTarget = editors[editorCounter].target;
// Skip added Components
if (editorTarget is Component && PrefabUtility.GetPrefabInstanceHandle(editorTarget) == null)
{
// If editorIndex and editorCounter are identical we also increment the editor index because we don't
// want to add the removed component visual element to added components editors
// For consistency the visual element for removed components are never added to added components, so if the current
// editor is an added component we skip the current editor
if (editorIndex == editorCounter)
++editorIndex;
++editorCounter;
continue;
}
Object correspondingSource = PrefabUtility.GetCorrespondingObjectFromSource(editorTarget);
if (correspondingSource == sourceComponent)
{
// When we found an editor that matches the asset component, we move the start index because we don't have to test
// this editor again
editorIndex = editorCounter + 1;
break;
}
++editorCounter;
}
// If the forward looking counter has reached the end of the editors list, the component must have been removed from the instance
if (editorCounter >= editors.Length)
{
// If the editorIndex has also reached the end we have removed components at the end of the list and those need to have their
// visual element added separately
if (editorIndex >= editors.Length)
{
m_AdditionalRemovedComponents.Add(sourceComponent);
}
else
{
if (!m_RemovedComponentDict.ContainsKey(editorIndex))
m_RemovedComponentDict.Add(editorIndex, new List<Component>());
m_RemovedComponentDict[editorIndex].Add(sourceComponent);
}
}
}
}
private void ExtractPrefabComponents()
{
m_LastInitialEditorInstanceID = m_Tracker.activeEditors.Length == 0 ? 0 : m_Tracker.activeEditors[0].GetInstanceID();
m_ComponentsInPrefabSource = null;
m_RemovedComponentDict = null;
m_AdditionalRemovedComponents = null;
if (m_RemovedComponents == null)
{
m_RemovedComponents = new HashSet<Component>();
m_SuppressedComponents = new HashSet<Component>();
}
m_RemovedComponents.Clear();
m_SuppressedComponents.Clear();
if (m_Tracker.activeEditors.Length == 0)
return;
if (m_Tracker.activeEditors[0].targets.Length != 1)
return;
GameObject go = m_Tracker.activeEditors[0].target as GameObject;
if (go == null && m_Tracker.activeEditors[0] is PrefabImporterEditor)
go = m_Tracker.activeEditors[1].target as GameObject;
if (go == null)
return;
GameObject sourceGo = PrefabUtility.GetCorrespondingConnectedObjectFromSource(go);
if (sourceGo == null)
return;
m_ComponentsInPrefabSource = sourceGo.GetComponents<Component>();
Component[] actuallyRemovedComponents = PrefabUtility.GetRemovedComponents(PrefabUtility.GetPrefabInstanceHandle(go));
var removedComponentsList = PrefabOverridesUtility.GetRemovedComponentsForSingleGameObject(go);
for (int i = 0; i < removedComponentsList.Count; i++)
{
if (actuallyRemovedComponents.Contains(removedComponentsList[i].assetComponent))
m_RemovedComponents.Add(removedComponentsList[i].assetComponent);
else
m_SuppressedComponents.Add(removedComponentsList[i].assetComponent);
}
}
protected void CreatePreviewables()
{
if (m_Previews != null)
return;
m_Previews = new List<IPreviewable>();
var activeEditors = tracker?.activeEditors;
if (activeEditors == null || activeEditors.Length == 0)
return;
foreach (var editor in activeEditors)
{
IEnumerable<IPreviewable> previews = GetPreviewsForType(editor);
foreach (var preview in previews)
{
m_Previews.Add(preview);
}
}
}
protected void ClearPreviewables()
{
if (m_Previews == null)
return;
for (int i = 0, c = m_Previews.Count; i < c; i++)
m_Previews[i]?.Cleanup();
m_Previews = null;
}
private Dictionary<Type, List<Type>> GetPreviewableTypes()
{
// We initialize this list once per PropertyEditor, instead of globally.
// This means that if the user is debugging an IPreviewable structure,
// the PropertyEditor can be closed and reopened to refresh this list.
//
if (m_PreviewableTypes == null)
{
InspectorWindowUtils.GetPreviewableTypes(out m_PreviewableTypes);
}
return m_PreviewableTypes;
}
private IEnumerable<IPreviewable> GetPreviewsForType(Editor editor)
{
// Retrieve the type we are looking for.
if (editor == null || editor.target == null)
return Enumerable.Empty<IPreviewable>();
Type targetType = editor.target.GetType();
var previewableTypes = GetPreviewableTypes();
if (previewableTypes == null || !previewableTypes.TryGetValue(targetType, out var previewerList) || previewerList == null)
return Enumerable.Empty<IPreviewable>();
List<IPreviewable> previews = new List<IPreviewable>();
foreach (var previewerType in previewerList)
{
var instance = Activator.CreateInstance(previewerType);
if (instance is IPreviewable preview)
{
preview.Initialize(editor.targets);
previews.Add(preview);
}
}
return previews;
}
private void ClearTrackerDirtyOnRepaint()
{
if (Event.current.type == EventType.Repaint)
{
tracker.ClearDirty();
}
}
public IMGUIContainer CreateIMGUIContainer(Action onGUIHandler, string name = null)
{
IMGUIContainer result = null;
if (m_TrackerResetInserted)
{
result = new IMGUIContainer(onGUIHandler);
}
else
{
m_TrackerResetInserted = true;
result = new IMGUIContainer(() =>
{
ClearTrackerDirtyOnRepaint();
onGUIHandler();
});
}
if (name != null)
{
result.name = name;
}
return result;
}
static readonly ProfilerMarker k_CreateInspectorElements = new ProfilerMarker("PropertyEditor.CreateInspectorElements");
protected virtual void BeginRebuildContentContainers() {}
protected virtual void EndRebuildContentContainers() {}
internal virtual void RebuildContentsContainers()
{
ClearPreviewables();
m_SelectedPreview = null;
m_TypeSelectionList = null;
m_FirstInitialize = false;
editorsWithImportedObjectLabel.Clear();
m_LastInitialEditorInstanceID = 0;
if (m_RemovedPrefabComponentsElement != null)
{
m_RemovedPrefabComponentsElement.RemoveFromHierarchy();
m_RemovedPrefabComponentsElement = null;
}
if (m_RemovedComponentDict != null)
{
m_RemovedComponentDict = null;
m_AdditionalRemovedComponents = null;
}
BeginRebuildContentContainers();
ResetKeyboardControl();
var addComponentButton = rootVisualElement.Q(className: s_AddComponentClassName);
if (addComponentButton != null)
addComponentButton.Clear();
if (versionControlElement != null)
versionControlElement.Clear();
if (previewAndLabelElement != null)
previewAndLabelElement.Clear();
Editor[] editors = tracker.activeEditors;
// Fix for a swapping an `m_Script` field in debug mode followed by an undo/redo. This causes the serialized object to be reset back to it's previous type.
// The editor instance remains the same, the serialized object remains the same and property iterators return the previous type properties.
// Here we track the last built editor types which is compared during the next undo-redo operation.
m_EditorTargetTypes.Clear();
foreach (var editor in editors)
m_EditorTargetTypes.Add(editor.target ? editor.target.GetType() : null);
if (editors.Any() && versionControlElement != null)
{
versionControlElement.Add(CreateIMGUIContainer(
() => VersionControlBar(editors)));
}
DrawEditors(editors);
var labelMustBeAdded = editorsElement != null && m_MultiEditLabel.parent != editorsElement;
// The PrefabImporterEditor can hide its imported objects if it detects missing scripts. In this case
// do not add the multi editing warning
var assetImporter = GetAssetImporter(editors);
if (assetImporter != null && !assetImporter.showImportedObject)
labelMustBeAdded = false;
if (tracker.hasComponentsWhichCannotBeMultiEdited)
{
if (editors.Length == 0 && !tracker.isLocked && Selection.objects.Length > 0 && editorsElement != null)
{
editorsElement.Add(CreateIMGUIContainer(DrawSelectionPickerList));
}
else
{
if (labelMustBeAdded && editorsElement != null)
{
editorsElement.Add(m_MultiEditLabel);
}
}
}
else if (m_MultiEditLabel != null)
{
m_MultiEditLabel.RemoveFromHierarchy();
}
if (addComponentButton != null && editors.Any() && RootEditorUtils.SupportsAddComponent(editors))
{
addComponentButton.Add(CreateIMGUIContainer(() =>
{
EditorGUI.indentLevel = 0;
AddComponentButton(editors);
}));
}
if(m_SplitView == null)
m_SplitView = rootVisualElement.Q<TwoPaneSplitView>();
ClearPreview();
if (m_PreviewResizer != null && editors.Any())
{
if (previewAndLabelElement != null && !hasFloatingPreviewWindow)
{
VisualElement previewItem = null;
CreatePreviewables();
IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors);
m_cachedPreviewEditor = GetEditorThatControlsPreview(editorsWithPreviews);
if (m_cachedPreviewEditor != null && m_cachedPreviewEditor.HasPreviewGUI())
{
previewWindow = new InspectorPreviewWindow();
preview = m_SplitView.Q(s_PreviewContainer);
preview.style.minHeight = m_PreviewMinHeight;
previewItem = m_cachedPreviewEditor.CreatePreview(previewWindow);
if (previewItem != null)
{
// Temporary naming while in transition to UITK
InitUITKPreview();
preview.Add(previewWindow);
}
else // IMGUI fallback if no UITK preview found
{
var previewAndLabelsContainer =
CreateIMGUIContainer(DrawPreviewAndLabels, s_PreviewContainer);
m_PreviewResizer.SetContainer(previewAndLabelsContainer, kBottomToolbarHeight);
previewAndLabelElement.Add(previewAndLabelsContainer);
if (preview == null)
m_SplitView.Add(previewAndLabelElement);
}
}
}
// Footer
if (previewAndLabelElement?.childCount == 0)
{
var footerContainer = CreateIMGUIContainer(DrawFooter, s_Footer);
previewAndLabelElement.Add(footerContainer);
}
}
k_CreateInspectorElements.Begin();
// Only trigger the fixed count and viewport creation if this is the first build. Otherwise let the update method handle it.
if (m_EditorElementUpdater.Position == 0 && editors.Any())
{
// Force create a certain number of inspector elements without invoking a layout pass.
// We always want a minimum number of elements to be added.
m_EditorElementUpdater.CreateInspectorElementsWithoutLayout(k_CreateInspectorElementMinCount);
// Continue creating elements until the viewport is full.
m_EditorElementUpdater.CreateInspectorElementsForViewport(m_ScrollView, editorsElement);
}
k_CreateInspectorElements.End();
rootVisualElement.MarkDirtyRepaint();
ScriptAttributeUtility.ClearGlobalCache();
EndRebuildContentContainers();
Repaint();
RefreshTitle();
}
void ClearPreview()
{
if (m_Previews == null)
{
if (m_SplitView?.fixedPane?.resolvedStyle != null)
{
float height = m_SplitView.fixedPane.resolvedStyle.height;
if(height != 0 && height != m_PreviewMinHeight)
m_CachedPreviewHeight = height;
}
UpdatePreviewHeight(0);
m_cachedPreviewEditor = null;
if(preview?.childCount > 0 && previewWindow != null && preview.Q(previewWindow.name) != null)
preview.Remove(previewWindow);
var footer = previewAndLabelElement?.Q(s_Footer);
if(previewAndLabelElement?.childCount > 0 && footer != null)
previewAndLabelElement.Remove(footer);
}
}
void InitUITKPreview()
{
// Toolbar
PrepareToolbar(previewWindow);
UpdateLabel(previewWindow);
// Dragline
m_SplitView.AddToClassList(InspectorPreviewWindow.Styles.ussClassName);
var draglineAnchor = m_SplitView.Q(s_draglineAnchor);
var dragline = draglineAnchor.Q(s_dragline);
dragline.style.height = m_PreviewMinHeight;
dragline.RegisterCallback<GeometryChangedEvent>(e =>
OnDraglineGeometryChange(previewWindow, dragline));
draglineAnchor.RegisterCallback<PointerUpEvent>(OnDragLineChange);
UpdatePreviewHeight(m_CachedPreviewHeight);
// IMGUI Preview
VisualElement previewPane = previewWindow.GetPreviewPane();
if (previewPane.childCount == 0)
{
var previewAndLabelsContainer =
CreateIMGUIContainer(() => DrawPreview(m_cachedPreviewEditor), "preview");
previewPane.Add(previewAndLabelsContainer);
}
}
private void OnDraglineGeometryChange(VisualElement window, VisualElement dragline)
{
if (window == null)
return;
var header = window.Q(InspectorPreviewWindow.Styles.headerName);
var toolbar = header?.Q(InspectorPreviewWindow.Styles.toolbarName);
var ellipsisMenu = header?.Q(InspectorPreviewWindow.Styles.elipsisMenuName);
float margin = dragline.resolvedStyle.marginRight;
if (header != null && toolbar != null && ellipsisMenu != null)
{
margin = toolbar.resolvedStyle.width + ellipsisMenu.resolvedStyle.width;
}
dragline.style.marginRight = margin;
}
internal void PrepareToolbar(InspectorPreviewWindow toolbar, bool isFloatingPreviewWindow = false)
{
IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors);
IPreviewable previewEditor = GetEditorThatControlsPreview(editorsWithPreviews);
if(!isFloatingPreviewWindow)
CreatePreviewEllipsisMenu(toolbar, this);
}
internal void UpdateLabel(InspectorPreviewWindow toolbar)
{
IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors);
IPreviewable previewEditor = GetEditorThatControlsPreview(editorsWithPreviews);
string label;
if (previewEditor != null && previewEditor.HasPreviewGUI())
{
string userDefinedTitle = previewEditor.GetPreviewTitle().text;
label = !String.IsNullOrEmpty(userDefinedTitle)? userDefinedTitle : Styles.preTitle.text;
}
else
{
label = Styles.labelTitle.text;
}
var header = toolbar?.Q(InspectorPreviewWindow.Styles.headerName);
if (header?.Q(InspectorPreviewWindow.Styles.titleName) is Label labelElement)
{
labelElement.text = label;
}
}
public bool showingPreview => m_SplitView?.fixedPane?.resolvedStyle.height > m_PreviewMinHeight;
void UpdatePreviewHeight(float newHeight)
{
var draglineAnchor = m_SplitView?.Q(s_draglineAnchor);
if (draglineAnchor != null && m_SplitView.fixedPane != null)
{
m_SplitView.fixedPane.style.height = newHeight;
m_SplitView.fixedPaneDimension = newHeight;
draglineAnchor.style.top = m_SplitView.resolvedStyle.height - newHeight;
}
}
private void OnDragLineChange(PointerUpEvent evt)
{
var previewHeight = m_SplitView.fixedPane.resolvedStyle.height;
var isSingleClick = (previewHeight == m_CachedPreviewHeight || previewHeight == m_PreviewMinHeight)
&& Math.Abs(m_SplitView.m_Resizer.delta) <= 5;
if (isSingleClick && evt.button == (int) MouseButton.LeftMouse)
{
ExpandCollapsePreview();
return;
}
if (!showingPreview) return;
m_CachedPreviewHeight = previewHeight;
}
internal void ExpandCollapsePreview()
{
if (showingPreview)
{
m_CachedPreviewHeight = m_SplitView.fixedPane.resolvedStyle.height;
UpdatePreviewHeight(m_PreviewMinHeight);
m_CachedPreviewHeight = m_PreviewMinHeight;
}
else
{
UpdatePreviewHeight(m_CachedPreviewHeight);
}
}
internal void AutoScroll(Vector2 mousePosition)
{
if (m_ScrollView != null)
{
// implement auto-scroll for easier component drag'n'drop,
// we define a zone of height = k_AutoScrollZoneHeight
// at the top/bottom of the scrollView viewport,
// while dragging, when the mouse moves in these zones,
// we automatically scroll up/down
var localDragPosition = m_ScrollView.contentViewport.WorldToLocal(mousePosition);
if (localDragPosition.y < k_AutoScrollZoneHeight)
m_ScrollView.verticalScroller.ScrollPageUp();
else if (localDragPosition.y > m_ScrollView.contentViewport.rect.height - k_AutoScrollZoneHeight)
m_ScrollView.verticalScroller.ScrollPageDown();
}
}
internal void ScrollTo(Vector2 position)
{
if (m_ScrollView != null)
{
var localDragPosition = m_ScrollView.contentViewport.WorldToLocal(position);
if (localDragPosition.y < k_AutoScrollZoneHeight)
m_ScrollView.verticalScroller.value += localDragPosition.y - k_AutoScrollZoneHeight;
else if (localDragPosition.y > m_ScrollView.contentViewport.rect.height - k_AutoScrollZoneHeight)
m_ScrollView.verticalScroller.value += localDragPosition.y - (m_ScrollView.contentViewport.rect.height - k_AutoScrollZoneHeight);
}
}
private void DragOverBottomArea(DragUpdatedEvent dragUpdatedEvent)
{
if (DragAndDrop.objectReferences.Any())
{
if (editorsElement != null && editorsElement.ContainsPoint(editorsElement.WorldToLocal(dragUpdatedEvent.mousePosition)))
{
AutoScroll(dragUpdatedEvent.mousePosition);
return;
}
if (editorsElement != null)
{
var lastChild = editorsElement.Children().LastOrDefault();
if (lastChild == null)
return;
editorDragging.HandleDraggingInBottomArea(tracker.activeEditors, bottomAreaDropRectangle, lastChild.layout);
}
}
}
private void DragPerformInBottomArea(DragPerformEvent dragPerformedEvent)
{
if (editorsElement == null)
return;
if (editorsElement.ContainsPoint(editorsElement.WorldToLocal(dragPerformedEvent.mousePosition)))
return;
var lastChild = editorsElement.Children().LastOrDefault();
if (lastChild == null)
return;
editorDragging.HandleDragPerformInBottomArea(tracker.activeEditors, bottomAreaDropRectangle, lastChild.layout);
}
internal virtual Editor GetLastInteractedEditor()
{
return lastInteractedEditor;
}
protected IPreviewable GetEditorThatControlsPreview(IPreviewable[] editors)
{
if (editors.Length == 0)
return null;
if (m_SelectedPreview != null)
{
return m_SelectedPreview;
}
// Find last interacted editor, if not found check if we had an editor of similar type,
// if not found use first editor that can show a preview otherwise return null.
IPreviewable lastInteractedEditor = GetLastInteractedEditor();
Type lastType = lastInteractedEditor?.GetType();
IPreviewable firstEditorThatHasPreview = null;
IPreviewable similarEditorAsLast = null;
foreach (IPreviewable e in editors)
{
if (e == null || e.target == null)
continue;
// If target is an asset, but not the same asset as the asset
// of the first editor, then ignore it. This will prevent showing
// preview of materials attached to a GameObject but should cover
// future use cases as well.
if (EditorUtility.IsPersistent(e.target) &&
AssetDatabase.GetAssetPath(e.target) != AssetDatabase.GetAssetPath(editors[0].target))
continue;
// If main editor is an asset importer editor and this is an editor of the imported object, ignore.
if (editors[0] is AssetImporterEditor && !(e is AssetImporterEditor))
continue;
if (e.HasPreviewGUI())
{
if (e == lastInteractedEditor)
return e;
if (similarEditorAsLast == null && e.GetType() == lastType)
similarEditorAsLast = e;
if (firstEditorThatHasPreview == null)
firstEditorThatHasPreview = e;
}
}
if (similarEditorAsLast != null)
return similarEditorAsLast;
if (firstEditorThatHasPreview != null)
return firstEditorThatHasPreview;
// Found no valid editor
return null;
}
protected IPreviewable[] GetEditorsWithPreviews(Editor[] editors)
{
IList<IPreviewable> editorsWithPreview = new List<IPreviewable>();
int i = -1;
foreach (Editor e in editors)
{
++i;
if (!e || e.target == null)
continue;
// If target is an asset, but not the same asset as the asset
// of the first editor, then ignore it. This will prevent showing
// preview of materials attached to a GameObject but should cover
// future use cases as well.
if (EditorUtility.IsPersistent(e.target) &&
AssetDatabase.GetAssetPath(e.target) != AssetDatabase.GetAssetPath(editors[0].target))
continue;
if (!EditorUtility.IsPersistent(editors[0].target) && EditorUtility.IsPersistent(e.target))
continue;
if (ShouldCullEditor(editors, i))
continue;
// If main editor is an asset importer editor and this is an editor of the imported object, ignore.
if (editors[0] is AssetImporterEditor && !(e is AssetImporterEditor))
continue;
if (e.HasPreviewGUI())
{
editorsWithPreview.Add(e);
}
}
if (m_Previews == null) return new IPreviewable[] {};
foreach (var previewable in m_Previews)
{
if (previewable.HasPreviewGUI())
editorsWithPreview.Add(previewable);
}
return editorsWithPreview.ToArray();
}
internal virtual Object GetInspectedObject()
{
return m_InspectedObject;
}
private void ResetKeyboardControl()
{
if (m_ResetKeyboardControl)
{
GUIUtility.keyboardControl = 0;
m_ResetKeyboardControl = false;
}
}
private static bool IsOpenForEdit(Object target)
{
if (EditorUtility.IsPersistent(target))
{
var assetPath = AssetDatabase.GetAssetPath(target);
return Provider.PathHasMetaFile(assetPath) && AssetDatabase.IsMetaFileOpenForEdit(target);
}
return false;
}
private Object[] GetInspectedAssets()
{
// We use this technique to support locking of the inspector. An inspector locks via an editor, so we need to use an editor to get the selection
Editor assetEditor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(tracker.activeEditors);
if (assetEditor != null && assetEditor.targets.Length == 1)
{
string assetPath = AssetDatabase.GetAssetPath(assetEditor.target);
if (IsOpenForEdit(assetEditor.target) && !Directory.Exists(assetPath))
return assetEditor.targets;
}
// This is used if more than one asset is selected
// Ideally the tracker should be refactored to track not just editors but also the selection that caused them, so we wouldn't need this
return Selection.objects.Where(EditorUtility.IsPersistent).ToArray();
}
protected virtual bool BeginDrawPreviewAndLabels() { return true; }
protected virtual void EndDrawPreviewAndLabels(Event evt, Rect rect, Rect dragRect) {}
protected virtual void CreatePreviewEllipsisMenu(InspectorPreviewWindow window, PropertyEditor editor) {}
TwoPaneSplitView m_SplitView = null;
VisualElement preview = null;
internal InspectorPreviewWindow previewWindow = null;
private void DrawPreviewAndLabels()
{
CreatePreviewables();
var hasPreview = BeginDrawPreviewAndLabels();
IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors);
IPreviewable previewEditor = GetEditorThatControlsPreview(editorsWithPreviews);
// Do we have a preview?
m_HasPreview = previewEditor != null && previewEditor.HasPreviewGUI() && hasPreview;
m_PreviewResizer.containerMinimumHeightExpanded = m_HasPreview ? k_InspectorPreviewMinTotalHeight : 0;
Object[] assets = GetInspectedAssets();
bool hasLabels = assets.Length > 0;
bool hasBundleName = assets.Any(a => !(a is MonoScript) && AssetDatabase.IsMainAsset(a));
if (!m_HasPreview && !hasLabels)
return;
Event evt = Event.current;
// Preview / Asset Labels toolbar
Rect dragRect;
Rect dragIconRect = new Rect();
const float dragPadding = 3f;
const float minDragWidth = 20f;
Rect rect = EditorGUILayout.BeginHorizontal(GUIContent.none, Styles.preToolbar, GUILayout.Height(kBottomToolbarHeight));
{
GUILayout.FlexibleSpace();
dragRect = GUILayoutUtility.GetLastRect();
GUIContent title;
if (m_HasPreview)
{
GUIContent userDefinedTitle = previewEditor.GetPreviewTitle();
title = userDefinedTitle ?? Styles.preTitle;
}
else
{
title = Styles.labelTitle;
}
dragIconRect.x = dragRect.x + dragPadding;
dragIconRect.y = dragRect.y + (kBottomToolbarHeight - Styles.dragHandle.fixedHeight) / 2;
dragIconRect.width = dragRect.width - dragPadding * 2;
dragIconRect.height = Styles.dragHandle.fixedHeight;
//If we have more than one component with Previews, show a DropDown menu.
if (editorsWithPreviews.Length > 1)
{
Vector2 foldoutSize = Styles.preDropDown.CalcSize(title);
float maxFoldoutWidth = (dragIconRect.xMax - dragRect.xMin) - dragPadding - minDragWidth;
float foldoutWidth = Mathf.Min(maxFoldoutWidth, foldoutSize.x);
Rect foldoutRect = new Rect(dragRect.x, dragRect.y, foldoutWidth, foldoutSize.y);
dragRect.xMin += foldoutWidth;
dragIconRect.xMin += foldoutWidth;
GUIContent[] panelOptions = new GUIContent[editorsWithPreviews.Length];
int selectedPreview = -1;
for (int index = 0; index < editorsWithPreviews.Length; index++)
{
IPreviewable currentEditor = editorsWithPreviews[index];
GUIContent previewTitle = currentEditor.GetPreviewTitle() ?? Styles.preTitle;
string fullTitle;
if (previewTitle == Styles.preTitle)
{
string componentTitle = ObjectNames.GetTypeName(currentEditor.target);
if (NativeClassExtensionUtilities.ExtendsANativeType(currentEditor.target))
{
componentTitle = MonoScript.FromScriptedObject(currentEditor.target).GetClass()
.Name;
}
fullTitle = previewTitle.text + " - " + componentTitle;
}
else
{
fullTitle = previewTitle.text;
}
panelOptions[index] = new GUIContent(fullTitle);
if (editorsWithPreviews[index] == previewEditor)
{
selectedPreview = index;
}
}
if (GUI.Button(foldoutRect, title, Styles.preDropDown))
{
EditorUtility.DisplayCustomMenu(foldoutRect, panelOptions, selectedPreview,
OnPreviewSelected, editorsWithPreviews);
}
}
else
{
float maxLabelWidth = (dragIconRect.xMax - dragRect.xMin) - dragPadding - minDragWidth;
float labelWidth = Mathf.Min(maxLabelWidth, Styles.preToolbar2.CalcSize(title).x);
Rect labelRect = new Rect(dragRect.x, dragRect.y, labelWidth, dragRect.height);
dragIconRect.xMin = labelRect.xMax + dragPadding;
GUI.Label(labelRect, title, Styles.preToolbarLabel);
}
if (m_HasPreview && Event.current.type == EventType.Repaint)
{
// workaround: To properly center the image because it already has a 1px bottom padding
dragIconRect.y += 1;
Styles.dragHandle.Draw(dragIconRect, GUIContent.none, false, false, false, false);
}
if (m_HasPreview && m_PreviewResizer.GetExpandedBeforeDragging())
previewEditor.OnPreviewSettings();
EndDrawPreviewAndLabels(evt, rect, dragRect);
}
EditorGUILayout.EndHorizontal();
// Logic for resizing and collapsing
float previewSize;
if (m_HasPreview)
{
// If we have a preview we'll use the ResizerControl which handles both resizing and collapsing
previewSize = m_PreviewResizer.ResizeHandle(position, k_InspectorPreviewMinTotalHeight, k_MinAreaAbovePreview, kBottomToolbarHeight, dragRect);
}
else
{
// If we don't have a preview, just toggle the collapsible state with a button
if (GUI.Button(rect, GUIContent.none, GUIStyle.none))
m_PreviewResizer.ToggleExpanded();
previewSize = 0;
}
// If collapsed, early out
if (!m_PreviewResizer.GetExpanded())
{
if (m_PreviousPreviewExpandedState)
{
UIEventRegistration.MakeCurrentIMGUIContainerDirty();
m_PreviousPreviewExpandedState = false;
}
m_PreviousFooterHeight = previewSize;
return;
}
// The preview / label area (not including the toolbar)
GUILayout.BeginVertical(Styles.preBackground, GUILayout.Height(previewSize));
{
// Draw preview
if (m_HasPreview)
{
DrawPreview(previewEditor);
}
DrawFooter();
}
GUILayout.EndVertical();
if (m_PreviousFooterHeight >= 0f && !FloatComparer.s_ComparerWithDefaultTolerance.Equals(previewSize, m_PreviousFooterHeight))
{
UIEventRegistration.MakeCurrentIMGUIContainerDirty();
}
m_PreviousFooterHeight = previewSize;
m_PreviousPreviewExpandedState = m_PreviewResizer.GetExpanded();
}
private void DrawPreview(IPreviewable editor)
{
var previewRect = GUILayoutUtility.GetRect(0, 10240, 64, 10240);
if (!float.IsNaN(previewRect.height) && !float.IsNaN(previewRect.width))
{
editor.DrawPreview(previewRect);
}
}
private void DrawFooter()
{
Object[] assets = GetInspectedAssets();
bool hasLabels = assets.Length > 0;
bool hasBundleName = assets.Any(a => !(a is MonoScript) && AssetDatabase.IsMainAsset(a));
IPreviewable[] editorsWithPreviews = GetEditorsWithPreviews(tracker.activeEditors);
IPreviewable previewEditor = GetEditorThatControlsPreview(editorsWithPreviews);
if (previewEditor == null || !previewEditor.HasPreviewGUI())
{
GUILayout.BeginVertical(Styles.footer);
GUILayout.Label(Styles.labelTitle, Styles.preToolbarLabel);
GUILayout.EndVertical();
}
GUILayout.BeginVertical(Styles.footer);
if (hasLabels)
{
using (new EditorGUI.DisabledScope(assets.Any(a => !IsOpenForEdit(a) || !Editor.IsAppropriateFileOpenForEdit(a))))
{
m_LabelGUI.OnLabelGUI(assets);
}
}
if (hasBundleName)
{
using (new EditorGUI.DisabledScope(assets.Any(a => !IsOpenForEdit(a))))
{
m_AssetBundleNameGUI.OnAssetBundleNameGUI(assets);
}
}
GUILayout.EndVertical();
}
private void OnPreviewSelected(object userData, string[] options, int selected)
{
IPreviewable[] availablePreviews = userData as IPreviewable[];
m_SelectedPreview = availablePreviews[selected];
}
internal static void VersionControlBar(Editor assetEditor) => VersionControlBar(new[] { assetEditor });
internal static void VersionControlBar(Editor[] assetEditors)
{
Editor assetEditor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(assetEditors);
var vco = VersionControlManager.activeVersionControlObject;
if (vco != null)
{
vco.GetExtension<IInspectorWindowExtension>()?.OnVersionControlBar(assetEditor);
return;
}
if (!Provider.enabled)
return;
var vcsMode = VersionControlSettings.mode;
if (vcsMode == ExternalVersionControl.Generic || vcsMode == ExternalVersionControl.Disabled || vcsMode == ExternalVersionControl.AutoDetect)
return;
var assetPath = AssetDatabase.GetAssetPath(assetEditor.target);
Asset asset = Provider.GetAssetByPath(assetPath);
if (asset == null)
return;
if (!VersionControlUtils.IsPathVersioned(asset.path))
return;
var connected = Provider.isActive;
// Note: files under project settings do not have .meta files next to them,
// but Provider.GetAssetByPath API helpfully (or unhelpfully, in this case)
// checks if passed file ends with "meta" and says "here, take this asset instead"
// if it exists -- so for files under project settings, it ends up returning
// a valid entry for the non-existing meta file. So just don't do it.
Asset metaAsset = null;
if (Provider.PathHasMetaFile(asset.path))
metaAsset = Provider.GetAssetByPath(assetPath.Trim('/') + ".meta");
string currentState = asset.StateToString();
string currentMetaState = metaAsset == null ? String.Empty : metaAsset.StateToString();
// If VCS is enabled but disconnected, the assets will have "Updating" state most of the time,
// but what we want to displays is a note that VCS is not connected.
if (!connected)
{
if (EditorUserSettings.WorkOffline)
currentState = Styles.vcsOffline.text;
else
currentState = string.Format(Styles.vcsNotConnected.text, Provider.GetActivePlugin().name);
currentMetaState = currentState;
}
var hasAssetState = !string.IsNullOrEmpty(currentState);
var hasMetaState = !string.IsNullOrEmpty(currentMetaState);
// Cache AssetList for current selection and
// figure out which buttons we'll need to show for them.
VersionControlBarState state;
if (!m_VersionControlBarState.TryGetValue(assetEditor, out state))
{
state = VersionControlBarState.Calculate(assetEditors, asset, connected);
m_VersionControlBarState.Add(assetEditor, state);
}
// Based on that and the current inspector width, we might want to layout the VCS
// bar in two rows to better fit status label & buttons.
var approxSpaceForButtons = state.GetButtonCount() * 50;
var useTwoRows = GUIView.current != null && GUIView.current.position.width * 0.5f < approxSpaceForButtons;
var lineHeight = Styles.vcsBarStyleOneRow.fixedHeight;
var barStyle = useTwoRows ? Styles.vcsBarStyleTwoRows : Styles.vcsBarStyleOneRow;
GUILayout.BeginHorizontal(GUIContent.none, barStyle);
var barRect = GUILayoutUtility.GetRect(GUIContent.none, barStyle, GUILayout.ExpandWidth(true));
var icon = AssetDatabase.GetCachedIcon(assetPath) as Texture2D;
var overlayRect = new Rect(barRect.x, barRect.y + 1, 28, 16);
var iconRect = overlayRect;
iconRect.x += 6;
iconRect.width = 16;
if (icon != null)
GUI.DrawTexture(iconRect, icon);
Overlay.DrawOtherOverlay(asset, metaAsset ?? asset, overlayRect);
if (currentMetaState != currentState)
{
if (hasAssetState && hasMetaState)
currentState = currentState + "; meta: " + currentMetaState;
else if (hasAssetState && metaAsset != null) // project settings don't even have .meta files; no point in adding "asset only" for them
currentState = currentState + " (asset only)";
else if (hasMetaState)
currentState = currentMetaState + " (meta only)";
}
var buttonsRect = barRect;
buttonsRect.yMin = buttonsRect.yMax - lineHeight;
var buttonX = VersionControlBarButtons(state, buttonsRect, connected);
var textRect = barRect;
textRect.height = lineHeight;
textRect.xMin += 26;
if (!useTwoRows)
textRect.xMax = buttonX;
var content = GUIContent.Temp(currentState);
var fullState = Asset.AllStateToString(asset.state);
var fullMetaState = metaAsset != null ? Asset.AllStateToString(metaAsset.state) : string.Empty;
if (fullState != fullMetaState)
fullState = $"Asset state: {fullState}\nMeta state: {fullMetaState}";
else
fullState = "State: " + fullState;
content.tooltip = fullState;
GUI.Label(textRect, content, EditorStyles.label);
GUILayout.EndHorizontal();
VersionControlCheckoutHint(assetEditor, connected);
}
private static void VersionControlCheckoutHint(Editor assetEditor, bool connected)
{
if (!connected)
return;
const string prefKeyName = "vcs_CheckoutHintClosed";
var removedHint = EditorPrefs.GetBool(prefKeyName);
if (removedHint)
return;
if (Editor.IsAppropriateFileOpenForEdit(assetEditor.target))
return;
// allow clicking the help note to make it go away via prefs
if (GUILayout.Button(Styles.vcsCheckoutHint, EditorStyles.helpBox))
EditorPrefs.SetBool(prefKeyName, true);
GUILayout.Space(4);
}
internal static void CheckoutForInspector(Object[] targets)
{
if (targets == null || targets.Length < 0) return;
AssetList inspectorAssets = new AssetList();
// Since we can't edit multiple asset types in one Inspector it is safe to say
// that we will have to checkout all assets in the same way as the first one.
bool needToCheckoutBoth = AssetDatabase.CanOpenAssetInEditor(targets[0].GetInstanceID());
foreach (var asset in targets)
{
string assetPath = AssetDatabase.GetAssetPath(asset);
if (needToCheckoutBoth)
{
Asset actualAsset = Provider.CacheStatus(assetPath);
if (actualAsset != null) inspectorAssets.Add(actualAsset);
}
Asset metaAsset = Provider.CacheStatus(AssetDatabase.GetTextMetaFilePathFromAssetPath(assetPath));
if (metaAsset != null) inspectorAssets.Add(metaAsset);
}
Provider.Checkout(inspectorAssets, CheckoutMode.Exact);
}
private static void DoRevertUnchanged(object o)
{
var al = (AssetList)o;
Provider.Revert(al, RevertMode.Unchanged);
}
private static float VersionControlBarButtons(VersionControlBarState presence, Rect rect, bool connected)
{
var buttonX = rect.xMax - 7;
var buttonRect = rect;
var buttonStyle = Styles.vcsButtonStyle;
buttonRect.y += 1;
buttonRect.height = buttonStyle.CalcSize(Styles.vcsAdd).y;
if (!connected)
{
if (presence.settings)
{
if (VersionControlActionButton(buttonRect, ref buttonX, Styles.vcsSettings))
SettingsService.OpenProjectSettings("Project/Version Control");
}
return buttonX;
}
if (presence.revert && !presence.revertUnchanged)
{
// just a simple revert button
if (VersionControlActionButton(buttonRect, ref buttonX, Styles.vcsRevert))
{
WindowRevert.Open(presence.assets);
GUIUtility.ExitGUI();
}
}
else if (presence.revert || presence.revertUnchanged)
{
// revert + revert unchanged dropdown button
if (VersionControlActionDropdownButton(buttonRect, ref buttonX, Styles.vcsRevert,
Styles.vcsRevertMenuNames, Styles.vcsRevertMenuActions, presence.assets))
{
if (presence.revert)
{
WindowRevert.Open(presence.assets);
GUIUtility.ExitGUI();
}
}
}
if (presence.checkout)
{
if (VersionControlActionButton(buttonRect, ref buttonX, AssetDatabase.CanOpenAssetInEditor(presence.Editor.target.GetInstanceID()) ? Styles.vcsCheckout : Styles.vcsCheckoutMeta))
CheckoutForInspector(presence.Editor.targets);
}
if (presence.add)
{
if (VersionControlActionButton(buttonRect, ref buttonX, Styles.vcsAdd))
Provider.Add(presence.assets, true).Wait();
}
if (presence.submit)
{
if (VersionControlActionButton(buttonRect, ref buttonX, Styles.vcsSubmit))
WindowChange.Open(presence.assets, true);
}
if (presence.@lock)
{
if (VersionControlActionButton(buttonRect, ref buttonX, Styles.vcsLock))
Provider.Lock(presence.assets, true).Wait();
}
if (presence.unlock)
{
if (VersionControlActionButton(buttonRect, ref buttonX, Styles.vcsUnlock))
Provider.Lock(presence.assets, false).Wait();
}
return buttonX;
}
private static bool VersionControlActionDropdownButton(Rect buttonRect, ref float buttonX, GUIContent content, GUIContent[] menuNames, GenericMenu.MenuFunction2[] menuActions, object context)
{
var dropdownStyle = Styles.vcsRevertStyle;
const float kDropDownButtonWidth = 20f;
buttonRect.width = dropdownStyle.CalcSize(content).x + 6;
buttonRect.x = buttonX - buttonRect.width;
buttonX -= buttonRect.width;
var dropDownRect = buttonRect;
dropDownRect.xMin = dropDownRect.xMax - kDropDownButtonWidth;
if (Event.current.type == EventType.MouseDown && dropDownRect.Contains(Event.current.mousePosition))
{
var menu = new GenericMenu();
for (var i = 0; i < menuNames.Length; ++i)
menu.AddItem(menuNames[i], false, menuActions[i], context);
menu.DropDown(buttonRect);
Event.current.Use();
}
else
{
return GUI.Button(buttonRect, content, dropdownStyle);
}
return false;
}
private static bool VersionControlActionButton(Rect buttonRect, ref float buttonX, GUIContent content)
{
var buttonStyle = Styles.vcsButtonStyle;
buttonRect.width = buttonStyle.CalcSize(content).x;
buttonRect.x = buttonX - buttonRect.width;
buttonX -= buttonRect.width;
return GUI.Button(buttonRect, content, buttonStyle);
}
private void DrawEditors(Editor[] editors)
{
if (editorsElement == null)
return;
Dictionary<int, IEditorElement> mapping = null;
var selection = new HashSet<int>(Selection.instanceIDs);
if (m_DrawnSelection.SetEquals(selection))
{
if (editorsElement.childCount > 0 && m_DrawnSelection.Any()) // do we already have a hierarchy
{
mapping = ProcessEditorElementsToRebuild(editors);
}
}
else
{
m_DrawnSelection.Clear();
m_DrawnSelection = selection;
}
if (mapping == null)
{
editorsElement.Clear();
m_EditorElementUpdater.Clear();
}
if (editors.Length == 0)
{
// Release references to prefabs so they can be removed by GC
m_ComponentsInPrefabSource = null;
return;
}
Editor.m_AllowMultiObjectAccess = true;
if (editors.Length > 0 && editors[0].GetInstanceID() != m_LastInitialEditorInstanceID)
OnTrackerRebuilt();
if (m_RemovedComponents == null)
ExtractPrefabComponents(); // needed after assembly reload (due to HashSet not being serializable)
int targetGameObjectIndex = -1;
GameObject targetGameObject = null;
if (m_ComponentsInPrefabSource != null)
{
targetGameObjectIndex = editors[0] is PrefabImporterEditor ? 1 : 0;
targetGameObject = (GameObject)editors[targetGameObjectIndex].target;
}
if (m_ComponentsInPrefabSource != null && m_RemovedComponents.Count > 0 && m_RemovedComponentDict == null)
DetermineInsertionPointOfVisualElementForRemovedComponent(targetGameObjectIndex, editors);
for (int editorIndex = 0; editorIndex < editors.Length; editorIndex++)
{
if (!editors[editorIndex])
continue;
editors[editorIndex].propertyViewer = this;
VisualElement prefabsComponentElement = new VisualElement() { name = "PrefabComponentElement" };
Object target = editors[editorIndex].target;
if (m_RemovedComponentDict != null && m_RemovedComponentDict.ContainsKey(editorIndex))
{
var objectList = m_RemovedComponentDict[editorIndex];
foreach (var sourceComponent in objectList)
AddRemovedPrefabComponentElement(targetGameObject, sourceComponent, prefabsComponentElement);
}
try
{
var editor = editors[editorIndex];
Object editorTarget = editor.targets[0];
if (ShouldCullEditor(editors, editorIndex))
{
editor.isInspectorDirty = false;
// Adds an empty IMGUIContainer to prevent infinite repainting (case 1264833).
// EXCEPT for the ParticleSystemRenderer, because it prevents the ParticleSystem inspector
// from working correctly when setting the Material for its renderer (case 1308966).
if (!(editor.target is ParticleSystemRenderer) && (mapping == null || !mapping.TryGetValue(editor.target.GetInstanceID(),
out var culledEditorContainer)))
{
culledEditorContainer =
new UIElements.EditorElement(editorIndex, this, editors, true);
editorsElement.Add(culledEditorContainer as VisualElement);
if (!InspectorElement.disabledThrottling)
m_EditorElementUpdater.Add(culledEditorContainer);
}
continue;
}
if (mapping == null || !mapping.TryGetValue(editors[editorIndex].target.GetInstanceID(), out var editorContainer))
{
editorContainer = new UIElements.EditorElement(editorIndex, this, editors);
editorsElement.Add(editorContainer as VisualElement);
if (!InspectorElement.disabledThrottling)
m_EditorElementUpdater.Add(editorContainer);
}
if (prefabsComponentElement.childCount > 0)
{
editorContainer.AddPrefabComponent(prefabsComponentElement);
}
else
{
editorContainer.AddPrefabComponent(null);
}
}
catch (Editor.SerializedObjectNotCreatableException)
{
// This can happen after a domain reload when the
// target is a pure c# object, like a MonoBehaviour
// We'll just attempt to recreate the EditorElement on the next frame
// see case 1147234
// For some reasons the case 1302872 is also triggering that code but does not force an inspector rebuild.
// Adding a delayed call to make sure a rebuild is done regardless of the magic happening behind it.
EditorApplication.delayCall += InspectorWindow.RefreshInspectors;
}
}
// Make sure to display any remaining removed components that come after the last component on the GameObject.
if (m_AdditionalRemovedComponents != null && m_AdditionalRemovedComponents.Count() > 0)
{
VisualElement prefabsComponentElement = new VisualElement() { name = "RemainingPrefabComponentElement" };
foreach(var sourceComponent in m_AdditionalRemovedComponents)
AddRemovedPrefabComponentElement(targetGameObject, sourceComponent, prefabsComponentElement);
if (prefabsComponentElement.childCount > 0)
{
editorsElement.Add(prefabsComponentElement);
m_RemovedPrefabComponentsElement = prefabsComponentElement;
}
}
}
private void RestoreVerticalScrollIfNeeded()
{
if (m_LastInspectedObjectInstanceID == -1)
return;
var inspectedObjectInstanceID = GetInspectedObject()?.GetInstanceID() ?? -1;
if (inspectedObjectInstanceID == m_LastInspectedObjectInstanceID && inspectedObjectInstanceID != -1)
m_ScrollView.verticalScroller.value = m_LastVerticalScrollValue;
m_LastInspectedObjectInstanceID = -1; // reset to make sure the restore occurs once
}
void OnPrefabInstanceUnpacked(GameObject unpackedPrefabInstance, PrefabUnpackMode unpackMode)
{
if (m_RemovedComponents == null)
return;
// We don't use the input 'unpackedPrefabInstance', instead we reuse the ExtractPrefabComponents logic to detect
// if RebuildContentsContainers if actually needed to clear any "Component Name (Removed)" title headers.
// This prevents performance issues when unpacking a large multiselection.
var prevRemovedComponents = new HashSet<Component>(m_RemovedComponents);
ExtractPrefabComponents();
if (!prevRemovedComponents.SetEquals(m_RemovedComponents))
{
RebuildContentsContainers();
}
}
private void AddRemovedPrefabComponentElement(GameObject targetGameObject, Component nextInSource, VisualElement element)
{
if (ShouldDisplayRemovedComponent(targetGameObject, nextInSource))
{
string missingComponentTitle = ObjectNames.GetInspectorTitle(nextInSource);
var removedComponentElement =
CreateIMGUIContainer(() => DisplayRemovedComponent(targetGameObject, nextInSource), missingComponentTitle);
removedComponentElement.style.paddingBottom = kEditorElementPaddingBottom;
element.Add(removedComponentElement);
}
}
private bool ShouldDisplayRemovedComponent(GameObject go, Component comp)
{
if (m_ComponentsInPrefabSource == null || m_RemovedComponents == null)
return false;
if (go == null)
return false;
if (comp == null)
return false;
if ((comp.hideFlags & HideFlags.HideInInspector) != 0)
return false;
if (!m_RemovedComponents.Contains(comp))
return false;
if (comp.IsCoupledComponent())
return false;
return true;
}
private static void DisplayRemovedComponent(GameObject go, Component comp)
{
Rect rect = GUILayoutUtility.GetRect(GUIContent.none, EditorStyles.inspectorTitlebar);
EditorGUI.RemovedComponentTitlebar(rect, go, comp);
}
public bool WasEditorVisible(Editor[] editors, int editorIndex, Object target)
{
int wasVisibleState = tracker.GetVisible(editorIndex);
bool wasVisible;
if (wasVisibleState == -1)
{
// Some inspectors (MaterialEditor) needs to be told when they are the main visible asset.
if (editorIndex == 0 || (editorIndex == 1 && ShouldCullEditor(editors, 0)))
{
editors[editorIndex].firstInspectedEditor = true;
}
// Init our state with last state
// Large headers should always be considered visible
// because they need to at least update their Icons when they have a static preview (Material for exemple)
wasVisible = InternalEditorUtility.GetIsInspectorExpanded(target) || EditorHasLargeHeader(editorIndex, editors);
tracker.SetVisible(editorIndex, wasVisible ? 1 : 0);
}
else
{
wasVisible = wasVisibleState == 1;
}
return wasVisible;
}
public static bool IsMultiEditingSupported(Editor editor, Object target, InspectorMode mode)
{
// Culling of editors that can't be properly shown.
// If the current editor is a GenericInspector even though a custom editor for it exists,
// then it's either a fallback for a custom editor that doesn't support multi-object editing,
// or we're in debug mode.
bool multiEditingSupported = true;
if (editor is GenericInspector && CustomEditorAttributes.FindCustomEditorType(target, false) != null)
{
if (mode == InspectorMode.DebugInternal)
{
// Do nothing
}
else if (mode == InspectorMode.Normal)
{
// If we're not in debug mode and it thus must be a fallback,
// hide the editor and show a notification.
multiEditingSupported = false;
}
else if (target is AssetImporter)
{
// If we are in debug mode and it's an importer type,
// hide the editor and show a notification.
multiEditingSupported = false;
}
// If we are in debug mode and it's an NOT importer type,
// just show the debug inspector as usual.
}
return multiEditingSupported;
}
internal static bool EditorHasLargeHeader(int editorIndex, Editor[] trackerActiveEditors)
{
return trackerActiveEditors[editorIndex].firstInspectedEditor || trackerActiveEditors[editorIndex].HasLargeHeader();
}
public bool ShouldCullEditor(Editor[] editors, int editorIndex)
{
if (EditorUtility.IsHiddenInInspector(editors[editorIndex]))
return true;
Object currentTarget = editors[editorIndex].target;
// Editors that should always be hidden
if (currentTarget is ParticleSystemRenderer
|| currentTarget is UnityEngine.VFX.VFXRenderer)
return true;
// Hide regular AssetImporters (but not inherited types)
if (currentTarget != null && currentTarget.GetType() == typeof(AssetImporter))
return true;
// Let asset importers decide if the imported object should be shown or not
if (m_InspectorMode == InspectorMode.Normal && editorIndex != 0)
{
AssetImporterEditor importerEditor = GetAssetImporter(editors);
if (importerEditor != null && !importerEditor.showImportedObject)
return true;
}
return false;
}
public override void SaveChanges()
{
base.SaveChanges();
foreach (var editor in tracker.activeEditors)
{
editor.SaveChanges();
}
}
public override void DiscardChanges()
{
base.DiscardChanges();
foreach (var editor in tracker.activeEditors)
{
editor.DiscardChanges();
}
}
public void UnsavedChangesStateChanged(Editor editor, bool value)
{
tracker.UnsavedChangesStateChanged(editor, value);
hasUnsavedChanges = tracker.hasUnsavedChanges;
if (hasUnsavedChanges)
{
StringBuilder str = new StringBuilder();
foreach (var activeEditor in tracker.activeEditors)
{
if (activeEditor.hasUnsavedChanges)
{
str.AppendLine(activeEditor.saveChangesMessage);
}
}
saveChangesMessage = str.ToString();
}
else
{
saveChangesMessage = string.Empty;
}
}
[RequiredByNativeCode]
private static bool PrivateRequestRebuild(ActiveEditorTracker tracker)
{
foreach (var inspector in Resources.FindObjectsOfTypeAll<PropertyEditor>())
{
if (inspector.tracker.Equals(tracker))
{
return ContainerWindow.CanClose(inspector);
}
}
return true;
}
private void DrawSelectionPickerList()
{
if (m_TypeSelectionList == null)
m_TypeSelectionList = new TypeSelectionList(Selection.objects);
// Force header to be flush with the top of the window
GUILayout.Space(0);
Editor.DrawHeaderGUI(null, Selection.objects.Length + " Objects");
GUILayout.Label("Narrow the Selection:", EditorStyles.label);
GUILayout.Space(4);
Vector2 oldSize = EditorGUIUtility.GetIconSize();
EditorGUIUtility.SetIconSize(new Vector2(16, 16));
foreach (TypeSelection ts in m_TypeSelectionList.typeSelections)
{
Rect r = GUILayoutUtility.GetRect(16, 16, GUILayout.ExpandWidth(true));
if (GUI.Button(r, ts.label, Styles.typeSelection))
{
Selection.objects = ts.objects;
Event.current.Use();
}
if (GUIUtility.hotControl == 0)
EditorGUIUtility.AddCursorRect(r, MouseCursor.Link);
GUILayout.Space(4);
}
EditorGUIUtility.SetIconSize(oldSize);
}
private AssetImporterEditor GetAssetImporter(Editor[] editors)
{
if (editors == null || editors.Length == 0)
return null;
return editors[0] as AssetImporterEditor;
}
private void AddComponentButton(Editor[] editors)
{
// Don't show the Add Component button if we are not showing imported objects for Asset Importers
var assetImporter = GetAssetImporter(editors);
if (assetImporter != null && !assetImporter.showImportedObject)
return;
Editor editor = InspectorWindowUtils.GetFirstNonImportInspectorEditor(editors);
if (editor != null && editor.target != null && editor.target is GameObject && editor.IsEnabled())
{
if (ModeService.HasExecuteHandler("inspector_read_only") && ModeService.Execute("inspector_read_only", editor.target))
return;
EditorGUILayout.BeginHorizontal(GUIContent.none, GUIStyle.none, GUILayout.Height(kAddComponentButtonHeight));
{
GUILayout.FlexibleSpace();
var content = Styles.addComponentLabel;
Rect rect = GUILayoutUtility.GetRect(content, Styles.addComponentButtonStyle);
// Visually separates the Add Component button from the existing components
if (Event.current.type == EventType.Repaint)
DrawSplitLine(rect.y);
rect.y += 9;
if (EditorGUI.DropdownButton(rect, content, FocusType.Passive, Styles.addComponentButtonStyle) ||
m_OpenAddComponentMenu && Event.current.type == EventType.Repaint)
{
m_OpenAddComponentMenu = false;
if (AddComponentWindow.Show(rect, editor.targets.Cast<GameObject>().Where(o => o).ToArray()))
{
// Repaint the inspector window to ensure the AddComponentWindow.Show
// does not clear the inspector window gl buffer, which blacks out the inspector window.
this.RepaintImmediately();
GUIUtility.ExitGUI();
}
}
GUILayout.FlexibleSpace();
}
EditorGUILayout.EndHorizontal();
}
}
private bool ReadyToRepaint()
{
if (AnimationMode.InAnimationPlaybackMode())
{
long timeNow = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
if (timeNow - m_LastUpdateWhilePlayingAnimation < delayRepaintWhilePlayingAnimation)
return false;
m_LastUpdateWhilePlayingAnimation = timeNow;
}
return true;
}
private void DrawSplitLine(float y)
{
Rect position = new Rect(0, y - Styles.lineSeparatorOffset, m_Pos.width + 1, 1);
using (new GUI.ColorScope(Styles.lineSeparatorColor * GUI.color))
GUI.DrawTexture(position, EditorGUIUtility.whiteTexture);
}
private Dictionary<int, IEditorElement> ProcessEditorElementsToRebuild(Editor[] editors)
{
Dictionary<int, IEditorElement> editorToElementMap = new Dictionary<int, IEditorElement>();
var currentElements = editorsElement.Children().OfType<IEditorElement>().ToList();
if (editors.Length == 0)
{
return null;
}
if (rootVisualElement.panel == null)
{
return null;
}
var newEditorsIndex = 0;
var previousEditorsIndex = 0;
while (newEditorsIndex < editors.Length && previousEditorsIndex < currentElements.Count)
{
var ed = editors[newEditorsIndex];
var currentElement = currentElements[previousEditorsIndex];
var currentEditor = currentElement.editor;
if (currentEditor == null)
{
++previousEditorsIndex;
continue;
}
// We won't have an EditorElement for editors that are normally culled so we should skip this
if (ShouldCullEditor(editors, newEditorsIndex))
{
// Reinit culled when editor is culled to avoid NullPointerException (case 1281347)
// EXCEPT for the ParticleSystemRenderer, because it prevents the ParticleSystem inspector
// from working correctly when setting the Material for its renderer (case 1308966).
if (!(ed.target is ParticleSystemRenderer))
{
currentElement.ReinitCulled(newEditorsIndex, editors);
if (!InspectorElement.disabledThrottling)
m_EditorElementUpdater.Add(currentElement);
// We need to move forward as the current element is the culled one, so we're not really
// interested in it.
++previousEditorsIndex;
}
++newEditorsIndex;
continue;
}
if (currentEditor && ed.target != currentEditor.target)
{
return null;
}
editors[newEditorsIndex].propertyViewer = this;
currentElement.Reinit(newEditorsIndex, editors);
if (!InspectorElement.disabledThrottling)
m_EditorElementUpdater.Add(currentElement);
editorToElementMap[ed.target.GetInstanceID()] = currentElement;
++newEditorsIndex;
++previousEditorsIndex;
}
// Remove any elements at the end of the PropertyEditor that don't have matching Editors
for (int j = previousEditorsIndex; j < currentElements.Count; ++j)
{
currentElements[j].RemoveFromHierarchy();
m_EditorElementUpdater.Remove(currentElements[j]);
}
return editorToElementMap;
}
[UsedImplicitly, MenuItem(k_AssetPropertiesMenuItemName, validate = true)]
internal static bool ValidatePropertyEditorOnSelection()
{
return Selection.activeObject;
}
[UsedImplicitly, MenuItem(k_AssetPropertiesMenuItemName, priority = 99999)]
internal static void OpenPropertyEditorOnSelection()
{
OpenPropertyEditor(Selection.objects);
}
internal static PropertyEditor OpenPropertyEditor(IList<Object> objs)
{
if (objs == null || objs.Count == 0)
return null;
var firstPropertyEditor = OpenPropertyEditor(objs.First());
EditorApplication.delayCall += () =>
{
var dock = firstPropertyEditor.m_Parent as DockArea;
for (int i = 1; i < objs.Count; ++i)
dock.AddTab(OpenPropertyEditor(objs[i], false));
};
return firstPropertyEditor;
}
internal static PropertyEditor OpenPropertyEditor(Object obj, bool showWindow = true)
{
if (!obj)
return null;
var propertyEditor = CreateInstance<PropertyEditor>();
propertyEditor.tracker.SetObjectsLockedByThisTracker(new List<Object> { obj });
propertyEditor.m_GlobalObjectId = GlobalObjectId.GetGlobalObjectIdSlow(obj).ToString();
propertyEditor.m_InspectedObject = obj;
propertyEditor.SetTitle(obj);
if (showWindow)
ShowPropertyEditorWindow(propertyEditor);
return propertyEditor;
}
private static void ShowPropertyEditorWindow(PropertyEditor propertyEditor)
{
propertyEditor.Show();
// Offset new window instance.
if (s_LastPropertyEditor)
{
var pos = s_LastPropertyEditor.position;
propertyEditor.position = new Rect(pos.x + 30, pos.y + 30, propertyEditor.position.width, propertyEditor.position.height);
}
s_LastPropertyEditor = propertyEditor;
}
[ShortcutManagement.Shortcut("PropertyEditor/OpenMouseOver")]
static void OpenHoveredItemPropertyEditor(ShortcutManagement.ShortcutArguments args)
{
var windows = Resources.FindObjectsOfTypeAll<EditorWindow>();
if (windows.Length == 0)
return;
foreach (var w in windows)
{
var pso = w as IPropertySourceOpener;
if (pso == null)
continue;
if (!w.m_Parent || !w.m_Parent.window)
continue;
if (pso.hoveredObject)
OpenPropertyEditor(pso.hoveredObject);
}
}
internal static DataMode GetPreferredDataMode()
=> EditorApplication.isPlaying
? DataMode.Mixed
: DataMode.Authoring;
List<DataMode> GetSupportedDataModes() => m_SupportedDataModes;
bool m_IsEnteringPlaymode;
void OnPlayModeStateChanged(PlayModeStateChange stateChange)
{
if (stateChange is not (PlayModeStateChange.EnteredEditMode or PlayModeStateChange.EnteredPlayMode))
return;
m_IsEnteringPlaymode = true;
UpdateSupportedDataModesList();
}
void OnDataModeChanged(DataModeChangeEventArgs evt)
{
tracker.dataMode = evt.nextDataMode;
tracker.ForceRebuild();
}
protected void UpdateSupportedDataModesList()
{
m_SupportedDataModes.Clear();
OnUpdateSupportedDataModes(m_SupportedDataModes);
m_SupportedDataModes.Sort();
if (m_InspectorMode != InspectorMode.Normal || m_SupportedDataModes.Count == 0)
m_SupportedDataModes = k_DisabledDataModes;
var dataMode = Selection.dataModeHint == DataMode.Disabled ? GetPreferredDataMode() : Selection.dataModeHint;
// When entering playmode, Inspector relies on getting selection hint
// from Hierarchy window to switch to the proper data mode.
// However when inspector is locked, selection is locked too.
// Here we force the preferred data mode to inspector for this special case.
if (m_IsEnteringPlaymode && m_Tracker.isLocked)
{
dataMode = GetPreferredDataMode();
m_IsEnteringPlaymode = false;
}
dataModeController.UpdateSupportedDataModes(m_SupportedDataModes, dataMode);
}
protected virtual void OnUpdateSupportedDataModes(List<DataMode> supportedModes)
{
// Override me
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/PropertyEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/PropertyEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 53803
} | 313 |
// 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 UnityEngine
{
[ExcludeFromPreset]
[CustomEditor(typeof(CubemapArray))]
internal class CubemapArrayInspector : TextureInspector
{
private PreviewRenderUtility m_PreviewUtility;
private Material m_Material;
private int m_Slice;
private int m_Mip;
private int m_MipCount;
private Mesh m_Mesh;
public Vector2 m_PreviewDir = new Vector2(0, 0);
static class Styles
{
public static readonly GUIContent slice = EditorGUIUtility.TrTextContent("Slice", "Displayed array slice");
public static readonly GUIStyle toolbarLabel = "toolbarLabel";
}
protected override void OnEnable()
{
base.OnEnable();
InitPreview();
}
protected override void OnDisable()
{
if (m_PreviewUtility != null)
{
m_PreviewUtility.Cleanup();
m_PreviewUtility = null;
}
base.OnDisable();
}
public override void OnPreviewSettings()
{
CubemapArray t = (CubemapArray)target;
EditorGUI.BeginDisabledGroup(t.cubemapCount <= 1);
EditorGUILayout.LabelField(Styles.slice, GUILayout.Width(40));
m_Slice = EditorGUILayout.IntSlider(m_Slice, 0, t.cubemapCount - 1, GUILayout.Width(120));
EditorGUI.EndDisabledGroup();
m_Material.SetFloat("_SliceIndex", (float)m_Slice);
EditorGUI.BeginDisabledGroup(!TextureUtil.NeedsExposureControl(t));
m_ExposureSliderValue = EditorGUIInternal.ExposureSlider(m_ExposureSliderValue, ref m_ExposureSliderMax, EditorStyles.toolbarSlider);
EditorGUI.EndDisabledGroup();
m_Material.SetFloat("_Exposure", GetExposureValueForTexture(t));
EditorGUI.BeginDisabledGroup(m_MipCount == 0);
GUILayout.Box(EditorGUIUtility.IconContent("PreTextureMipMapLow"), Styles.toolbarLabel);
m_Mip = Mathf.RoundToInt(GUILayout.HorizontalSlider(m_Mip, m_MipCount - 1, 0, GUILayout.Width(64)));
GUILayout.Box(EditorGUIUtility.IconContent("PreTextureMipMapHigh"), Styles.toolbarLabel);
EditorGUI.EndDisabledGroup();
m_Material.SetFloat("_Mip", m_Mip);
}
public override void OnPreviewGUI(Rect r, GUIStyle background)
{
if (!SystemInfo.supportsCubemapArrayTextures || (m_Material != null && !m_Material.shader.isSupported))
{
if (Event.current.type == EventType.Repaint)
EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40), "Cubemap array preview is not supported");
return;
}
CubemapArray t = (CubemapArray)target;
m_Material.mainTexture = t;
m_PreviewUtility.BeginPreview(r, background);
const float previewDistance = 6.0f;
m_PreviewDir = PreviewGUI.Drag2D(m_PreviewDir, r);
m_PreviewUtility.camera.transform.position = -Vector3.forward * previewDistance;
m_PreviewUtility.camera.transform.rotation = Quaternion.identity;
Quaternion rot = Quaternion.Euler(m_PreviewDir.y, 0, 0) * Quaternion.Euler(0, m_PreviewDir.x, 0);
m_PreviewUtility.DrawMesh(m_Mesh, Vector3.zero, rot, m_Material, 0);
m_PreviewUtility.Render();
Texture renderedTexture = m_PreviewUtility.EndPreview();
GUI.DrawTexture(r, renderedTexture, ScaleMode.StretchToFill, false);
EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10, r.width, 30),
"Slice " + m_Slice + "\nMip " + m_Mip);
}
void InitPreview()
{
OnDisable();
m_PreviewUtility = new PreviewRenderUtility();
m_PreviewUtility.camera.fieldOfView = 15f;
m_Mesh = PreviewRenderUtility.GetPreviewSphere();
var t = target as CubemapArray;
if (t == null)
return;
m_Material = (Material)EditorGUIUtility.LoadRequired("Previews/CubeArrayPreview.mat");
m_Material.mainTexture = t;
m_Slice = 0;
m_Mip = Mathf.RoundToInt(GetMipLevelForRendering());
m_MipCount = TextureUtil.GetMipmapCount(t);
m_Material.SetFloat("_SliceIndex", (float)m_Slice);
m_Material.SetFloat("_Mip", m_Mip);
m_Material.SetFloat("_Exposure", GetExposureValueForTexture(t));
}
public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
{
// It's not clear what a meaningful preview for a CubemapArray would be - the first slice? Multiple slices composed?
// Until we have a clear idea about the best way to do things, return null for now, to indicate no preview.
return null;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/CubemapArrayInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/CubemapArrayInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 2320
} | 314 |
// Unity 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<T> where T : ScriptableObject
{
readonly ScriptableObjectSaveLoadHelper<T> m_SaveLoadHelper;
readonly UnityEngine.Object m_Target;
readonly string m_Header;
readonly VerticalGrid m_Grid;
readonly Action<string> 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<string> 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<T>(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;
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/GenericPresetLibraryInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/GenericPresetLibraryInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 3544
} | 315 |
// Unity 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.Xml.Serialization;
using UnityEditorInternal;
using UnityEngine;
using System.Linq;
using UnityEditor.EditorTools;
using UnityEditor.Overlays;
using Object = UnityEngine.Object;
using UnityEngine.Rendering;
namespace UnityEditor
{
internal class LightProbeGroupEditor : IEditablePoint
{
private bool m_Editing;
private List<Vector3> m_SourcePositions;
private List<int> m_Selection = new List<int>();
private LightProbeGroupSelection m_SerializedSelectedProbes;
private readonly LightProbeGroup m_Group;
private bool m_ShouldRecalculateTetrahedra;
private bool m_SourcePositionsDirty;
private Vector3 m_LastPosition = Vector3.zero;
private Quaternion m_LastRotation = Quaternion.identity;
private Vector3 m_LastScale = Vector3.one;
public SavedBool drawTetrahedra { get; set; }
public bool deringProbes { get { return m_Group.dering; } set { m_Group.dering = value; } }
public LightProbeGroupEditor(LightProbeGroup group)
{
m_Group = group;
m_ShouldRecalculateTetrahedra = true;
m_SourcePositionsDirty = true;
m_SerializedSelectedProbes = ScriptableObject.CreateInstance<LightProbeGroupSelection>();
m_SerializedSelectedProbes.hideFlags = HideFlags.HideAndDontSave;
}
public void SetEditing(bool editing)
{
m_Editing = editing;
}
public void AddProbe(Vector3 position)
{
Undo.RegisterCompleteObjectUndo(new Object[] { m_Group, m_SerializedSelectedProbes }, "Add Probe");
m_SourcePositions.Add(position);
SelectProbe(m_SourcePositions.Count - 1);
MarkSourcePositionsDirty();
}
private void SelectProbe(int i)
{
if (!m_Selection.Contains(i))
m_Selection.Add(i);
}
public void SelectAllProbes()
{
DeselectProbes();
var count = m_SourcePositions.Count;
for (var i = 0; i < count; i++)
m_Selection.Add(i);
}
public void DeselectProbes()
{
m_Selection.Clear();
m_SerializedSelectedProbes.m_Selection = m_Selection;
}
private IEnumerable<Vector3> SelectedProbePositions()
{
return m_Selection.Select(t => m_SourcePositions[t]).ToList();
}
public void DuplicateSelectedProbes()
{
var selectionCount = m_Selection.Count;
if (selectionCount == 0) return;
Undo.RegisterCompleteObjectUndo(new Object[] { m_Group, m_SerializedSelectedProbes }, "Duplicate Probes");
foreach (var position in SelectedProbePositions())
{
m_SourcePositions.Add(position);
}
MarkSourcePositionsDirty();
}
private void CopySelectedProbes()
{
//Convert probes to world position for serialization
var localPositions = SelectedProbePositions();
var serializer = new XmlSerializer(typeof(Vector3[]));
var writer = new StringWriter();
serializer.Serialize(writer, localPositions.Select(pos => m_Group.transform.TransformPoint(pos)).ToArray());
writer.Close();
GUIUtility.systemCopyBuffer = writer.ToString();
}
private static bool CanPasteProbes()
{
try
{
var deserializer = new XmlSerializer(typeof(Vector3[]));
var reader = new StringReader(GUIUtility.systemCopyBuffer);
deserializer.Deserialize(reader);
reader.Close();
return true;
}
catch
{
return false;
}
}
private bool PasteProbes()
{
//If we can't paste / paste buffer is bad do nothing
try
{
var deserializer = new XmlSerializer(typeof(Vector3[]));
var reader = new StringReader(GUIUtility.systemCopyBuffer);
var pastedProbes = (Vector3[])deserializer.Deserialize(reader);
reader.Close();
if (pastedProbes.Length == 0) return false;
Undo.RegisterCompleteObjectUndo(new Object[] { m_Group, m_SerializedSelectedProbes }, "Paste Probes");
var oldLength = m_SourcePositions.Count;
//Need to convert into local space...
foreach (var position in pastedProbes)
{
m_SourcePositions.Add(m_Group.transform.InverseTransformPoint(position));
}
//Change selection to be the newly pasted probes
DeselectProbes();
for (int i = oldLength; i < oldLength + pastedProbes.Length; i++)
{
SelectProbe(i);
}
MarkSourcePositionsDirty();
return true;
}
catch
{
return false;
}
}
public void RemoveSelectedProbes()
{
int selectionCount = m_Selection.Count;
if (selectionCount == 0)
return;
Undo.RegisterCompleteObjectUndo(new Object[] { m_Group, m_SerializedSelectedProbes }, "Delete Probes");
var reverseSortedIndicies = m_Selection.OrderByDescending(x => x);
foreach (var index in reverseSortedIndicies)
{
m_SourcePositions.RemoveAt(index);
}
DeselectProbes();
MarkSourcePositionsDirty();
}
public void PullProbePositions()
{
if (m_Group != null && m_SerializedSelectedProbes != null)
{
m_SourcePositions = new List<Vector3>(m_Group.probePositions);
m_Selection = new List<int>(m_SerializedSelectedProbes.m_Selection);
}
}
public void PushProbePositions()
{
if (m_SourcePositionsDirty)
{
m_Group.probePositions = m_SourcePositions.ToArray();
m_SourcePositionsDirty = false;
}
m_SerializedSelectedProbes.m_Selection = m_Selection;
}
private void DrawTetrahedra()
{
if (Event.current.type != EventType.Repaint)
return;
if (SceneView.lastActiveSceneView)
{
LightProbeVisualization.DrawTetrahedra(m_ShouldRecalculateTetrahedra,
SceneView.lastActiveSceneView.camera.transform.position);
m_ShouldRecalculateTetrahedra = false;
}
}
public void HandleEditMenuHotKeyCommands()
{
//Handle other events!
if (Event.current.type == EventType.ValidateCommand
|| Event.current.type == EventType.ExecuteCommand)
{
bool execute = Event.current.type == EventType.ExecuteCommand;
switch (Event.current.commandName)
{
case EventCommandNames.SoftDelete:
case EventCommandNames.Delete:
if (execute) RemoveSelectedProbes();
Event.current.Use();
break;
case EventCommandNames.Duplicate:
if (execute) DuplicateSelectedProbes();
Event.current.Use();
break;
case EventCommandNames.SelectAll:
if (execute)
SelectAllProbes();
Event.current.Use();
break;
case EventCommandNames.Cut:
if (execute)
{
CopySelectedProbes();
RemoveSelectedProbes();
}
Event.current.Use();
break;
case EventCommandNames.Copy:
if (execute) CopySelectedProbes();
Event.current.Use();
break;
}
}
}
public static void TetrahedralizeSceneProbes(out Vector3[] positions, out int[] indices)
{
var probeGroups = Object.FindObjectsByType<LightProbeGroup>(FindObjectsSortMode.None);
if (probeGroups == null)
{
positions = new Vector3[0];
indices = new int[0];
return;
}
var probePositions = new List<Vector3>();
foreach (var group in probeGroups)
{
var localPositions = group.probePositions;
foreach (var position in localPositions)
{
var wPosition = group.transform.TransformPoint(position);
probePositions.Add(wPosition);
}
}
if (probePositions.Count == 0)
{
positions = new Vector3[0];
indices = new int[0];
return;
}
Lightmapping.Tetrahedralize(probePositions.ToArray(), out indices, out positions);
}
public bool OnSceneGUI(Transform transform)
{
if (!m_Group.enabled || SupportedRenderingFeatures.active.overridesLightProbeSystem)
return m_Editing;
if (Event.current.type == EventType.Layout)
{
//If the group has moved / scaled since last frame need to retetra);)
if (m_LastPosition != m_Group.transform.position
|| m_LastRotation != m_Group.transform.rotation
|| m_LastScale != m_Group.transform.localScale)
{
MarkSourcePositionsDirty();
}
m_LastPosition = m_Group.transform.position;
m_LastRotation = m_Group.transform.rotation;
m_LastScale = m_Group.transform.localScale;
}
//Need to cache this as select points will use it!
var mouseUpEvent = Event.current.type == EventType.MouseUp;
if (m_Editing)
{
if (PointEditor.SelectPoints(this, transform, ref m_Selection))
{
Undo.RegisterCompleteObjectUndo(new Object[] { m_Group, m_SerializedSelectedProbes }, "Select Probes");
}
}
//Special handling for paste (want to be able to paste when not in edit mode!)
if ((Event.current.type == EventType.ValidateCommand || Event.current.type == EventType.ExecuteCommand)
&& Event.current.commandName == EventCommandNames.Paste)
{
if (Event.current.type == EventType.ValidateCommand)
{
if (CanPasteProbes())
Event.current.Use();
}
if (Event.current.type == EventType.ExecuteCommand)
{
if (PasteProbes())
{
Event.current.Use();
m_Editing = true;
}
}
}
if (drawTetrahedra)
DrawTetrahedra();
PointEditor.Draw(this, transform, m_Selection, true);
if (!m_Editing)
return m_Editing;
HandleEditMenuHotKeyCommands();
if (m_Editing && PointEditor.MovePoints(this, transform, m_Selection))
{
Undo.RegisterCompleteObjectUndo(new Object[] { m_Group, m_SerializedSelectedProbes }, "Move Probes");
if (LightProbeVisualization.dynamicUpdateLightProbes)
MarkSourcePositionsDirty();
}
if (m_Editing && mouseUpEvent && !LightProbeVisualization.dynamicUpdateLightProbes)
{
MarkSourcePositionsDirty();
}
return m_Editing;
}
public void MarkSourcePositionsDirty()
{
m_ShouldRecalculateTetrahedra = true;
m_SourcePositionsDirty = true;
}
public Bounds selectedProbeBounds
{
get
{
List<Vector3> selectedPoints = new List<Vector3>();
foreach (var idx in m_Selection)
selectedPoints.Add(m_SourcePositions[(int)idx]);
return GetBounds(selectedPoints);
}
}
public Bounds bounds
{
get { return GetBounds(m_SourcePositions); }
}
private Bounds GetBounds(List<Vector3> positions)
{
if (positions.Count == 0)
return new Bounds();
if (positions.Count == 1)
return new Bounds(m_Group.transform.TransformPoint(positions[0]), new Vector3(1f, 1f, 1f));
return GeometryUtility.CalculateBounds(positions.ToArray(), m_Group.transform.localToWorldMatrix);
}
/// Get the world-space position of a specific point
public Vector3 GetPosition(int idx)
{
return m_SourcePositions[idx];
}
public Vector3 GetWorldPosition(int idx)
{
return m_Group.transform.TransformPoint(m_SourcePositions[idx]);
}
public void SetPosition(int idx, Vector3 position)
{
if (m_SourcePositions[idx] == position)
return;
m_SourcePositions[idx] = position;
MarkSourcePositionsDirty();
}
private static readonly Color kCloudColor = new Color(200f / 255f, 200f / 255f, 20f / 255f, 0.85f);
private static readonly Color kSelectedCloudColor = new Color(.3f, .6f, 1, 1);
public Color GetDefaultColor()
{
return kCloudColor;
}
public Color GetSelectedColor()
{
return kSelectedCloudColor;
}
public float GetPointScale()
{
// Should match LightProbeVisualizationSettings::GetLightProbeSize()
return 10.0f * AnnotationUtility.iconSize;
}
public Vector3[] GetSelectedPositions()
{
var selectedCount = SelectedCount;
var result = new Vector3[selectedCount];
for (int i = 0; i < selectedCount; i++)
{
result[i] = m_SourcePositions[m_Selection[i]];
}
return result;
}
public void UpdateSelectedPosition(int idx, Vector3 position)
{
if (idx > (SelectedCount - 1))
return;
m_SourcePositions[m_Selection[idx]] = position;
MarkSourcePositionsDirty();
}
public IEnumerable<Vector3> GetPositions()
{
return m_SourcePositions;
}
public Vector3[] GetUnselectedPositions()
{
var totalProbeCount = Count;
var selectedProbeCount = SelectedCount;
if (selectedProbeCount == totalProbeCount)
{
return new Vector3[0];
}
else if (selectedProbeCount == 0)
{
return m_SourcePositions.ToArray();
}
else
{
var selectionList = new bool[totalProbeCount];
// Mark everything unselected
for (int i = 0; i < totalProbeCount; i++)
{
selectionList[i] = false;
}
// Mark selected
for (int i = 0; i < selectedProbeCount; i++)
{
selectionList[m_Selection[i]] = true;
}
// Get remaining unselected
var result = new Vector3[totalProbeCount - selectedProbeCount];
var unselectedCount = 0;
for (int i = 0; i < totalProbeCount; i++)
{
if (selectionList[i] == false)
{
result[unselectedCount++] = m_SourcePositions[i];
}
}
return result;
}
}
/// How many points are there in the array.
public int Count { get { return m_SourcePositions.Count; } }
/// How many points are selected in the array.
public int SelectedCount { get { return m_Selection.Count; } }
}
class LightProbeGroupOverlay : TransientSceneViewOverlay
{
LightProbeGroup m_Target;
LightProbeGroupEditor m_Editor;
internal static class Styles
{
public static readonly GUIContent showWireframe = EditorGUIUtility.TrTextContent("Show Wireframe", "Show the tetrahedron wireframe visualizing the blending between probes.");
public static readonly GUIContent selectedProbePosition = EditorGUIUtility.TrTextContent("Selected Probe Position", "The local position of this probe relative to the parent group.");
public static readonly GUIContent addProbe = EditorGUIUtility.TrTextContent("Add Probe", "Add a Light Probe to the Light Probe Group.");
public static readonly GUIContent deleteSelected = EditorGUIUtility.TrTextContent("Delete Selected", "Delete the selected Light Probes from the Light Probe Group.");
public static readonly GUIContent selectAll = EditorGUIUtility.TrTextContent("Select All", "Select all Light Probes in the Light Probe Group.");
public static readonly GUIContent duplicateSelected = EditorGUIUtility.TrTextContent("Duplicate Selected", "Duplicate the selected Light Probes.");
public static readonly GUIContent performDeringing = EditorGUIUtility.TrTextContent("Remove Ringing", "When enabled, removes visible overshooting often observed as ringing on objects affected by intense lighting at the expense of reduced contrast.");
public static readonly GUIContent enterEditMode = EditorGUIUtility.TrTextContent("Edit Light Probe Positions", "Change positions for Light Probes.");
public static readonly GUIContent exitEditMode = EditorGUIUtility.TrTextContent("Exit Light Probe Editing", "Exit Light Probe Positions Editing.");
public static readonly GUIContent toolIcon = EditorGUIUtility.TrIconContent("EditCollider", "Edit Light Probe Group.\n\nUse the overlay to add Light Probes and modify probe positions.");
public static readonly GUIContent editModeInfoBox = EditorGUIUtility.TrTextContentWithIcon("Use the <b>Edit Light Probe Group Tool</b> in the <b>Scene Tools Overlay</b> to edit Light Probe positions.", MessageType.Info);
public static readonly GUIStyle editModeInfoBoxStyle = new GUIStyle(EditorStyles.helpBox) { richText = true };
}
public LightProbeGroupOverlay(LightProbeGroup target, LightProbeGroupEditor editor)
{
m_Target = target;
m_Editor = editor;
displayName = "Edit Light Probes";
}
public override void OnGUI()
{
EditorGUI.BeginChangeCheck();
m_Editor.PullProbePositions();
m_Editor.drawTetrahedra.value = GUILayout.Toggle(m_Editor.drawTetrahedra.value, Styles.showWireframe, EditorStyles.toggle);
EditorGUI.BeginChangeCheck();
Vector3 pos = m_Editor.SelectedCount > 0 ? m_Editor.GetSelectedPositions()[0] : Vector3.zero;
Vector3 newPosition = EditorGUILayout.Vector3Field(Styles.selectedProbePosition, pos);
if (EditorGUI.EndChangeCheck())
{
Vector3[] selectedPositions = m_Editor.GetSelectedPositions();
Vector3 delta = CalculateDeltaAndClamp(newPosition, pos);
for (int i = 0; i < selectedPositions.Length; i++)
m_Editor.UpdateSelectedPosition(i, selectedPositions[i] + delta);
}
GUILayout.Space(3);
GUILayoutOption minButtonWidth = GUILayout.MinWidth(130);
GUILayout.BeginHorizontal();
{
GUILayout.BeginVertical();
if (GUILayout.Button(Styles.addProbe, minButtonWidth))
{
var position = Vector3.zero;
if (SceneView.lastActiveSceneView)
position = m_Target.transform.InverseTransformPoint(position);
m_Editor.DeselectProbes();
m_Editor.AddProbe(position);
}
if (GUILayout.Button(Styles.deleteSelected, minButtonWidth))
m_Editor.RemoveSelectedProbes();
GUILayout.EndVertical();
}
GUILayout.BeginVertical();
{
if (GUILayout.Button(Styles.selectAll, minButtonWidth))
m_Editor.SelectAllProbes();
if (GUILayout.Button(Styles.duplicateSelected, minButtonWidth))
m_Editor.DuplicateSelectedProbes();
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
m_Editor.HandleEditMenuHotKeyCommands();
m_Editor.PushProbePositions();
if (EditorGUI.EndChangeCheck())
{
m_Editor.MarkSourcePositionsDirty();
SceneView.RepaintAll();
}
}
Vector3 CalculateDeltaAndClamp(Vector3 vec1, Vector3 vec2)
{
if (float.IsInfinity(vec1.x) || float.IsNaN(vec1.x))
vec1.x = 0;
if (float.IsInfinity(vec1.y) || float.IsNaN(vec1.y))
vec1.y = 0;
if (float.IsInfinity(vec1.z) || float.IsNaN(vec1.z))
vec1.z = 0;
vec1.x = Mathf.Clamp(vec1.x, float.MinValue, float.MaxValue);
vec1.y = Mathf.Clamp(vec1.y, float.MinValue, float.MaxValue);
vec1.z = Mathf.Clamp(vec1.z, float.MinValue, float.MaxValue);
return vec1 - vec2;
}
public override bool visible => true;
}
[EditorTool("Light Probe Group", typeof(LightProbeGroup))]
class LightProbeGroupTool : EditorTool, IDrawSelectedHandles
{
LightProbeGroup m_LightProbeGroup;
LightProbeGroupEditor m_Editor;
LightProbeGroupOverlay m_Overlay;
void OnEnable()
{
m_LightProbeGroup = (LightProbeGroup) target;
if (m_LightProbeGroup == null)
return;
m_Editor = new LightProbeGroupEditor(m_LightProbeGroup);
m_Editor.PullProbePositions();
m_Editor.DeselectProbes();
m_Editor.PushProbePositions();
m_Editor.drawTetrahedra = new SavedBool($"{target.GetType()}.drawTetrahedra", true);
Undo.undoRedoEvent += UndoRedoPerformed;
}
void OnDisable()
{
Undo.undoRedoEvent -= UndoRedoPerformed;
}
void UndoRedoPerformed(in UndoRedoInfo info)
{
// Update the cached probe positions from the ones just restored in the LightProbeGroup
m_Editor.PullProbePositions();
m_Editor.MarkSourcePositionsDirty();
SceneView.RepaintAll();
}
public override void OnActivated()
{
m_Editor.SetEditing(true);
SceneView.AddOverlayToActiveView(m_Overlay = new LightProbeGroupOverlay(m_LightProbeGroup, m_Editor));
SceneView.RepaintAll();
}
public override void OnWillBeDeactivated()
{
m_Editor.DeselectProbes();
m_Editor.SetEditing(false);
m_Editor.PushProbePositions();
SceneView.RemoveOverlayFromActiveView(m_Overlay);
SceneView.RepaintAll();
}
public void OnDrawHandles()
{
m_Editor.PullProbePositions();
if (m_Editor.OnSceneGUI(m_LightProbeGroup.transform))
{
m_Editor.PushProbePositions();
// OnSceneGUI can cause us to enter edit mode, for example when pasting probes.
// In these cases, we must set the active EditorTool to reflect that change.
if (!ToolManager.IsActiveTool(this))
EditorToolManager.activeTool = this;
}
}
public override bool IsAvailable() => !SupportedRenderingFeatures.active.overridesLightProbeSystem;
public override GUIContent toolbarIcon => LightProbeGroupOverlay.Styles.toolIcon;
}
[CustomEditor(typeof(LightProbeGroup))]
class LightProbeGroupInspector : Editor
{
SerializedProperty dering;
public void OnEnable()
{
if (serializedObject == null)
return;
dering = serializedObject.FindProperty("m_Dering");
}
public override void OnInspectorGUI()
{
bool srpHasAlternativeToLegacyProbes = SupportedRenderingFeatures.active.overridesLightProbeSystem;
using (new EditorGUI.DisabledScope(srpHasAlternativeToLegacyProbes))
{
serializedObject.Update();
EditorGUILayout.PropertyField(dering, LightProbeGroupOverlay.Styles.performDeringing);
serializedObject.ApplyModifiedProperties();
}
if (srpHasAlternativeToLegacyProbes)
{
EditorGUILayout.HelpBox(SupportedRenderingFeatures.active.overridesLightProbeSystemWarningMessage, MessageType.Warning, true);
}
else
{
EditorGUILayout.LabelField(GUIContent.none, LightProbeGroupOverlay.Styles.editModeInfoBox, LightProbeGroupOverlay.Styles.editModeInfoBoxStyle);
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/LightProbeGroupInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/LightProbeGroupInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 12939
} | 316 |
// 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 UnityEngine.Rendering;
using System.Collections.Generic;
namespace UnityEditor
{
[CustomEditor(typeof(MeshRenderer))]
[CanEditMultipleObjects]
internal class MeshRendererEditor : RendererEditorBase
{
class Styles
{
public static readonly GUIContent materialWarning = EditorGUIUtility.TrTextContent("This renderer has more materials than the Mesh has submeshes. Multiple materials will be applied to the same submesh, which costs performance. Consider using multiple shader passes.");
public static readonly GUIContent staticBatchingWarning = EditorGUIUtility.TrTextContent("This Renderer uses static batching and instanced Shaders. When the Player is active, instancing is disabled. If you want instanced Shaders at run time, disable static batching.");
}
private SerializedObject m_GameObjectsSerializedObject;
private SerializedProperty m_GameObjectStaticFlags;
public override void OnEnable()
{
// Since we are not doing anything if we are not displayed in the inspector, early out. This help keeps multi selection snappier.
if (hideInspector)
return;
base.OnEnable();
m_GameObjectsSerializedObject = new SerializedObject(targets.Select(t => ((MeshRenderer)t).gameObject).ToArray());
m_GameObjectStaticFlags = m_GameObjectsSerializedObject.FindProperty("m_StaticEditorFlags");
Lightmapping.lightingDataUpdated += LightingDataUpdatedRepaint;
}
public void OnDisable()
{
Lightmapping.lightingDataUpdated -= LightingDataUpdatedRepaint;
}
private void LightingDataUpdatedRepaint()
{
if (m_Lighting.showLightmapSettings)
{
Repaint();
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// Evaluate displayMaterialWarning before drawing properties to avoid mismatched layout group
bool displayMaterialWarning = false;
if (!m_Materials.hasMultipleDifferentValues)
{
MeshFilter mf = ((MeshRenderer)serializedObject.targetObject).GetComponent<MeshFilter>();
displayMaterialWarning = mf != null && mf.sharedMesh != null && m_Materials.arraySize > mf.sharedMesh.subMeshCount;
}
// Disable Materials menu for the legacy Tree objects, see Fogbugz case: 1283092
Tree treeComponent = ((MeshRenderer)serializedObject.targetObject).GetComponent<Tree>();
bool hasTreeComponent = treeComponent != null;
bool isSpeedTree = hasTreeComponent && treeComponent.data == null; // SpeedTrees always have the Tree component, but have null 'data' property
using (new EditorGUI.DisabledScope(hasTreeComponent && !isSpeedTree))
{
DrawMaterials();
}
if (!m_Materials.hasMultipleDifferentValues && displayMaterialWarning)
{
EditorGUILayout.HelpBox(Styles.materialWarning.text, MessageType.Warning, true);
}
if (ShaderUtil.MaterialsUseInstancingShader(m_Materials))
{
m_GameObjectsSerializedObject.Update();
int staticBatching, dynamicBatching;
PlayerSettings.GetBatchingForPlatform(EditorUserBuildSettings.activeBuildTarget, out staticBatching, out dynamicBatching);
if (!m_GameObjectStaticFlags.hasMultipleDifferentValues && ((StaticEditorFlags)m_GameObjectStaticFlags.intValue & StaticEditorFlags.BatchingStatic) != 0 && staticBatching != 0)
{
EditorGUILayout.HelpBox(Styles.staticBatchingWarning.text, MessageType.Warning, true);
}
}
LightingSettingsGUI(true);
RayTracingSettingsGUI();
OtherSettingsGUI(true, false, false);
if (targets.Length == 1)
SpeedTreeMaterialFixer.DoFixerUI((target as MeshRenderer).gameObject);
serializedObject.ApplyModifiedProperties();
}
}
}
| UnityCsReference/Editor/Mono/Inspector/MeshRendererEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/MeshRendererEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1720
} | 317 |
// 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;
using UnityEngine.Events;
namespace UnityEditor
{
internal partial class PlayerSettingsSplashScreenEditor
{
PlayerSettingsEditor m_Owner;
SerializedProperty m_ShowUnitySplashLogo;
SerializedProperty m_ShowUnitySplashScreen;
SerializedProperty m_SplashScreenAnimation;
SerializedProperty m_SplashScreenBackgroundAnimationZoom;
SerializedProperty m_SplashScreenBackgroundColor;
SerializedProperty m_SplashScreenBackgroundLandscape;
SerializedProperty m_SplashScreenBackgroundPortrait;
SerializedProperty m_SplashScreenBlurBackground;
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 readonly Color32 k_DarkOnLightBgColor = new Color32(204, 204, 204, 255);// #CCCCCC
static readonly Color32 k_LightOnDarkBgColor = new Color32(35, 31, 32, 255);
static Sprite s_UnityLogoLight; // We use this version as a placeholder when the logo is in the list.
static Sprite s_UnityLogoDark;
readonly AnimBool m_ShowAnimationControlsAnimator = new AnimBool();
readonly AnimBool m_ShowBackgroundColorAnimator = new AnimBool();
readonly AnimBool m_ShowLogoControlsAnimator = new AnimBool();
Sprite UnityLogo => m_SplashScreenLogoStyle.intValue == (int)PlayerSettings.SplashScreen.UnityLogoStyle.DarkOnLight ? s_UnityLogoDark : s_UnityLogoLight;
// If the user changes an asset(delete, re-import etc) then we should cancel the splash screen to avoid using invalid data. (case 857060)
class CancelSplashScreenOnAssetChange : AssetPostprocessor
{
void OnPreprocessAsset()
{
SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate);
}
}
class CancelSplashScreenOnAssetDelete : AssetModificationProcessor
{
static AssetDeleteResult OnWillDeleteAsset(string asset, RemoveAssetOptions options)
{
SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate);
return AssetDeleteResult.DidNotDelete;
}
}
class Texts
{
public GUIContent animate = EditorGUIUtility.TrTextContent("Animation");
public GUIContent backgroundColor = EditorGUIUtility.TrTextContent("Background Color", "Background color when no background image is used. On Android, use this property to set static splash image background color.");
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 blurBackground = EditorGUIUtility.TrTextContent("Blur Background Image");
public GUIContent cancelPreviewSplash = EditorGUIUtility.TrTextContent("Cancel Preview");
public GUIContent configDialogBanner = EditorGUIUtility.TrTextContent("Application Config Dialog Banner");
public GUIContent configDialogBannerDeprecationWarning = EditorGUIUtility.TrTextContent("Application Config Dialog Banner is deprecated and will be removed in future versions.");
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_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_SplashScreenBlurBackground = m_Owner.FindPropertyAssert("blurSplashScreenBackground");
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_ShowBackgroundColorAnimator.value = m_SplashScreenBackgroundLandscape.objectReferenceValue == null;
m_ShowLogoControlsAnimator.value = m_ShowUnitySplashLogo.boolValue;
SetValueChangeListeners(m_Owner.Repaint);
if (s_UnityLogoLight == null)
s_UnityLogoLight = AssetDatabase.GetBuiltinExtraResource<Sprite>("SplashScreen/UnitySplash-Light.png");
if (s_UnityLogoDark == null)
s_UnityLogoDark = AssetDatabase.GetBuiltinExtraResource<Sprite>("SplashScreen/UnitySplash-Dark.png");
}
internal void SetValueChangeListeners(UnityAction action)
{
m_ShowAnimationControlsAnimator.valueChanged.RemoveAllListeners();
m_ShowAnimationControlsAnimator.valueChanged.AddListener(action);
m_ShowBackgroundColorAnimator.valueChanged.RemoveAllListeners();
m_ShowBackgroundColorAnimator.valueChanged.AddListener(action);
m_ShowLogoControlsAnimator.valueChanged.RemoveAllListeners();
m_ShowLogoControlsAnimator.valueChanged.AddListener(action);
}
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);
var logoRect = new Rect(rect.x, rect.y, logoWidth, rect.height);
GUI.DrawTexture(logoRect, UnityLogo.texture, ScaleMode.ScaleToFit);
// 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_UnityLogoLight)
{
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 propertyRect = new Rect(rect.x + unityLogoWidth, rect.y + EditorGUIUtility.standardVerticalSpacing, rect.width - unityLogoWidth, EditorGUIUtility.singleLineHeight);
var duration = element.FindPropertyRelative("duration");
EditorGUI.BeginChangeCheck();
var oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = k_LogoListPropertyLabelWidth;
var newDurationVal = EditorGUI.Slider(propertyRect, k_Texts.logoDuration, duration.floatValue, k_MinLogoTime, k_MaxLogoTime);
EditorGUIUtility.labelWidth = oldLabelWidth;
if (EditorGUI.EndChangeCheck())
duration.floatValue = newDurationVal;
m_TotalLogosDuration += duration.floatValue;
}
private void DrawLogoListFooterCallback(Rect rect)
{
float totalDuration = Mathf.Max(k_MinLogoTime, m_TotalLogosDuration);
EditorGUI.LabelField(rect, "Splash Screen Duration: " + totalDuration, 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 bool OnLogoListCanRemoveCallback(ReorderableList list)
{
var element = list.serializedProperty.GetArrayElementAtIndex(list.index);
var logo = (Sprite)element.FindPropertyRelative("logo").objectReferenceValue;
return logo != s_UnityLogoLight;
}
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_UnityLogoLight)
return;
}
m_SplashScreenLogos.InsertArrayElementAtIndex(0);
var element = m_SplashScreenLogos.GetArrayElementAtIndex(0);
var logo = element.FindPropertyRelative("logo");
var duration = element.FindPropertyRelative("duration");
logo.objectReferenceValue = s_UnityLogoLight;
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_UnityLogoLight)
{
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<T>(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;
}
EditorGUI.EndProperty();
}
public void SplashSectionGUI(BuildPlatform platform, ISettingEditorExtension settingsExtension, int sectionIndex = 2)
{
if (m_Owner.BeginSettingsBox(sectionIndex, k_Texts.title))
{
if (platform.namedBuildTarget == NamedBuildTarget.Server)
{
PlayerSettingsEditor.ShowNoSettings();
EditorGUILayout.Space();
}
else
{
bool VREnabled = BuildPipeline.IsFeatureSupported("ENABLE_VR", platform.defaultTarget);
if (VREnabled)
ObjectReferencePropertyField<Texture2D>(m_VirtualRealitySplashScreen, k_Texts.vrSplashScreen);
if (TargetSupportsOptionalBuiltinSplashScreen(platform.namedBuildTarget.ToBuildTargetGroup(), settingsExtension))
BuiltinCustomSplashScreenGUI(platform.namedBuildTarget.ToBuildTargetGroup(), settingsExtension);
if (settingsExtension != null)
{
settingsExtension.SplashSectionGUI();
if (!m_ShowUnitySplashScreen.boolValue && settingsExtension.SupportsStaticSplashScreenBackgroundColor())
EditorGUILayout.PropertyField(m_SplashScreenBackgroundColor, k_Texts.backgroundColor);
}
if (m_ShowUnitySplashScreen.boolValue)
m_Owner.ShowSharedNote();
}
}
m_Owner.EndSettingsBox();
}
private void BuiltinCustomSplashScreenGUI(BuildTargetGroup targetGroup, ISettingEditorExtension settingsExtension)
{
EditorGUILayout.LabelField(k_Texts.splashTitle, EditorStyles.boldLabel);
using (new EditorGUI.DisabledScope(!licenseAllowsDisabling))
{
EditorGUILayout.PropertyField(m_ShowUnitySplashScreen, k_Texts.showSplash);
if (!m_ShowUnitySplashScreen.boolValue)
return;
}
GUIContent buttonLabel = SplashScreen.isFinished ? k_Texts.previewSplash : k_Texts.cancelPreviewSplash;
Rect previewButtonRect = GUILayoutUtility.GetRect(buttonLabel, "button");
previewButtonRect = EditorGUI.PrefixLabel(previewButtonRect, new GUIContent(" "));
if (GUI.Button(previewButtonRect, buttonLabel))
{
if (SplashScreen.isFinished)
{
SplashScreen.Begin();
PlayModeView.RepaintAll();
var playModeView = PlayModeView.GetMainPlayModeView();
if (playModeView)
{
playModeView.Focus();
}
EditorApplication.update += PollSplashState;
}
else
{
SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate);
EditorApplication.update -= PollSplashState;
}
GameView.RepaintAll();
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_SplashScreenLogoStyle, k_Texts.splashStyle);
if (EditorGUI.EndChangeCheck())
{
if (m_SplashScreenLogoStyle.intValue == (int)PlayerSettings.SplashScreen.UnityLogoStyle.DarkOnLight)
m_SplashScreenBackgroundColor.colorValue = k_DarkOnLightBgColor;
else
m_SplashScreenBackgroundColor.colorValue = k_LightOnDarkBgColor;
}
// 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.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();
}
}
EditorGUILayout.EndFadeGroup();
using (var vertical = new EditorGUILayout.VerticalScope())
using (new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_SplashScreenLogos))
{
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 ||
(settingsExtension?.SupportsStaticSplashScreenBackgroundColor() ?? false);
if (EditorGUILayout.BeginFadeGroup(m_ShowBackgroundColorAnimator.faded))
EditorGUILayout.PropertyField(m_SplashScreenBackgroundColor, k_Texts.backgroundColor);
EditorGUILayout.EndFadeGroup();
EditorGUILayout.PropertyField(m_SplashScreenBlurBackground, k_Texts.blurBackground);
EditorGUI.BeginChangeCheck();
ObjectReferencePropertyField<Sprite>(m_SplashScreenBackgroundLandscape, k_Texts.backgroundImage);
if (EditorGUI.EndChangeCheck() && m_SplashScreenBackgroundLandscape.objectReferenceValue == null)
m_SplashScreenBackgroundPortrait.objectReferenceValue = null;
using (new EditorGUI.DisabledScope(m_SplashScreenBackgroundLandscape.objectReferenceValue == null))
{
ObjectReferencePropertyField<Sprite>(m_SplashScreenBackgroundPortrait, k_Texts.backgroundPortraitImage);
}
}
void PollSplashState()
{
// Force the GameViews to repaint whilst showing the splash(1166664)
PlayModeView.RepaintAll();
// When the splash screen is playing we need to keep track so that we can update the preview button when it has finished.
if (SplashScreen.isFinished)
{
var window = SettingsWindow.FindWindowByScope(SettingsScope.Project);
window?.Repaint();
EditorApplication.update -= PollSplashState;
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/PlayerSettingsEditor/PlayerSettingsSplashScreenEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 10709
} | 318 |
// 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 UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
namespace UnityEditor
{
[CustomEditor(typeof(RenderTexture))]
[CanEditMultipleObjects]
internal class RenderTextureEditor : TextureInspector
{
private int m_RepaintDelay = 0;
private class Styles
{
public readonly GUIContent size = EditorGUIUtility.TrTextContent("Size", "Size of the render texture in pixels.");
public readonly GUIContent cross = EditorGUIUtility.TextContent("x");
public readonly GUIContent antiAliasing = EditorGUIUtility.TrTextContent("Anti-aliasing", "Number of anti-aliasing samples.");
public readonly GUIContent colorFormat = EditorGUIUtility.TrTextContent("Color Format", "Format of the color buffer.");
public readonly GUIContent depthStencilFormat = EditorGUIUtility.TrTextContent("Depth Stencil Format", "Format of the depth stencil buffer.");
public readonly GUIContent enableCompatibleFormat = EditorGUIUtility.TrTextContent("Enable Compatible Format", "Lets the color and depth stencil formats be changed to compatible and supported formats for the target platform automatically, if the target platform doesn't support the input format.");
public readonly GUIContent dimension = EditorGUIUtility.TrTextContent("Dimension", "Is the texture 2D, Cube or 3D?");
public readonly GUIContent enableMipmaps = EditorGUIUtility.TrTextContent("Enable Mip Maps", "This render texture will have Mip Maps.");
public readonly GUIContent autoGeneratesMipmaps = EditorGUIUtility.TrTextContent("Auto generate Mip Maps", "This render texture automatically generates its Mip Maps.");
public readonly GUIContent useDynamicScale = EditorGUIUtility.TrTextContent("Dynamic Scaling", "Allow the texture to be automatically resized by ScalableBufferManager, to support dynamic resolution.");
public readonly GUIContent enableRandomWrite = EditorGUIUtility.TrTextContent("Random Write", "Enable/disable random access write into the color buffer of this render texture.");
public readonly GUIContent shadowSamplingMode = EditorGUIUtility.TrTextContent("Shadow Sampling Mode", "Enable/disable shadow depth-compare sampling and percentage closer filtering.");
public readonly GUIContent[] renderTextureAntiAliasing =
{
EditorGUIUtility.TrTextContent("None"),
EditorGUIUtility.TrTextContent("2 samples"),
EditorGUIUtility.TrTextContent("4 samples"),
EditorGUIUtility.TrTextContent("8 samples")
};
public readonly int[] renderTextureAntiAliasingValues = { 1, 2, 4, 8 };
public readonly GUIContent[] dimensionStrings = { EditorGUIUtility.TextContent("2D"), EditorGUIUtility.TextContent("2D Array"), EditorGUIUtility.TrTextContent("Cube"), EditorGUIUtility.TrTextContent("3D") };
public readonly int[] dimensionValues = { (int)UnityEngine.Rendering.TextureDimension.Tex2D, (int)UnityEngine.Rendering.TextureDimension.Tex2DArray, (int)UnityEngine.Rendering.TextureDimension.Cube, (int)UnityEngine.Rendering.TextureDimension.Tex3D };
}
static Styles s_Styles = null;
private static Styles styles { get { if (s_Styles == null) s_Styles = new Styles(); return s_Styles; } }
[Flags]
protected enum GUIElements
{
RenderTargetNoneGUI = 0,
RenderTargetDepthGUI = 1 << 1,
RenderTargetAAGUI = 1 << 2
}
const GUIElements s_AllGUIElements = GUIElements.RenderTargetDepthGUI | GUIElements.RenderTargetAAGUI;
SerializedProperty m_Width;
SerializedProperty m_Height;
SerializedProperty m_Depth;
SerializedProperty m_ColorFormat;
SerializedProperty m_DepthStencilFormat;
SerializedProperty m_EnableCompatibleFormat;
SerializedProperty m_AntiAliasing;
SerializedProperty m_EnableMipmaps;
SerializedProperty m_AutoGeneratesMipmaps;
SerializedProperty m_Dimension;
SerializedProperty m_sRGB;
SerializedProperty m_UseDynamicScale;
SerializedProperty m_EnableRandomWrite;
SerializedProperty m_ShadowSamplingMode;
protected override void OnEnable()
{
base.OnEnable();
m_Width = serializedObject.FindProperty("m_Width");
m_Height = serializedObject.FindProperty("m_Height");
m_Depth = serializedObject.FindProperty("m_VolumeDepth");
m_AntiAliasing = serializedObject.FindProperty("m_AntiAliasing");
m_ColorFormat = serializedObject.FindProperty("m_ColorFormat");
m_DepthStencilFormat = serializedObject.FindProperty("m_DepthStencilFormat");
m_EnableCompatibleFormat = serializedObject.FindProperty("m_EnableCompatibleFormat");
m_EnableMipmaps = serializedObject.FindProperty("m_MipMap");
m_AutoGeneratesMipmaps = serializedObject.FindProperty("m_GenerateMips");
m_Dimension = serializedObject.FindProperty("m_Dimension");
m_sRGB = serializedObject.FindProperty("m_SRGB");
m_UseDynamicScale = serializedObject.FindProperty("m_UseDynamicScale");
m_EnableRandomWrite = serializedObject.FindProperty("m_EnableRandomWrite");
m_ShadowSamplingMode = serializedObject.FindProperty("m_ShadowSamplingMode");
Undo.undoRedoEvent += OnUndoRedoPerformed;
}
protected override void OnDisable()
{
base.OnDisable();
Undo.undoRedoEvent -= OnUndoRedoPerformed;
}
private void OnUndoRedoPerformed(in UndoRedoInfo info)
{
var rt = target as RenderTexture;
if (rt != null)
{
rt.Release();
}
}
protected void OnRenderTextureGUI(GUIElements guiElements)
{
GUI.changed = false;
EditorGUILayout.IntPopup(m_Dimension, styles.dimensionStrings, styles.dimensionValues, styles.dimension);
// Note that TextureInspector.IsTexture3D/Cube/2DArray/etc. exist. Those functions will use the actual target object to determine the dimension.
// This because they are drawing preview settings based on the selected target objects.
// Here we are drawing the one and only Render Texture GUI so we have the dimension field as most correct value.
bool isTexture3D = (m_Dimension.intValue == (int)UnityEngine.Rendering.TextureDimension.Tex3D);
bool isTexture2DArray = (m_Dimension.intValue == (int)UnityEngine.Rendering.TextureDimension.Tex2DArray);
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(styles.size, EditorStyles.popup);
EditorGUILayout.DelayedIntField(m_Width, GUIContent.none, GUILayout.MinWidth(40));
GUILayout.Label(styles.cross);
EditorGUILayout.DelayedIntField(m_Height, GUIContent.none, GUILayout.MinWidth(40));
if (isTexture3D || isTexture2DArray)
{
GUILayout.Label(styles.cross);
EditorGUILayout.DelayedIntField(m_Depth, GUIContent.none, GUILayout.MinWidth(40));
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if ((guiElements & GUIElements.RenderTargetAAGUI) != 0)
EditorGUILayout.IntPopup(m_AntiAliasing, styles.renderTextureAntiAliasing, styles.renderTextureAntiAliasingValues, styles.antiAliasing);
GraphicsFormat colorFormat = (GraphicsFormat)m_ColorFormat.intValue;
GraphicsFormat compatibleColorFormat = SystemInfo.GetCompatibleFormat(colorFormat, GraphicsFormatUsage.Render);
GraphicsFormat depthStencilFormat = (GraphicsFormat)m_DepthStencilFormat.intValue;
bool isDepthStencilUnused = depthStencilFormat == GraphicsFormat.None;
bool isDepthStencilFormatIncompatible = !isDepthStencilUnused && SystemInfo.GetCompatibleFormat(depthStencilFormat, GraphicsFormatUsage.Render) == GraphicsFormat.None;
GraphicsFormat compatibleDepthStencilFormat = (isDepthStencilUnused) ? GraphicsFormat.None :
GraphicsFormatUtility.GetDepthStencilFormat(GraphicsFormatUtility.GetDepthBits(depthStencilFormat), (GraphicsFormatUtility.IsStencilFormat(depthStencilFormat)) ? 8 : 0);
// If no fallbacks are found for the color AND depth stencil buffer, disable the EnableCompatibleFormat field
// If only one of the two fails, checkbox can still be interacted with
if (!(compatibleColorFormat == GraphicsFormat.None && compatibleDepthStencilFormat == GraphicsFormat.None))
{
EditorGUILayout.PropertyField(m_EnableCompatibleFormat, styles.enableCompatibleFormat);
}
EditorGUILayout.PropertyField(m_ColorFormat, styles.colorFormat);
m_sRGB.boolValue = GraphicsFormatUtility.IsSRGBFormat((GraphicsFormat)m_ColorFormat.intValue);
if (compatibleColorFormat != colorFormat)
{
string text = string.Format("Format {0} is not supported on this platform. ", colorFormat.ToString());
if (compatibleColorFormat != GraphicsFormat.None)
{
if (m_EnableCompatibleFormat.boolValue)
text += string.Format("Using {0} as a compatible format.", compatibleColorFormat.ToString());
else
text += string.Format("You may enable Compatible Format to fallback automatically to a platform specific compatible format, {0} on this device.", compatibleColorFormat.ToString());
}
EditorGUILayout.HelpBox(text, m_EnableCompatibleFormat.boolValue && compatibleColorFormat != GraphicsFormat.None ? MessageType.Warning : MessageType.Error);
}
// 3D Textures with a depth buffer aren't supported.
if (!isTexture3D)
{
if ((guiElements & GUIElements.RenderTargetDepthGUI) != 0)
{
EditorGUILayout.PropertyField(m_DepthStencilFormat, styles.depthStencilFormat);
}
if (depthStencilFormat != compatibleDepthStencilFormat)
{
string text = string.Format("Format {0} is not supported on this platform. ", depthStencilFormat.ToString());
if (compatibleDepthStencilFormat != GraphicsFormat.None)
{
if (m_EnableCompatibleFormat.boolValue)
text += string.Format("Using {0} as a compatible format.", compatibleDepthStencilFormat.ToString());
else
text += string.Format("You may enable Compatible Format to fallback automatically to a platform specific compatible format, {0} on this device.", compatibleDepthStencilFormat.ToString());
}
EditorGUILayout.HelpBox(text, m_EnableCompatibleFormat.boolValue && compatibleDepthStencilFormat != GraphicsFormat.None ? MessageType.Warning : MessageType.Error);
}
if ((GraphicsFormat)m_DepthStencilFormat.intValue == GraphicsFormat.None && (GraphicsFormat)m_ColorFormat.intValue == GraphicsFormat.None)
{
EditorGUILayout.HelpBox("You cannot set both color format and depth format to None", MessageType.Error);
}
}
// Mip map generation is not supported yet for 3D textures (and for depth only textures).
if (!(isTexture3D || RenderTextureIsDepthOnly()))
{
EditorGUILayout.PropertyField(m_EnableMipmaps, styles.enableMipmaps);
if (m_EnableMipmaps.boolValue)
{
++EditorGUI.indentLevel;
EditorGUILayout.PropertyField(m_AutoGeneratesMipmaps, styles.autoGeneratesMipmaps);
--EditorGUI.indentLevel;
}
}
else
{
if (isTexture3D)
{
// Mip map generation is not supported yet for 3D textures.
EditorGUILayout.HelpBox("3D RenderTextures do not support Mip Maps.", MessageType.Info);
}
if (RenderTextureIsDepthOnly())
{
// Mip map generation is not supported yet for depth-only textures.
EditorGUILayout.HelpBox("Depth-only RenderTextures do not support Mip Maps.", MessageType.Info);
}
}
EditorGUILayout.PropertyField(m_UseDynamicScale, styles.useDynamicScale);
EditorGUILayout.PropertyField(m_EnableRandomWrite, styles.enableRandomWrite);
var rt = target as RenderTexture;
if (GUI.changed && rt != null)
{
rt.Release();
m_RepaintDelay = 5;
}
// Trigger delayed repaint to allow camera's to be rendered before thumbnail is generated.
if (m_RepaintDelay > 0)
{
--m_RepaintDelay;
if (m_RepaintDelay == 0)
EditorUtility.SetDirty(target);
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
DoWrapModePopup();
DoFilterModePopup();
if (!RenderTextureHasDepth()) // Render Textures with depth are forced to 0 Aniso Level
{
DoAnisoLevelSlider();
}
else
{
EditorGUILayout.HelpBox("RenderTextures with depth are forced to have an Aniso Level of 0.", MessageType.Info);
}
if (RenderTextureHasDepth()) // Depth-only textures have shadow mode
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ShadowSamplingMode, styles.shadowSamplingMode);
// Shadow mode unlike the other filter settings requires re-creating the rt if it changed
// as it's an actual creation flag on the texture.
if (EditorGUI.EndChangeCheck() && rt != null)
{
rt.Release();
}
}
else
{
EditorGUILayout.HelpBox("Only render textures with depth can have shadow filtering.", MessageType.Info);
}
serializedObject.ApplyModifiedProperties();
if (EditorGUI.EndChangeCheck())
ApplySettingsToTextures();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
OnRenderTextureGUI(s_AllGUIElements);
}
private bool RenderTextureHasDepth()
{
return RenderTextureIsDepthOnly() || m_DepthStencilFormat.enumValueIndex != 0;
}
private bool RenderTextureIsDepthOnly()
{
GraphicsFormat colorFormat = (GraphicsFormat)m_ColorFormat.enumValueIndex;
return colorFormat == GraphicsFormat.None;
}
override public string GetInfoString()
{
RenderTexture t = target as RenderTexture;
string info = t.width + "x" + t.height;
if (t.dimension == UnityEngine.Rendering.TextureDimension.Tex3D)
info += "x" + t.volumeDepth;
if (!t.isPowerOfTwo)
info += "(NPOT)";
if (QualitySettings.desiredColorSpace == ColorSpace.Linear)
{
bool formatIsHDR = GraphicsFormatUtility.IsIEEE754Format(t.graphicsFormat);
bool sRGB = t.sRGB && !formatIsHDR;
info += " " + (sRGB ? "sRGB" : "Linear");
}
info += " " + t.graphicsFormat;
info += " " + EditorUtility.FormatBytes(TextureUtil.GetRuntimeMemorySizeLong(t));
return info;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/RenderTextureEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/RenderTextureEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 6878
} | 319 |
// 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
{
class Styles
{
public static GUIContent Get3DLayoutContent(MaterialProperty property)
{
if (s_Stereo3DLayoutContent == null)
s_Stereo3DLayoutContent = EditorGUIUtility.TrTextContent(
property.displayName,
"Layout of 3D content in the source. Only meaningful when stereoscopic render is used.");
return s_Stereo3DLayoutContent;
}
private static GUIContent s_Stereo3DLayoutContent;
}
readonly AnimBool m_ShowLatLongLayout = new AnimBool();
readonly AnimBool m_ShowMirrorOnBack = 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_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();
ShowProp(materialEditor, FindProperty("_Layout", props), Styles.Get3DLayoutContent);
}
EditorGUILayout.EndFadeGroup();
// Let the default implementation add the extra shader properties at the bottom.
materialEditor.PropertiesDefaultGUI(new MaterialProperty[0]);
}
private delegate GUIContent ContentGenerator(MaterialProperty property);
private float ShowProp(
MaterialEditor materialEditor, MaterialProperty prop,
ContentGenerator contentGenerator = null)
{
if (contentGenerator != null)
materialEditor.ShaderProperty(prop, contentGenerator(prop));
else
materialEditor.ShaderProperty(prop, prop.displayName);
return prop.floatValue;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/SkyboxPanoramicShaderGUI.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/SkyboxPanoramicShaderGUI.cs",
"repo_id": "UnityCsReference",
"token_count": 1498
} | 320 |
// 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 Texture2DArrayPreview
{
static readonly int s_ShaderColorMask = Shader.PropertyToID("_ColorMaskBits");
static readonly int s_ShaderSliceIndex = Shader.PropertyToID("_SliceIndex");
static readonly int s_ShaderMip = Shader.PropertyToID("_Mip");
static readonly int s_ShaderToSrgb = Shader.PropertyToID("_ToSRGB");
static readonly int s_ShaderIsNormalMap = Shader.PropertyToID("_IsNormalMap");
// Preview settings
Material m_Material;
int m_Slice = 0;
private Vector2 m_Pos;
static class Styles
{
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 static GUIContent arrayIcon = EditorGUIUtility.IconContent("Texture2DArray");
}
public float GetMipLevelForRendering(Texture texture, float mipLevel)
{
return Mathf.Min(mipLevel, TextureUtil.GetMipmapCount(texture));
}
public void SetShaderColorMask(TextureInspector.PreviewMode mode)
{
var mask = 15;
switch (mode)
{
case TextureInspector.PreviewMode.RGB: mask = 7; break;
case TextureInspector.PreviewMode.R: mask = 1; break;
case TextureInspector.PreviewMode.G: mask = 2; break;
case TextureInspector.PreviewMode.B: mask = 4; break;
case TextureInspector.PreviewMode.A: mask = 8; break;
}
m_Material.SetFloat(s_ShaderColorMask, (float)mask);
}
public void OnPreviewSettings(Texture target)
{
Texture2DArray texture2DArray = target as Texture2DArray;
RenderTexture renderTexture = target as RenderTexture;
if (texture2DArray == null && renderTexture == null)
return;
if (texture2DArray != null)
{
m_Slice = (int)TextureInspector.PreviewSettingsSlider(Styles.arrayIcon, m_Slice, 0, texture2DArray.depth - 1, 60, 30, isInteger: true);
}
else
{
m_Slice = (int)TextureInspector.PreviewSettingsSlider(Styles.arrayIcon, m_Slice, 0, renderTexture.volumeDepth - 1, 60, 30, isInteger: true);
}
}
public void OnPreviewGUI(Texture t, Rect r, GUIStyle background, float exposure, TextureInspector.PreviewMode previewMode, float mipLevel)
{
if (t == null)
return;
if (!SystemInfo.supports2DArrayTextures)
{
EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40), "2D texture array preview not supported");
return;
}
InitPreviewMaterialIfNeeded();
m_Material.mainTexture = t;
int effectiveSlice = GetEffectiveSlice(t);
m_Material.SetFloat(s_ShaderSliceIndex, (float)effectiveSlice);
m_Material.SetFloat(s_ShaderToSrgb, QualitySettings.activeColorSpace == ColorSpace.Linear ? 1.0f : 0.0f);
m_Material.SetFloat(s_ShaderIsNormalMap, TextureInspector.IsNormalMap(t) ? 1.0f : 0.0f);
SetShaderColorMask(previewMode);
int texWidth = Mathf.Max(t.width, 1);
int texHeight = Mathf.Max(t.height, 1);
float effectiveMipLevel = GetMipLevelForRendering(t, mipLevel);
float zoomLevel = Mathf.Min(Mathf.Min(r.width / texWidth, r.height / texHeight), 1);
Rect wantedRect = new Rect(r.x, r.y, texWidth * zoomLevel, texHeight * zoomLevel);
PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar",
"PreHorizontalScrollbarThumb");
FilterMode oldFilter = t.filterMode;
TextureUtil.SetFilterModeNoDirty(t, FilterMode.Point);
EditorGUI.DrawPreviewTexture(wantedRect, t, m_Material, ScaleMode.StretchToFill, 0, effectiveMipLevel, UnityEngine.Rendering.ColorWriteMask.All, exposure);
TextureUtil.SetFilterModeNoDirty(t, oldFilter);
int mipmapLimit = GetMipmapLimit(t);
int cpuMipLevel = Mathf.Min(TextureUtil.GetMipmapCount(t) - 1, (int)mipLevel + mipmapLimit);
m_Pos = PreviewGUI.EndScrollView();
GUIContent sliceAndMipLevelTextContent = new GUIContent($"Slice {effectiveSlice}");
if (cpuMipLevel != 0)
sliceAndMipLevelTextContent.text += cpuMipLevel != (int)effectiveMipLevel
? $" | Mip {cpuMipLevel}\nMip {mipLevel} on GPU (Texture Limit)"
: $" | Mip {mipLevel}";
EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 40), sliceAndMipLevelTextContent);
}
int GetEffectiveSlice(Texture t)
{
var texture2DArray = t as Texture2DArray;
if (texture2DArray != null)
{
// If multiple objects are selected, we might be using a slice level before the maximum
return Mathf.Clamp(m_Slice, 0, texture2DArray.depth - 1);
}
else
{
var renderTexture = t as RenderTexture;
// If multiple objects are selected, we might be using a slice level before the maximum
return Mathf.Clamp(m_Slice, 0, renderTexture.volumeDepth - 1);
}
}
int GetMipmapLimit(Texture t)
{
var texture2DArray = t as Texture2DArray;
if (texture2DArray != null)
return texture2DArray.activeMipmapLimit;
return 0;
}
void InitPreviewMaterialIfNeeded()
{
if (m_Material == null)
m_Material = (Material)EditorGUIUtility.LoadRequired("Previews/Preview2DTextureArrayMaterial.mat");
}
public Texture2D RenderStaticPreview(Texture target, string assetPath, Object[] subAssets, int width, int height)
{
if (!ShaderUtil.hardwareSupportsRectRenderTexture || !SystemInfo.supports2DArrayTextures)
return null;
var texture = target as Texture2DArray;
if (texture == null)
return null;
var previewUtility = new PreviewRenderUtility();
previewUtility.BeginStaticPreview(new Rect(0, 0, width, height));
InitPreviewMaterialIfNeeded();
m_Material.mainTexture = texture;
m_Material.SetFloat(s_ShaderColorMask, 15.0f);
m_Material.SetFloat(s_ShaderMip, 0);
m_Material.SetFloat(s_ShaderToSrgb, 0.0f);
m_Material.SetFloat(s_ShaderIsNormalMap, TextureInspector.IsNormalMap(texture) ? 1.0f : 0.0f);
int sliceDistance = previewUtility.renderTexture.width / 12;
var elementCount = Mathf.Min(texture.depth, 6);
Rect screenRect = new Rect(), sourceRect = new Rect();
var subRect = new Rect(0, 0, previewUtility.renderTexture.width - sliceDistance * (elementCount - 1), previewUtility.renderTexture.height - sliceDistance * (elementCount - 1));
for (var el = elementCount - 1; el >= 0; --el)
{
m_Material.SetFloat(s_ShaderSliceIndex, (float)el);
subRect.x = sliceDistance * el;
subRect.y = previewUtility.renderTexture.height - subRect.height - sliceDistance * el;
var aspect = texture.width / (float)texture.height;
GUI.CalculateScaledTextureRects(subRect, ScaleMode.ScaleToFit, aspect, ref screenRect, ref sourceRect);
Graphics.DrawTexture(screenRect, texture, sourceRect, 0, 0, 0, 0, Color.white, m_Material);
}
var res = previewUtility.EndStaticPreview();
previewUtility.Cleanup();
return res;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Texture2DArrayPreview.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Texture2DArrayPreview.cs",
"repo_id": "UnityCsReference",
"token_count": 3756
} | 321 |
// Unity 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.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor.UIElements
{
internal class ObjectFieldWithPrompt : BaseField<Object>
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : BaseField<Object>.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField] bool allowSceneObjects;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags allowSceneObjects_UxmlAttributeFlags;
[UxmlAttribute("type"), UxmlTypeReference(typeof(Object))]
[SerializeField] string objectType;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags objectType_UxmlAttributeFlags;
[SerializeField] string title;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags title_UxmlAttributeFlags;
[SerializeField] string message;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags message_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new ObjectFieldWithPrompt();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
var e = (ObjectFieldWithPrompt)obj;
if (ShouldWriteAttributeValue(allowSceneObjects_UxmlAttributeFlags))
e.allowSceneObjects = allowSceneObjects;
if (ShouldWriteAttributeValue(objectType_UxmlAttributeFlags))
e.objectType = UxmlUtility.ParseType(objectType, typeof(Object));
if (ShouldWriteAttributeValue(title_UxmlAttributeFlags))
e.title = title;
if (ShouldWriteAttributeValue(message_UxmlAttributeFlags))
e.message = message;
}
}
string m_Title;
public string title
{
get => m_Title;
set => m_Title = value;
}
string m_Message;
public string message
{
get => m_Message;
set => m_Message = value;
}
Type m_objectType;
public Type objectType
{
get { return m_objectType; }
set
{
if (m_objectType == value) return;
m_objectType = value;
m_ObjectField.objectType = value;
}
}
bool m_AllowSceneObjects;
public bool allowSceneObjects
{
get => m_AllowSceneObjects;
set
{
if (m_AllowSceneObjects == value) return;
m_AllowSceneObjects = value;
m_ObjectField.allowSceneObjects = value;
}
}
readonly ObjectField m_ObjectField;
public ObjectFieldWithPrompt() : this(null)
{
}
public ObjectFieldWithPrompt(string label) : base(label, null)
{
visualInput.style.display = DisplayStyle.None;
m_ObjectField = new ObjectField
{
allowSceneObjects = false,
style =
{
flexGrow = 1,
flexShrink = 1,
marginLeft = 0,
marginRight = 0
}
};
m_ObjectField.RegisterValueChangedCallback(evt =>
{
if (EditorUtility.DisplayDialog(title, message, "Confirm", "Cancel"))
value = evt.newValue;
else
m_ObjectField.SetValueWithoutNotify(value);
if (EditorWindow.HasOpenInstances<ObjectSelector>())
ObjectSelector.get.Cancel();
});
Add(m_ObjectField);
}
public override void SetValueWithoutNotify(Object newValue)
{
base.SetValueWithoutNotify(newValue);
m_ObjectField.SetValueWithoutNotify(newValue);
}
}
}
| UnityCsReference/Editor/Mono/Inspector/VisualElements/ObjectFieldWithPrompt.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/VisualElements/ObjectFieldWithPrompt.cs",
"repo_id": "UnityCsReference",
"token_count": 2079
} | 322 |
// 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("Editor/Mono/InternalMeshUtil.bindings.h")]
internal static class InternalMeshUtil
{
public static extern int GetPrimitiveCount(Mesh mesh);
public static extern int CalcTriangleCount(Mesh mesh);
public static extern bool HasSupportedTopologyForGI(Mesh mesh);
public static extern bool HasVertices(Mesh mesh);
public static extern bool HasNormals(Mesh mesh);
public static extern string GetVertexFormat(Mesh mesh);
public static extern float GetCachedMeshSurfaceArea(MeshRenderer meshRenderer);
}
}
| UnityCsReference/Editor/Mono/InternalMeshUtil.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/InternalMeshUtil.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 270
} | 323 |
// Unity 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 UnityEditor.Build;
using UnityEditor.Build.Profile;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Modules
{
internal abstract class DefaultBuildProfileExtension : IBuildProfileExtension
{
static readonly GUIContent k_DevelopmentBuild = EditorGUIUtility.TrTextContent("Development Build");
static readonly GUIContent k_AutoconnectProfiler = EditorGUIUtility.TrTextContent("Autoconnect Profiler", "When the build is started, an open Profiler Window will automatically connect to the Player and start profiling. The \"Build And Run\" option will also automatically open the Profiler Window.");
static readonly GUIContent k_AutoconnectProfilerDisabled = EditorGUIUtility.TrTextContent("Autoconnect Profiler", "Profiling is only enabled in a Development Player.");
static readonly GUIContent k_BuildWithDeepProfiler = EditorGUIUtility.TrTextContent("Deep Profiling Support", "Build Player with Deep Profiling Support. This might affect Player performance.");
static readonly GUIContent k_BuildWithDeepProfilerDisabled = EditorGUIUtility.TrTextContent("Deep Profiling", "Profiling is only enabled in a Development Player.");
static readonly GUIContent k_AllowDebugging = EditorGUIUtility.TrTextContent("Script Debugging", "Enable this setting to allow your script code to be debugged.");
static readonly GUIContent k_WaitForManagedDebugger = EditorGUIUtility.TrTextContent("Wait For Managed Debugger", "Show a dialog where you can attach a managed debugger before any script execution. Can also use volume Up or Down button to confirm on Android.");
static readonly GUIContent k_ManagedDebuggerFixedPort = EditorGUIUtility.TrTextContent("Managed Debugger Fixed Port", "Use the specified port to attach to the managed debugger. If 0, the port will be automatically selected.");
static readonly GUIContent k_CompressionMethod = EditorGUIUtility.TrTextContent("Compression Method", "Compression applied to Player data (scenes and resources).\nDefault - none or default platform compression.\nLZ4 - fast compression suitable for Development Builds.\nLZ4HC - higher compression rate variance of LZ4, causes longer build times. Works best for Release Builds.");
static readonly GUIContent k_ExplicitNullChecks = EditorGUIUtility.TrTextContent("Explicit Null Checks");
static readonly GUIContent k_ExplicitDivideByZeroChecks = EditorGUIUtility.TrTextContent("Divide By Zero Checks");
static readonly GUIContent k_ExplicitArrayBoundsChecks = EditorGUIUtility.TrTextContent("Array Bounds Checks");
static readonly Compression[] k_CompressionTypes =
{
Compression.None,
Compression.Lz4,
Compression.Lz4HC
};
static readonly GUIContent[] k_CompressionStrings =
{
EditorGUIUtility.TrTextContent("Default"),
EditorGUIUtility.TrTextContent("LZ4"),
EditorGUIUtility.TrTextContent("LZ4HC"),
};
static readonly GUIContent k_InstallInBuildFolder = EditorGUIUtility.TrTextContent("Install into source code 'build' folder", "Install into source checkout 'build' folder, for debugging with source code");
static readonly GUIContent k_InstallInBuildFolderHelp = EditorGUIUtility.TrIconContent("_Help", "Open documentation about source code building and debugging");
SerializedProperty m_Development;
SerializedProperty m_ConnectProfiler;
SerializedProperty m_BuildWithDeepProfilingSupport;
SerializedProperty m_AllowDebugging;
SerializedProperty m_WaitForManagedDebugger;
SerializedProperty m_ManagedDebuggerFixedPort;
SerializedProperty m_ExplicitNullChecks;
SerializedProperty m_ExplicitDivideByZeroChecks;
SerializedProperty m_ExplicitArrayBoundsChecks;
SerializedProperty m_CompressionType;
SerializedProperty m_InstallInBuildFolder;
BuildTarget m_BuildTarget;
BuildTargetGroup m_BuildTargetGroup;
NamedBuildTarget m_NamedBuildTarget;
protected bool m_IsClassicProfile = false;
protected SharedPlatformSettings m_SharedSettings;
// The properties can be unresponsive on multiple clicks due to the
// complex layout calculations which can slow down GUI rendering.
// So we set the GUI label elements' width to make it more responsive.
protected virtual float labelWidth => 230;
public abstract BuildProfilePlatformSettingsBase CreateBuildProfilePlatformSettings();
public virtual void CopyPlatformSettingsToBuildProfile(BuildProfilePlatformSettingsBase platformSettingsBase)
{
}
public virtual void CopyPlatformSettingsFromBuildProfile(BuildProfilePlatformSettingsBase platformSettings)
{
}
public virtual void OnDisable()
{
}
public virtual bool ShouldDrawDevelopmentPlayerCheckbox() => true;
public virtual bool ShouldDrawProfilerCheckbox() => true;
public virtual bool ShouldDrawScriptDebuggingCheckbox() => true;
// Enables a dialog "Wait For Managed debugger", which halts program execution until managed debugger is connected
public virtual bool ShouldDrawWaitForManagedDebugger() => false;
public virtual bool ShouldDrawManagedDebuggerFixedPort() => false;
public virtual bool ShouldDrawExplicitNullCheckbox() => false;
public virtual bool ShouldDrawExplicitDivideByZeroCheckbox() => false;
public virtual bool ShouldDrawExplicitArrayBoundsCheckbox() => false;
public VisualElement CreateSettingsGUI(
SerializedObject serializedObject, SerializedProperty rootProperty, BuildProfileWorkflowState workflowState)
{
var platformWarningsGUI = CreatePlatformBuildWarningsGUI(serializedObject, rootProperty);
var commonSettingsGUI = CreateCommonSettingsGUI(serializedObject, rootProperty, workflowState);
var platformSettingsGUI = CreatePlatformSettingsGUI(serializedObject, rootProperty, workflowState);
var settingsGUI = new VisualElement();
if (platformWarningsGUI != null)
settingsGUI.Add(platformWarningsGUI);
settingsGUI.Add(platformSettingsGUI);
if (m_IsClassicProfile && BuildPlayerWindow.WillDrawMultiplayerBuildOptions())
settingsGUI.Add(CreateMultiplayerSettingsGUI());
settingsGUI.Add(commonSettingsGUI);
return settingsGUI;
}
public virtual VisualElement CreatePlatformSettingsGUI(
SerializedObject serializedObject, SerializedProperty rootProperty, BuildProfileWorkflowState workflowState)
{
// Default implementation will render all platform settings defined in
// BuildProfilePlatformSettingsBase as a PropertyField. Enumerators are
// shown as-is.
var field = new PropertyField(rootProperty);
field.BindProperty(rootProperty);
return field;
}
public virtual VisualElement CreatePlatformBuildWarningsGUI(SerializedObject serializedObject, SerializedProperty rootProperty)
{
return null;
}
public SerializedProperty FindPlatformSettingsPropertyAssert(SerializedProperty rootProperty, string name)
{
SerializedProperty property = rootProperty.FindPropertyRelative(name);
Debug.Assert(property != null);
return property;
}
public SerializedProperty FindSerializedObjectPropertyAssert(SerializedObject serializedObject, string name)
{
SerializedProperty property = serializedObject.FindProperty(name);
Debug.Assert(property != null);
return property;
}
public VisualElement CreateCommonSettingsGUI(SerializedObject serializedObject, SerializedProperty rootProperty, BuildProfileWorkflowState workflowState)
{
m_Development = FindPlatformSettingsPropertyAssert(rootProperty, "m_Development");
m_ConnectProfiler = FindPlatformSettingsPropertyAssert(rootProperty, "m_ConnectProfiler");
m_BuildWithDeepProfilingSupport = FindPlatformSettingsPropertyAssert(rootProperty, "m_BuildWithDeepProfilingSupport");
m_AllowDebugging = FindPlatformSettingsPropertyAssert(rootProperty, "m_AllowDebugging");
m_WaitForManagedDebugger = FindPlatformSettingsPropertyAssert(rootProperty, "m_WaitForManagedDebugger");
m_ManagedDebuggerFixedPort = FindPlatformSettingsPropertyAssert(rootProperty, "m_ManagedDebuggerFixedPort");
m_ExplicitNullChecks = FindPlatformSettingsPropertyAssert(rootProperty, "m_ExplicitNullChecks");
m_ExplicitDivideByZeroChecks = FindPlatformSettingsPropertyAssert(rootProperty, "m_ExplicitDivideByZeroChecks");
m_ExplicitArrayBoundsChecks = FindPlatformSettingsPropertyAssert(rootProperty, "m_ExplicitArrayBoundsChecks");
m_CompressionType = FindPlatformSettingsPropertyAssert(rootProperty, "m_CompressionType");
m_InstallInBuildFolder = FindPlatformSettingsPropertyAssert(rootProperty, "m_InstallInBuildFolder");
var profile = serializedObject.targetObject as BuildProfile;
Debug.Assert(profile != null);
m_BuildTarget = profile.buildTarget;
var subtarget = profile.subtarget;
m_BuildTargetGroup = BuildPipeline.GetBuildTargetGroup(m_BuildTarget);
m_NamedBuildTarget = (subtarget == StandaloneBuildSubtarget.Server) ? NamedBuildTarget.Server : NamedBuildTarget.FromBuildTargetGroup(m_BuildTargetGroup);
m_IsClassicProfile = BuildProfileContext.IsClassicPlatformProfile(profile);
m_SharedSettings = BuildProfileContext.instance.sharedProfile.platformBuildProfile as SharedPlatformSettings;
return new IMGUIContainer(
() =>
{
var oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = labelWidth;
serializedObject.UpdateIfRequiredOrScript();
ShowCommonBuildOptions(workflowState);
serializedObject.ApplyModifiedProperties();
EditorGUIUtility.labelWidth = oldLabelWidth;
});
}
VisualElement CreateMultiplayerSettingsGUI()
{
return new IMGUIContainer(
() =>
{
var oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = labelWidth;
BuildPlayerWindow.DrawMultiplayerBuildOption(m_NamedBuildTarget);
EditorGUIUtility.labelWidth = oldLabelWidth;
});
}
public void ShowCommonBuildOptions(BuildProfileWorkflowState workflowState)
{
if (ShouldDrawDevelopmentPlayerCheckbox())
{
ShowDevelopmentPlayerCheckbox();
}
using (new EditorGUI.DisabledScope(!m_Development.boolValue))
{
if (ShouldDrawProfilerCheckbox())
{
ShowProfilerCheckbox();
}
if (ShouldDrawScriptDebuggingCheckbox())
{
ShowScriptDebuggingCheckbox();
}
}
if (ShouldDrawExplicitNullCheckbox())
{
ShowExplicitNullChecksToggle();
}
if (ShouldDrawExplicitDivideByZeroCheckbox())
{
ShowDivideByZeroChecksToggle();
}
if (ShouldDrawExplicitArrayBoundsCheckbox())
{
ShowArrayBoundsChecksToggle();
}
var postprocessor = ModuleManager.GetBuildPostProcessor(m_BuildTarget);
if (postprocessor != null && postprocessor.SupportsLz4Compression())
{
using (var vertical = new EditorGUILayout.VerticalScope())
using (var propertyScope = new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, m_CompressionType))
{
var cmpIdx = Array.IndexOf(k_CompressionTypes, (Compression)m_CompressionType.intValue);
if (cmpIdx == BuildProfilePlatformSettingsBase.k_InvalidCompressionIdx)
cmpIdx = Array.IndexOf(k_CompressionTypes, postprocessor.GetDefaultCompression());
if (cmpIdx == BuildProfilePlatformSettingsBase.k_InvalidCompressionIdx)
cmpIdx = (int)CompressionType.Lz4; // Lz4 by default.
cmpIdx = EditorGUILayout.Popup(k_CompressionMethod, cmpIdx, k_CompressionStrings);
m_CompressionType.intValue = (int)k_CompressionTypes[cmpIdx];
if (m_BuildTargetGroup == BuildTargetGroup.Standalone && m_IsClassicProfile)
{
m_SharedSettings.compressionType = (Compression)m_CompressionType.intValue;
}
}
}
if (Unsupported.IsSourceBuild() && PostprocessBuildPlayer.SupportsInstallInBuildFolder(m_BuildTarget))
{
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.PropertyField(m_InstallInBuildFolder, k_InstallInBuildFolder, GUILayout.ExpandWidth(false));
EditorGUILayout.BeginVertical();
GUILayout.Space(3);
if (GUILayout.Button(k_InstallInBuildFolderHelp, EditorStyles.iconButton))
{
const string k_ViewScriptPath = "Documentation/InternalDocs/docs/BuildSystem/view";
const string k_WindowsEditorScriptExtension = ".cmd";
const string k_MacAndLinuxEditorScriptExtension = ".sh";
var path = Path.Combine(Unsupported.GetBaseUnityDeveloperFolder(), k_ViewScriptPath);
if (Application.platform == RuntimePlatform.WindowsEditor)
System.Diagnostics.Process.Start(path + k_WindowsEditorScriptExtension);
else
System.Diagnostics.Process.Start(path + k_MacAndLinuxEditorScriptExtension);
}
EditorGUILayout.EndVertical();
}
}
else
m_InstallInBuildFolder.boolValue = false;
if (m_IsClassicProfile)
{
m_SharedSettings.installInBuildFolder = m_InstallInBuildFolder.boolValue;
}
ActionState buildAndRunState = (m_InstallInBuildFolder != null && m_InstallInBuildFolder.boolValue) ? ActionState.Disabled : workflowState.buildAndRunAction;
workflowState.UpdateBuildActionStates(workflowState.buildAction, buildAndRunState);
if (Unsupported.IsSourceBuild())
ShowInternalPlatformBuildOptions();
}
/// <summary>
/// Show the Development checkbox. Platforms can override this method to hide/customize the UI.
/// </summary>
public virtual void ShowDevelopmentPlayerCheckbox()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_Development, k_DevelopmentBuild);
if (EditorGUI.EndChangeCheck() && m_IsClassicProfile)
{
m_SharedSettings.development = m_Development.boolValue;
}
}
/// <summary>
/// Show profiler checkboxes, including Autoconnect Profiler and Deep Profiling Support checkboxes.
/// Platforms can override this method to hide/customize the UI.
/// </summary>
public virtual void ShowProfilerCheckbox()
{
var autoConnectLabel = m_Development.boolValue ? k_AutoconnectProfiler : k_AutoconnectProfilerDisabled;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ConnectProfiler, autoConnectLabel);
if (EditorGUI.EndChangeCheck() && m_IsClassicProfile)
{
m_SharedSettings.connectProfiler = m_ConnectProfiler.boolValue;
}
var buildWithDeepProfilerLabel = m_Development.boolValue ? k_BuildWithDeepProfiler : k_BuildWithDeepProfilerDisabled;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_BuildWithDeepProfilingSupport, buildWithDeepProfilerLabel);
if (EditorGUI.EndChangeCheck() && m_IsClassicProfile)
{
m_SharedSettings.buildWithDeepProfilingSupport = m_BuildWithDeepProfilingSupport.boolValue;
}
}
/// <summary>
/// Show script debugging options. Platforms can override this method to hide/customize the UI.
/// </summary>
public virtual void ShowScriptDebuggingCheckbox()
{
ShowManagedDebuggerCheckboxes();
if (m_AllowDebugging.boolValue && PlayerSettings.GetScriptingBackend(m_NamedBuildTarget) == ScriptingImplementation.IL2CPP)
{
var apiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(m_NamedBuildTarget);
bool isDebuggerUsable = apiCompatibilityLevel == ApiCompatibilityLevel.NET_4_6 || apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard_2_0 ||
apiCompatibilityLevel == ApiCompatibilityLevel.NET_Unity_4_8 || apiCompatibilityLevel == ApiCompatibilityLevel.NET_Standard;
if (!isDebuggerUsable)
EditorGUILayout.HelpBox("Script debugging is only supported with IL2CPP on .NET 4.x and .NET Standard 2.0 API Compatibility Levels.", MessageType.Warning);
}
}
/// <summary>
/// Show managed debugger options. Platforms can override this method to
/// hide/customize the UI.
/// </summary>
public virtual void ShowManagedDebuggerCheckboxes()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_AllowDebugging, k_AllowDebugging);
if (EditorGUI.EndChangeCheck() && m_IsClassicProfile)
{
m_SharedSettings.allowDebugging = m_AllowDebugging.boolValue;
}
// Not all platforms have native dialog implemented in Runtime\Misc\GiveDebuggerChanceToAttachIfRequired.cpp
// Display this option only for developer builds
if (ShouldDrawWaitForManagedDebugger())
{
ShowWaitForManagedDebuggerCheckbox();
}
if (ShouldDrawManagedDebuggerFixedPort())
{
ShowManagedDebuggerFixedPort();
}
}
public void ShowWaitForManagedDebuggerCheckbox()
{
if (m_AllowDebugging.boolValue)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_WaitForManagedDebugger, k_WaitForManagedDebugger);
if (EditorGUI.EndChangeCheck() && m_IsClassicProfile)
{
m_SharedSettings.waitForManagedDebugger = m_WaitForManagedDebugger.boolValue;
}
}
}
public void ShowManagedDebuggerFixedPort()
{
if (m_AllowDebugging.boolValue)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ManagedDebuggerFixedPort, k_ManagedDebuggerFixedPort);
if (m_ManagedDebuggerFixedPort.intValue < 0 || m_ManagedDebuggerFixedPort.intValue > BuildProfilePlatformSettingsBase.k_MaxPortNumber)
{
m_ManagedDebuggerFixedPort.intValue = 0;
}
if (EditorGUI.EndChangeCheck() && m_IsClassicProfile)
{
m_SharedSettings.managedDebuggerFixedPort = m_ManagedDebuggerFixedPort.intValue;
}
}
}
public void ShowExplicitNullChecksToggle()
{
using (new EditorGUI.DisabledScope(m_Development.boolValue))
{
EditorGUILayout.PropertyField(m_ExplicitNullChecks, k_ExplicitNullChecks);
}
// Force 'ExplicitNullChecks' to true if it's a development build.
if (m_Development.boolValue)
m_ExplicitNullChecks.boolValue = true;
if (m_IsClassicProfile)
{
m_SharedSettings.explicitNullChecks = m_ExplicitNullChecks.boolValue;
}
}
public void ShowDivideByZeroChecksToggle()
{
using (new EditorGUI.DisabledScope(m_Development.boolValue))
{
EditorGUILayout.PropertyField(m_ExplicitDivideByZeroChecks, k_ExplicitDivideByZeroChecks);
}
// Force 'explicitDivideByZeroChecks' to true if it's a development build.
if (m_Development.boolValue)
m_ExplicitDivideByZeroChecks.boolValue = true;
if (m_IsClassicProfile)
{
m_SharedSettings.explicitDivideByZeroChecks = m_ExplicitDivideByZeroChecks.boolValue;
}
}
public void ShowArrayBoundsChecksToggle()
{
using (new EditorGUI.DisabledScope(m_Development.boolValue))
{
EditorGUILayout.PropertyField(m_ExplicitArrayBoundsChecks, k_ExplicitArrayBoundsChecks);
}
// Force 'explicitArrayBoundsChecks' to true if it's a development build.
if (m_Development.boolValue)
m_ExplicitArrayBoundsChecks.boolValue = true;
if (m_IsClassicProfile)
{
m_SharedSettings.explicitArrayBoundsChecks = m_ExplicitArrayBoundsChecks.boolValue;
}
}
/// <summary>
/// Show internal platform build options for source-built editor.
/// </summary>
public virtual void ShowInternalPlatformBuildOptions()
{
}
/// Helper method for rendering an IMGUI popup over an enum
/// serialized property.
/// </summary>
protected void ShowIMGUIPopupOption<T>
(
GUIContent label,
(T SettingValue, GUIContent GUIString)[] options,
SerializedProperty currentSetting
) where T : Enum
{
using var vertical = new EditorGUILayout.VerticalScope();
using var prop = new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, currentSetting);
// Find the index of the currently set value relative to the GUI layout
var selectedIndex = Array.FindIndex(options,
match => match.SettingValue.Equals((T)(object)currentSetting.intValue));
selectedIndex = selectedIndex < 0 ? 0 : selectedIndex;
var GUIStrings = new GUIContent[options.Length];
for (var i = 0; i < options.Length; i++)
GUIStrings[i] = options[i].GUIString;
EditorGUI.BeginChangeCheck();
var newIndex = EditorGUILayout.Popup(label, selectedIndex, GUIStrings);
if (EditorGUI.EndChangeCheck())
currentSetting.intValue = (int)(object)options[newIndex].SettingValue;
}
/// <summary>
/// Helper method for rendering an IMGUI popup over an enum
/// serialized property.
/// </summary>
protected bool ShowIMGUIPopupOption<T>
(
GUIContent label,
T[] options,
GUIContent[] optionString,
SerializedProperty currentSetting
) where T : Enum
{
using var vertical = new EditorGUILayout.VerticalScope();
using var prop = new EditorGUI.PropertyScope(vertical.rect, GUIContent.none, currentSetting);
// Find the index of the currently set value relative to the GUI layout
var selectedIndex = Array.FindIndex(options,
match => match.Equals((T)(object)currentSetting.intValue));
selectedIndex = selectedIndex < 0 ? 0 : selectedIndex;
EditorGUI.BeginChangeCheck();
var newIndex = EditorGUILayout.Popup(label, selectedIndex, optionString);
if (EditorGUI.EndChangeCheck())
{
currentSetting.intValue = (int)(object)options[newIndex];
return true;
}
return false;
}
/// <summary>
/// Helper method for rendering an IMGUI popup for GUIContent
/// option values
/// </summary>
protected int ShowIMGUIPopupOptionForGUIContents
(
GUIContent label,
GUIContent[] optionValues,
GUIContent[] displayNames,
SerializedProperty property
)
{
EditorGUI.BeginChangeCheck();
using var verticalScope = new EditorGUILayout.VerticalScope();
using var propertyScope = new EditorGUI.PropertyScope(verticalScope.rect, GUIContent.none, property);
int selectedIndex = Math.Max(0, Array.FindIndex(optionValues, item => item.text == property.stringValue));
selectedIndex = EditorGUILayout.Popup(label, selectedIndex, displayNames);
if (EditorGUI.EndChangeCheck())
{
property.stringValue = optionValues[selectedIndex].text;
}
return selectedIndex;
}
}
}
| UnityCsReference/Editor/Mono/Modules/DefaultBuildProfileExtension.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Modules/DefaultBuildProfileExtension.cs",
"repo_id": "UnityCsReference",
"token_count": 10726
} | 324 |
// Unity 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.RegularExpressions;
using UnityEditor.IMGUI.Controls;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor.Networking.PlayerConnection
{
internal static class ConnectionUIHelper
{
private static string portPattern = @":\d{4,}";
private static string ipPattern = @"@\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}";
private static string localHostPattern = @" (Localhost prohibited)";
public static readonly string kDevices = L10n.Tr("Devices");
internal static class Content
{
public static string PlayerLogging = L10n.Tr("Player Logging");
public static string FullLog = L10n.Tr("Full Log [Developer Mode Only]");
public static string Logging = L10n.Tr("Logging");
}
public static string GetToolbarContent(string connectionName, GUIStyle style, int maxWidth)
{
var projectNameFromConnectionIdentifier = GetProjectNameFromConnectionIdentifier(ProfilerDriver.connectedProfiler);
var s = $"{GetPlayerNameFromIDString(GetIdString(connectionName))}{(string.IsNullOrEmpty(projectNameFromConnectionIdentifier) ? "" : $" - {projectNameFromConnectionIdentifier}")}";
return TruncateString(s, style, maxWidth);
}
public static string TruncateString(string s, GUIStyle style, float maxwidth)
{
if (style.CalcSize(GUIContent.Temp(s)).x < maxwidth)
return s;
maxwidth -= style.CalcSize(GUIContent.Temp("...")).x;
while (s.Length > 0 && style.CalcSize(GUIContent.Temp(s)).x > maxwidth)
{
s = s.Remove(s.Length - 1, 1);
}
return s + "...";
}
public static string GetPlayerNameFromId(int id)
{
return GetPlayerNameFromIDString(GetIdString(GeneralConnectionState.GetConnectionName(id)));
}
public static string GetIdString(string id)
{
//strip port info
var portMatch = Regex.Match(id, portPattern);
if (portMatch.Success)
{
id = id.Replace(portMatch.Value, "");
}
//strip ip info
var ipMatch = Regex.Match(id, ipPattern);
if (ipMatch.Success)
{
id = id.Replace(ipMatch.Value, "");
}
var removedWarning = false;
if (id.Contains(localHostPattern))
{
id = id.Replace(localHostPattern, "");
removedWarning = true;
}
id = id.Contains('(') ? id.Substring(id.IndexOf('(') + 1) : id;// trim the brackets
id = id.EndsWith(")") ? id.Substring(0, id.Length - 1) : id; // trimend cant be used as the player id might end with )
if (removedWarning)
id += localHostPattern;
return id;
}
public static string GetRuntimePlatformFromIDString(string id)
{
var commaIndx = id.IndexOf(',');
if (commaIndx == -1)
return "";
var s = id.Substring(0, commaIndx);
return RuntimePlatform.TryParse(s, out RuntimePlatform result) ? result.ToString() : "";
}
public static string GetPlayerNameFromIDString(string id)
{
var commaIndx = id.IndexOf(',');
return commaIndx != -1 ? id.Substring(commaIndx + 1) : id;
}
public static string GetPlayerType(string connectionName)
{
var parenthesisIndx = connectionName.IndexOf('(');
return parenthesisIndx != -1 ? connectionName.Substring(0, parenthesisIndx) : connectionName;
}
public static string GetProjectNameFromConnectionIdentifier(int connectionId)
{
return ProfilerDriver.GetProjectName(connectionId);
}
public static string GetIP(int connectionId)
{
return ProfilerDriver.GetConnectionIP(connectionId);
}
public static string GetPort(int connectionId)
{
var port = ProfilerDriver.GetConnectionPort(connectionId);
return port == 0 ? "-" : port.ToString();
}
public static GUIContent GetIcon(string name)
{
var content = GetBuildTargetIcon(name);
if (content == null)
{
content = name switch
{
"Editor" => EditorGUIUtility.IconContent("d_SceneAsset Icon"),
"WindowsEditor" => EditorGUIUtility.IconContent("d_SceneAsset Icon"),
"WindowsPlayer" => EditorGUIUtility.IconContent("BuildSettings.Metro.Small"),
"Android" => EditorGUIUtility.IconContent("BuildSettings.Android.Small"),
"OSXPlayer" => EditorGUIUtility.IconContent("BuildSettings.Standalone.Small"),
"IPhonePlayer" => EditorGUIUtility.IconContent("BuildSettings.iPhone.Small"),
"WebGLPlayer" => EditorGUIUtility.IconContent("BuildSettings.WebGL.Small"),
"tvOS" => EditorGUIUtility.IconContent("BuildSettings.tvOS.Small"),
"Lumin" => EditorGUIUtility.IconContent("BuildSettings.Lumin.small"),
"LinuxPlayer" => EditorGUIUtility.IconContent("BuildSettings.EmbeddedLinux.Small"),
"WSAPlayerX86" => EditorGUIUtility.IconContent("BuildSettings.Metro.Small"),
"WSAPlayerX64" => EditorGUIUtility.IconContent("BuildSettings.Metro.Small"),
"WSAPlayerARM" => EditorGUIUtility.IconContent("BuildSettings.Metro.Small"),
"Switch" => EditorGUIUtility.IconContent("BuildSettings.Switch.Small"),
"EmbeddedLinuxArm64" => EditorGUIUtility.IconContent("BuildSettings.EmbeddedLinux.Small"),
"EmbeddedLinuxArm32" => EditorGUIUtility.IconContent("BuildSettings.EmbeddedLinux.Small"),
"EmbeddedLinuxX64" => EditorGUIUtility.IconContent("BuildSettings.EmbeddedLinux.Small"),
"EmbeddedLinuxX86" => EditorGUIUtility.IconContent("BuildSettings.EmbeddedLinux.Small"),
"QNXArm64" => EditorGUIUtility.IconContent("BuildSettings.QNX.Small"),
"QNXArm32" => EditorGUIUtility.IconContent("BuildSettings.QNX.Small"),
"QNXX64" => EditorGUIUtility.IconContent("BuildSettings.QNX.Small"),
"QNXX86" => EditorGUIUtility.IconContent("BuildSettings.QNX.Small"),
"PS4" => EditorGUIUtility.IconContent("BuildSettings.PS4.Small"),
"PS5" => EditorGUIUtility.IconContent("BuildSettings.PS5.Small"),
"Devices" => EditorGUIUtility.IconContent("BuildSettings.Standalone.Small"),
"<unknown>" => EditorGUIUtility.IconContent("BuildSettings.Broadcom"),
_ => EditorGUIUtility.IconContent("BuildSettings.Broadcom")
};
}
return content;
}
private static GUIContent GetBuildTargetIcon(string name)
{
var target = BuildPipeline.GetBuildTargetByName(name);
if (target == BuildTarget.NoTarget)
{
return null;
}
var namedBuildTarget = Build.NamedBuildTarget.FromActiveSettings(target);
if (namedBuildTarget == null)
{
return null;
}
var buildPlatform = Build.BuildPlatforms.instance.BuildPlatformFromNamedBuildTarget(namedBuildTarget);
if (buildPlatform == null || buildPlatform.smallIcon == null)
{
return null;
}
return new GUIContent(buildPlatform.smallIcon);
}
}
internal class ConnectionDropDownItem : TreeViewItem
{
public Func<bool> m_Connected;
public Action m_OnSelected;
public string m_SubGroup;
public bool m_Disabled;
public string ProjectName;
public float ProjectNameSize;
public ConnectionMajorGroup m_TopLevelGroup;
public int m_ConnectionId;
internal string DisplayName;
public float DisplayNameSize;
internal string IP;
internal float IPSize;
internal string Port;
internal float PortSize;
internal bool OldConnectionFormat;
public bool IsDevice;
public GUIContent IconContent;
static class Content
{
public static readonly string DirectConnection = L10n.Tr("Direct Connection");
}
internal enum ConnectionMajorGroup
{
Editor,
Logging,
Local,
Remote,
ConnectionsWithoutID,
Direct,
Unknown
}
internal static string[] ConnectionMajorGroupLabels =
{
"Editor",
"Logging",
"Local",
"Remote",
"Connections Without ID",
"Direct Connection",
"Unknown"
};
public ConnectionDropDownItem(string content, int connectionId, string subGroup, ConnectionMajorGroup topLevelGroup, Func<bool> connected, Action onSelected,
bool isDevice = false, string iconString = null)
{
var idString = ConnectionUIHelper.GetIdString(content);
DisplayName = subGroup == ConnectionUIHelper.kDevices ? content : ConnectionUIHelper.GetPlayerNameFromIDString(idString);
DisplayNameSize = ConnectionDropDownStyles.sTVLine.CalcSize(GUIContent.Temp(DisplayName)).x;
ProjectName = subGroup == ConnectionUIHelper.kDevices ? "" : ConnectionUIHelper.GetProjectNameFromConnectionIdentifier(connectionId);
ProjectNameSize = ConnectionDropDownStyles.sTVLine.CalcSize(GUIContent.Temp(ProjectName)).x;
IP = ConnectionUIHelper.GetIP(connectionId);
IPSize = ConnectionDropDownStyles.sTVLine.CalcSize(GUIContent.Temp(IP)).x;
Port = ConnectionUIHelper.GetPort(connectionId);
PortSize = ConnectionDropDownStyles.sTVLine.CalcSize(GUIContent.Temp(Port)).x;
m_ConnectionId = connectionId;
m_Connected = connected;
m_OnSelected = onSelected;
m_SubGroup = string.IsNullOrEmpty(subGroup) ? ConnectionUIHelper.GetRuntimePlatformFromIDString(idString) : subGroup;
m_TopLevelGroup = topLevelGroup == ConnectionMajorGroup.Unknown ? (m_SubGroup == Content.DirectConnection ? ConnectionMajorGroup.Direct : (ProfilerDriver.IsIdentifierOnLocalhost(connectionId) ? ConnectionMajorGroup.Local : ConnectionMajorGroup.Remote)) : topLevelGroup;
if (m_TopLevelGroup == ConnectionMajorGroup.Direct)
{
DisplayName = content;
}
if (string.IsNullOrEmpty(m_SubGroup))
{
if (idString == "Editor" || idString == "Main Editor Process")
{
m_TopLevelGroup = ConnectionMajorGroup.Editor;
m_SubGroup = "Editor";
}
else
{
DisplayName = content;
m_TopLevelGroup = ConnectionMajorGroup.ConnectionsWithoutID;
OldConnectionFormat = true;
}
}
displayName = DisplayName + ProjectName;
id = GenerateID();
IsDevice = isDevice;
if (isDevice)
{
IconContent = ConnectionUIHelper.GetIcon(iconString);
}
}
public int GenerateID()
{
return (DisplayName + ProjectName + IP + Port).GetHashCode();
}
public bool DisplayProjectName()
{
return !IsDevice && !OldConnectionFormat &&
ConnectionMajorGroup.Direct != m_TopLevelGroup && ConnectionMajorGroup.Logging != m_TopLevelGroup;
}
public bool DisplayPort()
{
return !IsDevice && !OldConnectionFormat &&
ConnectionMajorGroup.Direct != m_TopLevelGroup && ConnectionMajorGroup.Logging != m_TopLevelGroup;
}
public bool DisplayIP()
{
return !IsDevice && !OldConnectionFormat &&
ConnectionMajorGroup.Direct != m_TopLevelGroup && ConnectionMajorGroup.Logging != m_TopLevelGroup;
}
}
enum ConnectionDropDownColumns
{
DisplayName,
ProjectName,
IP,
Port
}
internal class ConnectionDropDownMultiColumnHeader : MultiColumnHeader
{
public ConnectionDropDownMultiColumnHeader(MultiColumnHeaderState state) : base(state)
{
}
protected override void AddColumnHeaderContextMenuItems(GenericMenu menu)
{
base.AddColumnHeaderContextMenuItems(menu);
menu.menuItems.RemoveAt(0);
}
}
internal class ConnectionTreeView : TreeView
{
public List<ConnectionDropDownItem> dropDownItems = new List<ConnectionDropDownItem>(0);
public string search = "";
public float DisplayNameIndent => 2 * depthIndentWidth + ConnectionDropDownStyles.ToggleRectWidth + (2 * ConnectionDropDownStyles.SeparatorVerticalPadding) + ConnectionDropDownStyles.SeparatorLineWidth;
Action m_CloseWindow;
public ConnectionTreeView(TreeViewState state, ConnectionDropDownMultiColumnHeader multiColumnHeader, Action closeWindow) : base(state, multiColumnHeader)
{
showAlternatingRowBackgrounds = false;
baseIndent = 0;
depthIndentWidth = foldoutWidth;
rowHeight = 20f;
m_CloseWindow = closeWindow;
}
protected override TreeViewItem BuildRoot()
{
var root = new TreeViewItem { id = -1, depth = -1, displayName = "Root" };
foreach (var connectionType in dropDownItems.OrderBy(x => x.m_TopLevelGroup).GroupBy(x => x.m_TopLevelGroup))
{
if (connectionType.Key == ConnectionDropDownItem.ConnectionMajorGroup.Editor)
{
foreach (var connectionDropDownItem in connectionType)
{
root.AddChild(connectionDropDownItem);
}
continue;
}
// connection major group
var i = new TreeViewItem { displayName = ConnectionDropDownItem.ConnectionMajorGroupLabels[(int)connectionType.Key]};
i.id = (i.displayName + root.displayName).GetHashCode();
root.AddChild(i);
foreach (var playerType in connectionType.Where(x => x.m_SubGroup != null).GroupBy(x => x.m_SubGroup).OrderBy(x => x.Key))
{
// direct and preeasy id connections dont have any subgrouping
if (i.displayName == ConnectionDropDownItem.ConnectionMajorGroupLabels[(int)ConnectionDropDownItem.ConnectionMajorGroup.Direct] ||
i.displayName == ConnectionDropDownItem.ConnectionMajorGroupLabels[(int)ConnectionDropDownItem.ConnectionMajorGroup.ConnectionsWithoutID])
{
foreach (var player in playerType.OrderBy(x => x.DisplayName).Where(x => x.DisplayName.ToLower().Contains(search.ToLower())))
i.AddChild(player);
continue;
}
// if we match a top level group add all of its children and return
if (string.Equals(i.displayName.ToLower(), search.ToLower(), StringComparison.Ordinal))
{
AddChildren(playerType, i);
SetupDepthsFromParentsAndChildren(root);
return root;
}
// if we match a player type add all of its children and continue
if (string.Equals(playerType.Key.ToLower(), search.ToLower(), StringComparison.Ordinal))
{
AddChildren(playerType, i);
continue;
}
AddChildren(playerType, i, search);
}
if (!i.hasChildren)
root.children.Remove(i);
}
SetupDepthsFromParentsAndChildren(root);
return root;
}
TreeViewItem AddHeaderItem(string name, TreeViewItem item)
{
if (name == item.displayName) return item;
var newItem = new TreeViewItem { displayName = name, id = (name + item.parent.displayName).GetHashCode() };
item.AddChild(newItem);
return newItem;
}
void AddChildren(IGrouping<string, ConnectionDropDownItem> group, TreeViewItem treeViewItem, string filter = null)
{
if (filter == null)
{
var header = AddHeaderItem(group.Key, treeViewItem);
foreach (var player in group.OrderBy(x => x.DisplayName))
header.AddChild(player);
}
else
{
var header = AddHeaderItem(group.Key, treeViewItem);
bool addedChild = false;
foreach (var player in group.Where(x => x.DisplayName.ToLower().Contains(filter.ToLower()))
.OrderBy(x => x.DisplayName))
{
addedChild = true;
header.AddChild(player);
}
if (!addedChild && treeViewItem.hasChildren)
treeViewItem.children.Remove(treeViewItem.children.Last());
}
}
protected override void SingleClickedItem(int id)
{
var t = dropDownItems.Find(x => x.id == id);
if (t is ConnectionDropDownItem && !t.m_Disabled)
{
t.m_OnSelected?.Invoke();
m_CloseWindow.Invoke();
EditorGUIUtility.ExitGUI();
return;
}
var item = FindItem(id, rootItem);
controller.UserInputChangedExpandedState(item, FindRowOfItem(item), !IsExpanded(id));
}
protected override void RowGUI(RowGUIArgs args)
{
var item = args.item;
if (item is ConnectionDropDownItem cddi)
{
GUI.enabled = !cddi.m_Disabled;
if (GUI.enabled && args.selected && Event.current.keyCode == KeyCode.Return)
{
cddi.m_OnSelected?.Invoke();
Repaint();
}
}
for (int i = 0; i < args.GetNumVisibleColumns(); ++i)
{
CellGUI(args.GetCellRect(i), item, (ConnectionDropDownColumns)args.GetColumn(i), ref args);
}
GUI.enabled = true;
}
void CellGUI(Rect cellRect, TreeViewItem item, ConnectionDropDownColumns column, ref RowGUIArgs args)
{
// Center cell rect vertically (makes it easier to place controls, icons etc in the cells)
CenterRectUsingSingleLineHeight(ref cellRect);
ConnectionDropDownItem cddi = null;
if (item is ConnectionDropDownItem downItem)
cddi = downItem;
switch (column)
{
case ConnectionDropDownColumns.DisplayName:
if (cddi != null)
{//actual connections
var rect = cellRect;
rect.x += GetContentIndent(item) - foldoutWidth;
EditorGUI.BeginChangeCheck();
rect.width = ConnectionDropDownStyles.ToggleRectWidth;
var isConnected = cddi.m_Connected?.Invoke() ?? false;
GUI.Label(rect, (isConnected ? EditorGUIUtility.IconContent("Valid") : GUIContent.none));
rect.x += ConnectionDropDownStyles.ToggleRectWidth;
if (cddi.IsDevice)
{
EditorGUI.LabelField(new Rect(rect.x, rect.y, rowHeight, rowHeight), cddi.IconContent);
rect.x += rowHeight;
}
var textRect = cellRect;
textRect.x = rect.x;
textRect.width = cellRect.width - (textRect.x - cellRect.x);
GUI.Label(textRect, ConnectionUIHelper.TruncateString(cddi.DisplayName, ConnectionDropDownStyles.sTVLine, textRect.width));
if (EditorGUI.EndChangeCheck())
{
cddi.m_OnSelected.Invoke();
}
}
else
{
var r = cellRect;
if (item.depth <= 0)
{// major group headers
if (args.row != 0)
EditorGUI.DrawRect(new Rect(r.x, r.y, args.rowRect.width, 1f), ConnectionDropDownStyles.SeparatorColor);
r.x += GetContentIndent(item);
r.width = args.rowRect.width - GetContentIndent(item);
GUI.Label(r, item.displayName, EditorStyles.boldLabel);
}
else
{// sub group headers
r.x += GetContentIndent(item);
EditorGUI.LabelField(new Rect(r.x, r.y, rowHeight, rowHeight), ConnectionUIHelper.GetIcon(item.displayName));
GUI.Label(new Rect(r.x + rowHeight, r.y, r.width - rowHeight, r.height), item.displayName, EditorStyles.miniBoldLabel);
}
}
break;
case ConnectionDropDownColumns.ProjectName:
if(item.depth > 1)
{
DrawVerticalSeparatorLine(cellRect);
GUI.Label(cellRect, ConnectionUIHelper.TruncateString(cddi.ProjectName, ConnectionDropDownStyles.sTVLine, cellRect.width));
}
break;
case ConnectionDropDownColumns.IP:
if(item.depth > 1)
{
DrawVerticalSeparatorLine(cellRect);
GUI.Label(cellRect, ConnectionUIHelper.TruncateString(cddi.IP, ConnectionDropDownStyles.sTVLine, cellRect.width));
}
break;
case ConnectionDropDownColumns.Port:
if(item.depth > 1)
{
DrawVerticalSeparatorLine(cellRect);
GUI.Label(cellRect, ConnectionUIHelper.TruncateString(cddi.Port, ConnectionDropDownStyles.sTVLine, cellRect.width));
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(column), column, null);
}
}
private void DrawVerticalSeparatorLine(Rect cellRect)
{
EditorGUI.DrawRect(
new Rect(cellRect.x - 4, cellRect.y + ConnectionDropDownStyles.SeparatorVerticalPadding, ConnectionDropDownStyles.SeparatorLineWidth,
cellRect.height - 2 * ConnectionDropDownStyles.SeparatorVerticalPadding), ConnectionDropDownStyles.SeparatorColor);
}
public float GetHeight()
{
if (dropDownItems.Count > 0)
return totalHeight;
return 0;
}
}
internal class ConnectionDropDownStyles
{
internal static float searchFieldPadding = 12f;
internal static float searchFieldVerticalSpacing = 12f;
internal static GUIStyle sConnectionTrouble = "MenuItem";
internal static GUIStyle sTVLine = "TV Line";
internal static readonly Color SeparatorColor = new Color(0.5f, 0.5f, 0.5f, 0.5f);
internal static int ToggleRectWidth = 16;
internal static float SeparatorLineWidth = 1f;
internal static float SeparatorVerticalPadding = 2f;
public static float troubleShootBtnPadding = 10f;
}
internal class ConnectionTreeViewWindow : PopupWindowContent
{
private ConnectionTreeView m_connectionTreeView;
private SearchField m_SearchField;
private ConnectionDropDownMultiColumnHeader multiColumnHeader;
private IConnectionStateInternal state;
private static MultiColumnHeaderState multiColumnHeaderState;
private static TreeViewState treeViewState;
private List<ConnectionDropDownItem> connectionItems;
private static bool firstOpen = true;
float loggingVerticalPadding = 3f;
float searchToLoggingPadding = 8f;
ConsoleWindow.ConsoleAttachToPlayerState consoleAttachToPlayerState;
bool didFocus;
Dictionary<int, bool> m_expandedState = new Dictionary<int, bool>();
bool searching;
public ConnectionTreeViewWindow(IConnectionStateInternal internalState, Rect rect)
{
state = internalState;
state.AddItemsToTree(this, rect);
if (multiColumnHeaderState == null)
{
treeViewState = new TreeViewState();
multiColumnHeaderState = CreateDefaultMultiColumnHeaderState(100);
multiColumnHeader = new ConnectionDropDownMultiColumnHeader(multiColumnHeaderState);
m_connectionTreeView = new ConnectionTreeView(treeViewState, multiColumnHeader, ClosePopUp) { dropDownItems = connectionItems };
SetMinColumnWidths();
return;
}
multiColumnHeader = new ConnectionDropDownMultiColumnHeader(multiColumnHeaderState);
m_connectionTreeView = new ConnectionTreeView(treeViewState, multiColumnHeader, ClosePopUp) { dropDownItems = connectionItems };
}
static class Content
{
private static GUIStyle style = MultiColumnHeader.DefaultStyles.columnHeader;
public static GUIContent PlayerName = new GUIContent("Player Name");
public static float PlayerNameMinWidth = 150;
public static GUIContent ProjectName = new GUIContent("Product Name");
public static float ProjectNameMinWidth = style.CalcSize(ProjectName).x;
public static GUIContent IP = new GUIContent("IP");
public static float IPMinWidth = style.CalcSize(GUIContent.Temp("00000")).x;
public static GUIContent Port = new GUIContent("Port");
public static float PortMinWidth = style.CalcSize(GUIContent.Temp("00000")).x;
public static GUIContent TroubleShoot = new GUIContent("Troubleshoot Connection Issues");
}
void ClosePopUp()
{
this.editorWindow.Close();
}
public override void OnClose()
{
state = null;
}
internal void Reload()
{
if (m_connectionTreeView.dropDownItems.Count > 0)
{
m_connectionTreeView.Reload();
}
}
public override void OnOpen()
{
Reload();
if (firstOpen)
m_connectionTreeView.ExpandAll();
firstOpen = false;
m_SearchField = new SearchField();
}
public override void OnGUI(Rect rect)
{
EditorGUI.BeginChangeCheck();
m_connectionTreeView.search = m_SearchField.OnGUI(new Rect(rect.x + ConnectionDropDownStyles.searchFieldPadding, rect.y + ConnectionDropDownStyles.searchFieldPadding, rect.width - (2 * ConnectionDropDownStyles.searchFieldPadding), EditorGUI.kSingleLineHeight), m_connectionTreeView.search);
if (!didFocus && !m_SearchField.HasFocus())
{
m_SearchField.SetFocus();
didFocus = true;
}
if (EditorGUI.EndChangeCheck())
{
if (!string.IsNullOrEmpty(m_connectionTreeView.search))
{
if (!searching)
{
var rows = m_connectionTreeView.GetRows();
m_expandedState.Clear();
foreach (var row in rows)
{
m_expandedState.Add(row.id, m_connectionTreeView.IsExpanded(row.id));
}
}
m_connectionTreeView.ExpandAll();
searching = true;
}
else
{
if (searching)
{
foreach (var b in m_expandedState)
{
m_connectionTreeView.SetExpanded(b.Key, b.Value);
}
searching = false;
}
}
Reload();
}
rect.y += EditorGUI.kSingleLineHeight + ConnectionDropDownStyles.searchFieldVerticalSpacing;
if (consoleAttachToPlayerState != null)
{
rect.y += searchToLoggingPadding;
EditorGUI.BeginChangeCheck();
GUI.Toggle(new Rect(rect.x + ConnectionDropDownStyles.searchFieldPadding, rect.y, rect.width, EditorGUI.kSingleLineHeight), consoleAttachToPlayerState.IsConnected(), ConnectionUIHelper.Content.PlayerLogging);
if (EditorGUI.EndChangeCheck())
{
consoleAttachToPlayerState.PlayerLoggingOptionSelected();
}
rect.y += EditorGUI.kSingleLineHeight + loggingVerticalPadding;
GUI.enabled = consoleAttachToPlayerState.IsConnected();
m_connectionTreeView.dropDownItems.ForEach(x => x.m_Disabled = !GUI.enabled);
EditorGUI.BeginChangeCheck();
GUI.Toggle(new Rect(rect.x + ConnectionDropDownStyles.searchFieldPadding, rect.y, rect.width, EditorGUI.kSingleLineHeight), consoleAttachToPlayerState.IsLoggingFullLog(), ConnectionUIHelper.Content.FullLog);
if (EditorGUI.EndChangeCheck())
{
consoleAttachToPlayerState.FullLogOptionSelected();
}
rect.y += EditorGUI.kSingleLineHeight + loggingVerticalPadding;
}
m_connectionTreeView?.OnGUI(new Rect(rect.x, rect.y, rect.width, (float)m_connectionTreeView?.totalHeight));
rect.y += (float)m_connectionTreeView?.totalHeight;
GUI.enabled = true;
EditorGUI.DrawDelimiterLine(new Rect(rect.x,rect.y,rect.width,1f));
rect.y += 1f;
rect.y += ConnectionDropDownStyles.troubleShootBtnPadding / 2f;
if (EditorGUI.Button(rect, Content.TroubleShoot, ConnectionDropDownStyles.sConnectionTrouble))
{
var help = Help.FindHelpNamed("profiler-profiling-applications");
Help.BrowseURL(help);
}
if(Event.current.type == EventType.MouseMove)
Event.current.Use();
}
private void SetMinColumnWidths()
{
foreach (var stateVisibleColumn in m_connectionTreeView.multiColumnHeader.state.visibleColumns)
{
m_connectionTreeView.multiColumnHeader.state.columns[stateVisibleColumn].width = GetLargestWidth(stateVisibleColumn);
}
}
public static MultiColumnHeaderState CreateDefaultMultiColumnHeaderState(float treeViewWidth)
{
var columns = new[]
{
new MultiColumnHeaderState.Column
{
headerContent = Content.PlayerName,
headerTextAlignment = TextAlignment.Left,
autoResize = false,
allowToggleVisibility = false,
minWidth = Content.PlayerNameMinWidth,
canSort = false
},
new MultiColumnHeaderState.Column
{
headerContent = Content.ProjectName,
headerTextAlignment = TextAlignment.Left,
autoResize = false,
allowToggleVisibility = true,
minWidth = Content.ProjectNameMinWidth,
canSort = false
},
new MultiColumnHeaderState.Column
{
headerContent = Content.IP,
headerTextAlignment = TextAlignment.Left,
autoResize = false,
allowToggleVisibility = true,
minWidth = Content.IPMinWidth,
canSort = false,
},
new MultiColumnHeaderState.Column
{
headerContent = Content.Port,
headerTextAlignment = TextAlignment.Left,
autoResize = false,
allowToggleVisibility = true,
minWidth = Content.PortMinWidth,
canSort = false
}
};
var state = new MultiColumnHeaderState(columns);
return state;
}
public void AddDisabledItem(ConnectionDropDownItem connectionDropDownItem)
{
connectionDropDownItem.m_Disabled = true;
AddItem(connectionDropDownItem);
}
public void AddItem(ConnectionDropDownItem connectionDropDownItem)
{
// *begin-nonstandard-formatting*
connectionItems ??= new List<ConnectionDropDownItem>();
// *end-nonstandard-formatting*
// this is a hack to show switch connected over ethernet in devices
if (connectionDropDownItem.IP == "127.0.0.1" && ProfilerDriver.GetConnectionIdentifier(connectionDropDownItem.m_ConnectionId).StartsWith("Switch"))
{
connectionDropDownItem.m_TopLevelGroup = ConnectionDropDownItem.ConnectionMajorGroup.Local;
connectionDropDownItem.m_SubGroup = "Devices";
connectionDropDownItem.IsDevice = true;
connectionDropDownItem.IconContent = ConnectionUIHelper.GetIcon("Switch");
var fullName = ProfilerDriver.GetConnectionIdentifier(connectionDropDownItem.m_ConnectionId);
var start = fullName.IndexOf('-') + 1;
var end = fullName.IndexOf('(');
connectionDropDownItem.DisplayName = $"{fullName.Substring(start, end - start)} - {ProfilerDriver.GetProjectName(connectionDropDownItem.m_ConnectionId)}";
}
var dupes = connectionItems.FirstOrDefault(x => x.DisplayName == connectionDropDownItem.DisplayName && x.IP == connectionDropDownItem.IP && x.Port == connectionDropDownItem.Port);
if (dupes != null)
connectionItems.Remove(dupes);
connectionItems.Add(connectionDropDownItem);
}
public bool HasItem(string name)
{
return connectionItems != null && connectionItems.Any(x => x.DisplayName == name);
}
public override Vector2 GetWindowSize()
{
Vector2 v = Vector2.zero;
v.y += EditorGUI.kSingleLineHeight + ConnectionDropDownStyles.searchFieldVerticalSpacing; // search field
v.x = Mathf.Max(200, GetTotalVisibleWidth());
if (consoleAttachToPlayerState != null)
{
v.y += searchToLoggingPadding + 2 * (EditorGUI.kSingleLineHeight + loggingVerticalPadding);
}
v.y += GetTotalTreeViewHeight();
v.y += EditorGUI.kSingleLineHeight;
v.y += ConnectionDropDownStyles.troubleShootBtnPadding;
return v;
}
private float GetTotalTreeViewHeight()
{
return m_connectionTreeView.GetHeight();
}
float GetLargestWidth(int idx)
{
return idx switch
{
0 => GetRequiredDisplayNameColumnWidth(),
1 => GetRequiredProjectNameColumnWidth(),
2 => GetRequiredIPColumnWidth(),
3 => GetRequiredPortColumnWidth(),
_ => 0
};
}
private float GetRequiredProjectNameColumnWidth()
{
return Mathf.Max(Content.ProjectNameMinWidth,
connectionItems.Max(x => x.ProjectNameSize));
}
private float GetRequiredDisplayNameColumnWidth()
{
return Mathf.Max(Content.PlayerNameMinWidth,
connectionItems.Max(x => x.DisplayNameSize) + m_connectionTreeView.DisplayNameIndent );
}
private float GetRequiredIPColumnWidth()
{
return Mathf.Max(Content.IPMinWidth, connectionItems.Max(x => x.IPSize));
}
private float GetRequiredPortColumnWidth()
{
return Mathf.Max(Content.PortMinWidth, connectionItems.Max(x => x.PortSize));
}
float GetTotalVisibleWidth()
{
return m_connectionTreeView.multiColumnHeader.state.widthOfAllVisibleColumns;
}
//needed for tests
public int GetItemCount()
{
return m_connectionTreeView?.dropDownItems.Count ?? 0;
}
public void Clear()
{
m_connectionTreeView?.dropDownItems.Clear();
}
public void SetLoggingOptions(ConsoleWindow.ConsoleAttachToPlayerState state)
{
consoleAttachToPlayerState = state;
}
}
}
| UnityCsReference/Editor/Mono/Networking/PlayerConnection/ConnectionDropDown.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Networking/PlayerConnection/ConnectionDropDown.cs",
"repo_id": "UnityCsReference",
"token_count": 18261
} | 325 |
// Unity 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 System.Reflection;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.Serialization;
using UnityEngine.UIElements;
namespace UnityEditor.Overlays
{
[Serializable]
public class SaveData : IEquatable<SaveData>
{
// Note on the obsolete fields in this class:
// Previously, overlays were not serialized in any form. In 2023.2, overlays are serialized via json to the
// SaveData.contents field. This removes the need for many state variables previously required to restore an
// overlay to it's last position, visibility, dock, etc. SaveData as a class is still necessary, however, as
// the non-obsolete fields are conditions that are not known the Overlay itself.
// In the interest of backwards compatibility, the obsolete fields are left here for 2023.2. In 2024.1 (or
// whatever the next version happens to be), consider removing these. Overlay save data is implicitly updated
// when closing an editor or window for all overlays known to the window.
const int k_InvalidIndex = -1;
[SerializeField]
internal DockPosition dockPosition = DockPosition.Bottom;
[SerializeField]
internal string containerId = string.Empty;
[SerializeField]
internal bool displayed;
[SerializeField]
internal string id;
[SerializeField]
internal int index = k_InvalidIndex;
[SerializeField]
internal string contents;
[SerializeField, Obsolete]
internal bool floating;
[SerializeField, Obsolete]
internal bool collapsed;
[SerializeField, Obsolete]
internal Vector2 snapOffset;
[SerializeField, Obsolete]
internal Vector2 snapOffsetDelta;
[SerializeField, Obsolete]
internal SnapCorner snapCorner;
[SerializeField, Obsolete]
internal Layout layout = Layout.Panel;
[SerializeField, Obsolete]
internal Vector2 size;
[SerializeField, Obsolete]
[FormerlySerializedAs("sizeOverriden")]
internal bool sizeOverridden;
public SaveData() { }
#pragma warning disable 612
internal SaveData(SaveData other)
{
dockPosition = other.dockPosition;
containerId = other.containerId;
id = other.id;
index = other.index;
contents = other.contents;
// obsolete
floating = other.floating;
collapsed = other.collapsed;
displayed = other.displayed;
snapOffset = other.snapOffset;
snapOffsetDelta = other.snapOffsetDelta;
snapCorner = other.snapCorner;
layout = other.layout;
size = other.size;
sizeOverridden = other.sizeOverridden;
}
public SaveData(Overlay overlay)
: this(overlay, k_InvalidIndex) { }
internal SaveData(Overlay overlay, int indexInContainer)
{
if (indexInContainer < 0)
if (overlay.container == null || !overlay.container.GetOverlayIndex(overlay, out _, out indexInContainer))
indexInContainer = k_InvalidIndex;
string container = overlay.container != null ? overlay.container.name : "";
DockPosition dock = overlay.container != null
&& overlay.container.ContainsOverlay(overlay, OverlayContainerSection.BeforeSpacer)
? DockPosition.Top
: DockPosition.Bottom;
containerId = container;
index = indexInContainer;
dockPosition = dock;
id = overlay.id;
displayed = overlay.displayed;
contents = EditorJsonUtility.ToJson(overlay);
// obsolete
floating = overlay.floating;
collapsed = overlay.collapsed;
layout = overlay.layout;
snapCorner = overlay.floatingSnapCorner;
snapOffset = overlay.floatingSnapOffset - overlay.m_SnapOffsetDelta;
snapOffsetDelta = overlay.m_SnapOffsetDelta;
size = overlay.sizeToSave;
sizeOverridden = overlay.sizeOverridden;
}
public bool Equals(SaveData other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return dockPosition == other.dockPosition
&& containerId == other.containerId
&& id == other.id
&& index == other.index
&& displayed == other.displayed
&& floating == other.floating
&& collapsed == other.collapsed
&& snapOffset.Equals(other.snapOffset)
&& snapOffsetDelta.Equals(other.snapOffsetDelta)
&& snapCorner == other.snapCorner
&& layout == other.layout
&& size == other.size
&& sizeOverridden == other.sizeOverridden;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((SaveData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int)dockPosition;
hashCode = (hashCode * 397) ^ (containerId != null ? containerId.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ floating.GetHashCode();
hashCode = (hashCode * 397) ^ (id != null ? id.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ collapsed.GetHashCode();
hashCode = (hashCode * 397) ^ displayed.GetHashCode();
hashCode = (hashCode * 397) ^ snapOffset.GetHashCode();
hashCode = (hashCode * 397) ^ snapOffsetDelta.GetHashCode();
hashCode = (hashCode * 397) ^ (int)snapCorner;
hashCode = (hashCode * 397) ^ index;
hashCode = (hashCode * 397) ^ (int)layout;
hashCode = (hashCode * 397) ^ size.GetHashCode();
hashCode = (hashCode * 397) ^ sizeOverridden.GetHashCode();
return hashCode;
}
}
public override string ToString()
{
return $"dockPosition: {dockPosition}" +
$"\ncontainerId: {containerId}" +
$"\nfloating: {floating}" +
$"\ncollapsed: {collapsed}" +
$"\ndisplayed: {displayed}" +
$"\nsnapOffset: {snapOffset}" +
$"\nsnapOffsetDelta: {snapOffsetDelta}" +
$"\nsnapCorner: {snapCorner}" +
$"\nid: {id}" +
$"\nindex: {index}" +
$"\nlayout: {layout}" +
$"\nsize: {size}" +
$"\nsizeOverridden: {sizeOverridden}";
}
#pragma warning restore 612
}
[Serializable]
sealed class ContainerData
{
public string containerId;
public float scrollOffset;
}
//Dock position within container
//for a horizontal container, Top is left, Bottom is right
public enum DockPosition
{
Top,
Bottom
}
enum SnapCorner
{
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
// public API to set a default docking zone. default is RightColumnBottom
public enum DockZone
{
LeftToolbar = 0,
RightToolbar = 1,
TopToolbar = 2,
BottomToolbar = 3,
LeftColumn = 4,
RightColumn = 5,
Floating = 6
}
[Serializable]
public sealed class OverlayCanvas : ISerializationCallbackReceiver
{
internal static readonly string ussClassName = "unity-overlay-canvas";
const string k_UxmlPath = "UXML/Overlays/overlay-canvas.uxml";
const string k_UxmlPathDropZone = "UXML/Overlays/overlay-toolbar-dropzone.uxml";
internal const string k_StyleCommon = "StyleSheets/Overlays/OverlayCommon.uss";
internal const string k_StyleLight = "StyleSheets/Overlays/OverlayLight.uss";
internal const string k_StyleDark = "StyleSheets/Overlays/OverlayDark.uss";
internal const int k_OverlayMinVisibleArea = 24;
const string k_FloatingContainer = "overlay-container--floating";
const string k_ToolbarArea = "overlay-toolbar-area";
const string k_DropTargetClassName = "overlay-droptarget";
const string k_DefaultContainer = "overlay-container-default";
static VisualTreeAsset s_TreeAsset;
static VisualTreeAsset s_DropZoneTreeAsset;
static SaveData defaultSaveData => new SaveData()
{
containerId = null,
displayed = false,
dockPosition = DockPosition.Bottom,
index = int.MaxValue
};
// order must match OverlayDockArea
static readonly string[] k_DockZoneContainerIDs = new string[7]
{
"overlay-toolbar__left",
"overlay-toolbar__right",
"overlay-toolbar__top",
"overlay-toolbar__bottom",
"overlay-container--left",
"overlay-container--right",
"Floating"
};
internal static DockZone GetDockZone(OverlayContainer container)
{
for(int i = 0, c = k_DockZoneContainerIDs.Length; i < c; i++)
if (k_DockZoneContainerIDs[i] == container.name)
return (DockZone)i;
return DockZone.Floating;
}
// used by tests
[EditorBrowsable(EditorBrowsableState.Never)]
internal OverlayContainer GetDockZoneContainer(DockZone zone)
{
foreach(var container in m_Containers)
if (container.name == k_DockZoneContainerIDs[(int)zone])
return container;
return null;
}
//Used by tests
internal bool m_MouseInCurrentCanvas = false;
internal string lastAppliedPresetName => m_LastAppliedPresetName;
List<Overlay> m_Overlays = new List<Overlay>();
List<Overlay> m_TransientOverlays = new();
[SerializeField]
string m_LastAppliedPresetName = "Default";
[SerializeField]
List<SaveData> m_SaveData = new List<SaveData>();
[SerializeField]
List<ContainerData> m_ContainerData = new List<ContainerData>();
[SerializeField]
bool m_OverlaysVisible = true;
VisualElement m_RootVisualElement;
internal EditorWindow containerWindow { get; set; }
internal FloatingOverlayContainer floatingContainer => m_FloatingOverlayContainer ??= new FloatingOverlayContainer {canvas = this};
FloatingOverlayContainer m_FloatingOverlayContainer;
Overlay m_HoveredOverlay;
internal VisualElement rootVisualElement => m_RootVisualElement ??= CreateRoot();
internal Overlay hoveredOverlay => m_HoveredOverlay;
OverlayContainer hoveredOverlayContainer { get; set; }
OverlayContainer defaultContainer { get; set; }
OverlayContainer defaultToolbarContainer { get; set; }
internal OverlayDockArea dockArea { get; private set; }
List<OverlayContainer> m_Containers;
internal IEnumerable<OverlayContainer> containers => m_Containers;
readonly Dictionary<VisualElement, Overlay> m_OverlaysByVE = new Dictionary<VisualElement, Overlay>();
public IEnumerable<Overlay> overlays => m_Overlays.AsReadOnly();
internal IEnumerable<Overlay> transientOverlays => m_TransientOverlays;
OverlayPopup m_PopupOverlay;
VisualElement m_WindowRoot;
internal VisualElement windowRoot => m_WindowRoot;
internal Action afterOverlaysInitialized;
internal event Action<bool> overlaysEnabledChanged;
internal event Action overlayListChanged;
public bool overlaysEnabled
{
get => m_Containers.All(x => x.style.display != DisplayStyle.None);
set
{
m_OverlaysVisible = value;
if (value == overlaysEnabled)
return;
foreach (var container in m_Containers)
container.style.display = value ? DisplayStyle.Flex : DisplayStyle.None;
overlaysEnabledChanged?.Invoke(value);
}
}
internal OverlayCanvas() { }
VisualElement CreateRoot()
{
var ve = new VisualElement();
ve.AddToClassList(ussClassName);
StyleSheet sheet;
sheet = EditorGUIUtility.Load(k_StyleCommon) as StyleSheet;
ve.styleSheets.Add(sheet);
if (EditorGUIUtility.isProSkin)
sheet = EditorGUIUtility.Load(k_StyleDark) as StyleSheet;
else
sheet = EditorGUIUtility.Load(k_StyleLight) as StyleSheet;
ve.styleSheets.Add(sheet);
if (s_TreeAsset == null)
s_TreeAsset = EditorGUIUtility.Load(k_UxmlPath) as VisualTreeAsset;
if (s_TreeAsset != null)
s_TreeAsset.CloneTree(ve);
if (s_DropZoneTreeAsset == null)
s_DropZoneTreeAsset = EditorGUIUtility.Load(k_UxmlPathDropZone) as VisualTreeAsset;
ve.name = ussClassName;
ve.style.flexGrow = 1;
ve.Add(floatingContainer);
floatingContainer.AddToClassList(k_FloatingContainer);
floatingContainer.name = "Floating";
m_Containers = ve.Query<OverlayContainer>().ToList();
foreach (var container in m_Containers)
{
container.RegisterCallback<MouseEnterEvent>(OnMouseEnterOverlayContainer);
if (container.ClassListContains(k_DefaultContainer))
{
if (container.ClassListContains(k_ToolbarArea))
defaultToolbarContainer = container;
else
defaultContainer = container;
}
var data = GetContainerData(container.name);
if (container is ToolbarOverlayContainer toolbar)
toolbar.scrollOffset = data.scrollOffset;
}
SetPickingMode(ve, PickingMode.Ignore);
ve.RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel);
ve.RegisterCallback<DetachFromPanelEvent>(OnDetachedFromPanel);
m_WindowRoot = ve.Q("overlay-window-root");
ve.Add(dockArea = new OverlayDockArea(this));
m_WindowRoot.RegisterCallback<GeometryChangedEvent>((evt) =>
{
var worldPos = m_WindowRoot.LocalToWorld(evt.newRect.position);
dockArea.transform.position = ve.WorldToLocal(worldPos);
dockArea.style.width = evt.newRect.width;
dockArea.style.height = evt.newRect.height;
});
overlaysEnabled = m_OverlaysVisible;
return ve;
}
void SetPickingMode(VisualElement element, PickingMode mode)
{
element.pickingMode = mode;
foreach (var child in element.Children())
SetPickingMode(child, mode);
}
void OnMouseEnterOverlayContainer(MouseEnterEvent evt)
{
var overlayContainer = evt.target as OverlayContainer;
hoveredOverlayContainer = overlayContainer;
}
void OnAttachedToPanel(AttachToPanelEvent evt)
{
//this is used to clamp overlays to floating container bounds.
floatingContainer.RegisterCallback<GeometryChangedEvent>(GeometryChanged);
rootVisualElement.RegisterCallback<MouseEnterEvent>(OnMouseEnter);
rootVisualElement.RegisterCallback<MouseLeaveEvent>(OnMouseLeave);
}
void OnDetachedFromPanel(DetachFromPanelEvent evt)
{
floatingContainer.UnregisterCallback<GeometryChangedEvent>(GeometryChanged);
rootVisualElement.UnregisterCallback<MouseEnterEvent>(OnMouseEnter);
rootVisualElement.UnregisterCallback<MouseLeaveEvent>(OnMouseLeave);
}
internal void OnContainerWindowDisabled()
{
foreach (var overlay in m_Overlays)
overlay.OnWillBeDestroyed();
}
void OnMouseEnter(MouseEnterEvent evt)
{
m_MouseInCurrentCanvas = true;
}
void OnMouseLeave(MouseLeaveEvent evt)
{
m_MouseInCurrentCanvas = false;
}
internal Rect ClampToOverlayWindow(Rect rect)
{
return ClampRectToBounds(rootVisualElement.localBound, rect);
}
// ensure that a minimum area of a rect is within boundary
internal static Rect ClampRectToBounds(Rect boundary, Rect rectToClamp)
{
if (rectToClamp.x > boundary.xMax - k_OverlayMinVisibleArea)
rectToClamp.x = boundary.xMax - k_OverlayMinVisibleArea;
if (rectToClamp.xMax < boundary.xMin + k_OverlayMinVisibleArea)
rectToClamp.x = (boundary.xMin + k_OverlayMinVisibleArea) - rectToClamp.width;
if (rectToClamp.y > boundary.yMax - k_OverlayMinVisibleArea)
rectToClamp.y = boundary.yMax - k_OverlayMinVisibleArea;
if (rectToClamp.y < boundary.yMin)
rectToClamp.y = boundary.yMin;
return rectToClamp;
}
// clamp all overlays to root visual element's new bounds
void GeometryChanged(GeometryChangedEvent evt)
{
if (!overlaysEnabled)
return;
foreach (var overlay in m_Overlays)
{
if (overlay == null)
continue;
using (new Overlay.LockedAnchor(overlay))
overlay.floatingPosition = overlay.floatingPosition; //force an update of the floating position
overlay.UpdateAbsolutePosition();
//Register the geometrychanged callback to the overlay if it was not registered before,
//this is not doing anything if it has already been registered
overlay.rootVisualElement.RegisterCallback<GeometryChangedEvent>(overlay.OnGeometryChanged);
}
}
void OnMouseLeaveOverlay(MouseLeaveEvent evt)
{
m_HoveredOverlay = null;
}
void OnMouseEnterOverlay(MouseEnterEvent evt)
{
var overlay = evt.target as VisualElement;
if (overlay != null && overlay.ClassListContains(Overlay.ussClassName))
m_HoveredOverlay = m_OverlaysByVE[overlay];
}
internal void HideHoveredOverlay()
{
if (hoveredOverlay != null && hoveredOverlay.userControlledVisibility)
hoveredOverlay.displayed = false;
}
internal bool HasTransientOverlays()
{
return m_TransientOverlays.Count > 0;
}
internal bool IsTransient(Overlay overlay) => m_TransientOverlays.Contains(overlay);
internal Func<OverlayUtilities.OverlayEditorWindowAssociation, bool> filterOverlays;
internal void Initialize(EditorWindow window)
{
Profiler.BeginSample("OverlayCanvas.Initialize");
containerWindow = window;
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
List<Type> overlayTypes = OverlayUtilities.GetOverlaysForType(window.GetType(), filterOverlays);
// init all overlays
foreach (var overlayType in overlayTypes)
AddOverlay(OverlayUtilities.CreateOverlay(overlayType));
if (m_SaveData == null || m_SaveData.Count < 1)
{
var preset = OverlayPresetManager.GetDefaultPreset(window.GetType());
if(preset != null && preset.saveData != null)
m_SaveData = new List<SaveData>(preset.saveData);
}
RestoreOverlays();
Profiler.EndSample();
}
void OnBeforeAssemblyReload()
{
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
foreach (var overlay in m_Overlays)
overlay.rootVisualElement.UnregisterCallback<GeometryChangedEvent>(overlay.OnGeometryChanged);
}
void WriteOrReplaceSaveData(Overlay overlay, int containerIndex = -1)
{
var saveData = new SaveData(overlay, containerIndex);
int existing = m_SaveData.FindIndex(x => x.id == overlay.id);
if (existing < 0)
m_SaveData.Add(saveData);
else
m_SaveData[existing] = saveData;
}
public void OnBeforeSerialize()
{
if (m_Containers == null)
return;
foreach (var container in m_Containers)
{
if (container != null)
{
var before = container.GetSection(OverlayContainerSection.BeforeSpacer);
var after = container.GetSection(OverlayContainerSection.AfterSpacer);
for (int i = 0, c = before.Count; i < c; ++i)
{
if (!before[i].dontSaveInLayout)
WriteOrReplaceSaveData(before[i], i);
}
for (int i = 0, c = after.Count; i < c; ++i)
{
if (!after[i].dontSaveInLayout)
WriteOrReplaceSaveData(after[i], i);
}
var data = GetContainerData(container.name);
if (container is ToolbarOverlayContainer toolbar)
data.scrollOffset = toolbar.scrollOffset;
}
}
}
public void OnAfterDeserialize() {}
// used by tests
internal void CopySaveData(out SaveData[] saveData)
{
// Force a save of the current data
OnBeforeSerialize();
saveData = m_SaveData.ToArray();
for (int i = 0; i < saveData.Length; ++i)
saveData[i] = new SaveData(saveData[i]);
}
internal void ApplyPreset(OverlayPreset preset)
{
if (!preset.CanApplyToWindow(containerWindow.GetType()))
{
Debug.LogError($"Cannot apply preset for type {preset.targetWindowType} to canvas of type " +
$"{containerWindow.GetType()}");
return;
}
m_LastAppliedPresetName = preset.name;
ApplySaveData(preset.saveData);
}
internal void ApplySaveData(SaveData[] saveData)
{
m_SaveData = new List<SaveData>(saveData);
RestoreOverlays();
}
internal void Move(Overlay overlay, DockZone zone, DockPosition position = DockPosition.Bottom)
{
var container = GetDockZoneContainer(zone);
if (position == DockPosition.Bottom)
overlay.DockAt(container, OverlayContainerSection.AfterSpacer);
else
overlay.DockAt(container, OverlayContainerSection.BeforeSpacer);
}
internal void Rebuild()
{
OnBeforeSerialize();
RestoreOverlays();
}
// Overlays added to the canvas through this method are considered "temporary" and will be shown in separate
// category in the menu. Persistent overlays (i.e., overlays registered through OverlayAttribute) are not
// created using this method.
public void Add(Overlay overlay)
{
if(m_Overlays.Contains(overlay))
return;
overlay.canvas?.Remove(overlay);
AddOverlay(overlay, true);
RestoreOverlay(overlay);
}
public bool Remove(Overlay overlay)
{
if (!m_Overlays.Remove(overlay))
return false;
m_TransientOverlays.Remove(overlay);
overlay.OnWillBeDestroyed();
WriteOrReplaceSaveData(overlay);
overlay.container?.RemoveOverlay(overlay);
overlay.canvas = null;
var root = overlay.rootVisualElement;
m_OverlaysByVE.Remove(root);
root.UnregisterCallback<MouseEnterEvent>(OnMouseEnterOverlay);
root.UnregisterCallback<MouseLeaveEvent>(OnMouseLeaveOverlay);
root.RemoveFromHierarchy();
overlayListChanged?.Invoke();
return true;
}
public void ShowPopup<T>() where T : Overlay, new()
{
if (ClosePopupOverlay())
return;
var popup = OverlayPopup.CreateAtCanvasCenter(this, CreateOverlayForPopup<T>());
SetActiveOverlayPopup(popup);
}
public void ShowPopupAtMouse<T>() where T : Overlay, new()
{
if (!m_MouseInCurrentCanvas)
{
ClosePopupOverlay();
return;
}
ShowPopup<T>(PointerDeviceState.GetPointerPosition(PointerId.mousePointerId, ContextType.Editor));
}
public void ShowPopup<T>(Vector2 position) where T : Overlay, new()
{
if (ClosePopupOverlay())
return;
var popup = OverlayPopup.CreateAtPosition(this, CreateOverlayForPopup<T>(), position);
SetActiveOverlayPopup(popup);
}
T CreateOverlayForPopup<T>() where T : Overlay, new()
{
var overlay = new T();
var overlayName = OverlayUtilities.GetDisplayNameFromAttribute(typeof(T));
if (overlayName == string.Empty)
overlayName = ObjectNames.NicifyVariableName(typeof(T).Name);
// OnCreated must be invoked before contents are requested for the first time
overlay.canvas = this;
overlay.isPopup = true;
overlay.OnCreated();
overlay.displayed = false;
overlay.displayName = overlayName;
return overlay;
}
void SetActiveOverlayPopup(OverlayPopup popup)
{
m_PopupOverlay = popup;
m_PopupOverlay.RegisterCallback<FocusOutEvent>(evt =>
{
if (evt.relatedTarget is VisualElement target && (m_PopupOverlay == target || m_PopupOverlay.Contains(target)))
return;
// When the new focus is an embedded IMGUIContainer or popup window, give focus back to the modal
// popup so that the next focus out event has the opportunity to close the element.
if (evt.relatedTarget == null && m_PopupOverlay.containsCursor)
EditorApplication.delayCall += m_PopupOverlay.Focus;
else
{
ClosePopupOverlay();
popup.overlay.OnWillBeDestroyed();
}
});
rootVisualElement.Add(m_PopupOverlay);
m_PopupOverlay.Focus();
}
bool ClosePopupOverlay()
{
if (m_PopupOverlay == null)
return false;
m_PopupOverlay.RemoveFromHierarchy();
m_PopupOverlay = null;
return true;
}
// AddOverlay just registers the Overlay with Canvas. It does not init save data or add to a valid container.
void AddOverlay(Overlay overlay, bool transient = false)
{
// Don't show an error when attempting to add a null overlay. This means that a persistent Overlay type was
// removed from a project, or moved to a transient overlay. In either case, the user can't do anything
// meaningful with this information.
if (overlay == null)
return;
if(!OverlayUtilities.EnsureValidId(m_Overlays, overlay))
{
Debug.LogError($"An overlay with id \"{overlay.id}\" was already registered to window " +
$"({containerWindow.titleContent.text}).");
return;
}
overlay.canvas = this;
m_Overlays.Add(overlay);
if (transient)
m_TransientOverlays.Add(overlay);
m_OverlaysByVE[overlay.rootVisualElement] = overlay;
overlay.rootVisualElement.RegisterCallback<MouseEnterEvent>(OnMouseEnterOverlay);
overlay.rootVisualElement.RegisterCallback<MouseLeaveEvent>(OnMouseLeaveOverlay);
// OnCreated must be invoked before contents are requested for the first time
overlay.OnCreated();
overlayListChanged?.Invoke();
}
internal bool TryGetOverlay(string id, out Overlay overlay)
{
overlay = m_Overlays.FirstOrDefault(x => x.id == id);
return overlay != null;
}
internal bool TryGetOverlay<T>(string id, out T overlay) where T : Overlay
{
overlay = m_Overlays.FirstOrDefault(x => x is T && x.id == id) as T;
return overlay != null;
}
// GetOrCreateOverlay is used to instantiate Overlays. Do not use this method when deserializing and batch
// constructing Overlays, instead use AddOverlay/RestoreOverlays.
internal T GetOrCreateOverlay<T>(string id = null) where T : Overlay, new()
{
var attrib = OverlayUtilities.GetAttribute(containerWindow.GetType(), typeof(T));
if (string.IsNullOrEmpty(id))
id = attrib.id;
if(TryGetOverlay(id, out T overlay))
return overlay;
overlay = new T();
overlay.Initialize(id, attrib.ussName, attrib.displayName, attrib.defaultSize, attrib.minSize, attrib.maxSize);
if (overlay is LegacyOverlay legacy)
legacy.dontSaveInLayout = true;
AddOverlay(overlay);
RestoreOverlay(overlay);
return overlay;
}
// used by tests
internal SaveData FindSaveData(Overlay overlay)
{
var data = m_SaveData.FirstOrDefault(x => x.id == overlay.id);
if (data == null)
{
data = defaultSaveData;
var attrib = overlay.GetType().GetCustomAttribute<OverlayAttribute>();
if (attrib != null)
{
data.containerId = k_DockZoneContainerIDs[(int)attrib.defaultDockZone];
data.index = attrib.defaultDockIndex;
data.dockPosition = attrib.defaultDockPosition;
data.displayed = attrib.defaultDisplay;
overlay.layout = attrib.defaultLayout;
// also apply to obsolete SaveData fields for backwards compatibility (ie, there is no
// SaveData.contents but we still want layout and size attribute values to be forwarded)
#pragma warning disable 612
data.layout = attrib.defaultLayout;
data.floating = attrib.defaultDockZone == DockZone.Floating;
#pragma warning restore 612
}
}
return data;
}
public void ResetOverlay(Overlay overlay)
{
overlay.sizeOverridden = false;
var attrib = overlay.GetType().GetCustomAttribute<OverlayAttribute>();
overlay.Reset(attrib);
var container = GetDockZoneContainer(attrib.defaultDockZone);
if (attrib.defaultDockPosition == DockPosition.Top)
{
var index = Mathf.Min(attrib.defaultDockIndex, container.GetSectionCount(OverlayContainerSection.BeforeSpacer));
overlay.DockAt(container, OverlayContainerSection.BeforeSpacer, index);
}
else if (attrib.defaultDockPosition == DockPosition.Bottom)
{
var index = Mathf.Min(attrib.defaultDockIndex, container.GetSectionCount(OverlayContainerSection.AfterSpacer));
overlay.DockAt(container, OverlayContainerSection.AfterSpacer, index);
}
else
throw new Exception("data.dockPosition is not Top or Bottom, did someone add a new one?");
if(overlay.floating)
overlay.Undock();
if (overlay.displayed != attrib.defaultDisplay)
{
// start from "not shown" state so that Overlay.displayedChanged is called
overlay.rootVisualElement.style.display = DisplayStyle.None;
overlay.displayed = attrib.defaultDisplay;
}
else
overlay.RebuildContent();
overlay.UpdateAbsolutePosition();
}
public void RestoreOverlay(Overlay overlay, SaveData data = null)
{
if(data == null)
data = FindSaveData(overlay);
EditorJsonUtility.FromJsonOverwrite(data.contents, overlay);
#pragma warning disable 618
if(string.IsNullOrEmpty(data.contents))
overlay.ApplySaveData(data);
#pragma warning restore 618
var container = m_Containers.FirstOrDefault(x => data.containerId == x.name);
// Overlays were implemented with the idea that they are always associated with an OverlayContainer. While
// this doesn't really need to be true (floating Overlays don't need a Container), the code isn't capable
// of handling that case. So if a valid container can't be found from the serialized data, we just add it
// to a default container.
if(container == null)
container = overlay is ToolbarOverlay ? defaultToolbarContainer : defaultContainer;
// Overlays are sorted by their index in containers so we can directly add them to top or bottom without
// thinking of order
if (data.dockPosition == DockPosition.Top)
overlay.DockAt(container, OverlayContainerSection.BeforeSpacer, container.GetSectionCount(OverlayContainerSection.BeforeSpacer));
else if (data.dockPosition == DockPosition.Bottom)
overlay.DockAt(container, OverlayContainerSection.AfterSpacer, container.GetSectionCount(OverlayContainerSection.AfterSpacer));
else
throw new Exception("data.dockPosition is not Top or Bottom, did someone add a new one?");
if(overlay.floating)
overlay.Undock();
// when restoring an overlay from serialized state, always start from "not shown" state so that
// Overlay.displayedChanged is called
overlay.rootVisualElement.style.display = DisplayStyle.None;
if(overlay.displayed != data.displayed)
overlay.displayed = data.displayed;
else
overlay.RebuildContent();
overlay.UpdateAbsolutePosition();
}
void RestoreOverlays()
{
if (m_Containers == null)
return;
// Clear OverlayContainer instances and set Overlay.displayed to false. RestoreOverlay expects that Overlay
// is not present in VisualElement hierarchy.
foreach (var overlay in overlays)
{
overlay.displayed = false;
overlay.container?.RemoveOverlay(overlay);
}
// Three steps to reinitialize a canvas:
// 1. Find and associate all Overlays with SaveData (using default SaveData if necessary)
// 2. Sort in ascending order by SaveData.index
// 3. Apply SaveData, insert Overlay in Container
var ordered = new List<Tuple<SaveData, Overlay>>();
foreach(var o in overlays)
ordered.Add(new Tuple<SaveData, Overlay>(FindSaveData(o), o));
foreach (var o in ordered.OrderBy(x => x.Item1.index))
RestoreOverlay(o.Item2, o.Item1);
afterOverlaysInitialized?.Invoke();
}
ContainerData GetContainerData(string containerId)
{
foreach (var data in m_ContainerData)
if (data.containerId == containerId)
return data;
var newData = new ContainerData
{
containerId = containerId,
scrollOffset = 0
};
m_ContainerData.Add(newData);
return newData;
}
}
}
| UnityCsReference/Editor/Mono/Overlays/OverlayCanvas.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayCanvas.cs",
"repo_id": "UnityCsReference",
"token_count": 16991
} | 326 |
// Unity 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.UIElements;
using Cursor = UnityEngine.UIElements.Cursor;
namespace UnityEditor.Overlays
{
class OverlayResizerGroup : VisualElement
{
const float k_CornerSize = 8;
const float k_SideSize = 6;
const float k_MinDistanceFromEdge = 10;
[Flags]
enum Direction
{
Left = 1 << 0,
Bottom = 1 << 1,
Top = 1 << 2,
Right = 1 << 3,
TopLeft = Top | Left,
TopRight = Top | Right,
BottomLeft = Bottom | Left,
BottomRight = Bottom | Right,
}
class OverlayResizer : VisualElement
{
readonly Direction m_Direction;
readonly Overlay m_Overlay;
readonly bool m_ModifyPosition;
Vector2 m_OriginalMousePosition;
Rect m_OriginalRect;
Rect m_ContainerRect;
Vector2 m_MinSize;
Vector2 m_MaxSize;
bool m_Active;
public OverlayResizer(Overlay overlay, Direction direction)
{
m_Overlay = overlay;
m_Direction = direction;
style.position = Position.Absolute;
bool hasLeft = HasDirection(Direction.Left);
bool hasRight = HasDirection(Direction.Right);
bool hasTop = HasDirection(Direction.Top);
bool hasBottom = HasDirection(Direction.Bottom);
bool isCorner = HasMultipleDirections();
var size = isCorner ? k_CornerSize : k_SideSize;
if (hasLeft) style.left = -size * .5f;
if (hasRight) style.right = -size * .5f;
if (hasTop) style.top = -size * .5f;
if (hasBottom) style.bottom = -size * .5f;
style.width = hasLeft || hasRight ? size : new Length(100, LengthUnit.Percent);
style.height = hasTop || hasBottom ? size : new Length(100, LengthUnit.Percent);
m_ModifyPosition = HasDirection(Direction.Left) || HasDirection(Direction.Top);
style.cursor = new Cursor { defaultCursorId = (int)GetCursor(direction) };
RegisterCallback<MouseDownEvent>(OnMouseDown);
RegisterCallback<MouseMoveEvent>(OnMouseMove);
RegisterCallback<MouseUpEvent>(OnMouseUp);
}
void OnMouseDown(MouseDownEvent evt)
{
var container = m_Overlay.rootVisualElement.GetFirstAncestorOfType<OverlayContainer>();
var overlayPosition = m_Overlay.rootVisualElement.layout.position;
if (container != null)
overlayPosition = m_Overlay.rootVisualElement.parent.ChangeCoordinatesTo(container, overlayPosition);
m_OriginalRect = new Rect(
m_Overlay.floating ? m_Overlay.floatingPosition : overlayPosition,
m_Overlay.size);
m_ContainerRect = container?.rect ?? new Rect(float.NegativeInfinity,float.NegativeInfinity,float.PositiveInfinity,float.PositiveInfinity);
m_OriginalMousePosition = evt.mousePosition;
m_MaxSize = m_Overlay.maxSize;
m_MinSize = m_Overlay.minSize;
this.CaptureMouse();
evt.StopPropagation();
m_Active = true;
}
void OnMouseMove(MouseMoveEvent evt)
{
if (m_Active)
{
var translation = evt.mousePosition - m_OriginalMousePosition;
var rect = ResizeRect(m_OriginalRect, translation);
m_Overlay.size = rect.size;
if (m_ModifyPosition && m_Overlay.floating)
m_Overlay.floatingPosition = rect.position;
evt.StopPropagation();
}
}
void OnMouseUp(MouseUpEvent evt)
{
if (m_Active)
{
evt.StopPropagation();
this.ReleaseMouse();
m_Active = false;
}
}
Rect ResizeRect(Rect rect, Vector2 delta)
{
delta = ClampDeltaToMinMax(delta, rect);
if (HasDirection(Direction.Left))
rect.xMin = Mathf.Max(m_ContainerRect.xMin, rect.xMin + delta.x);
else if (HasDirection(Direction.Right))
rect.xMax = Mathf.Min(m_ContainerRect.xMax, rect.xMax + delta.x);
if (HasDirection(Direction.Top))
rect.yMin = Mathf.Max(m_ContainerRect.yMin, rect.yMin + delta.y);
else if (HasDirection(Direction.Bottom))
rect.yMax = Mathf.Min(m_ContainerRect.yMax, rect.yMax + delta.y);
return rect;
}
Vector2 ClampDeltaToMinMax(Vector2 delta, Rect rect)
{
if (HasDirection(Direction.Left))
delta.x = rect.width - Mathf.Clamp(rect.width - delta.x, m_MinSize.x, m_MaxSize.x);
else if (HasDirection(Direction.Right))
delta.x = Mathf.Clamp(rect.width + delta.x, m_MinSize.x, m_MaxSize.x) - rect.width;
if (HasDirection(Direction.Top))
delta.y = rect.height - Mathf.Clamp(rect.height - delta.y, m_MinSize.y, m_MaxSize.y);
else if (HasDirection(Direction.Bottom))
delta.y = Mathf.Clamp(rect.height + delta.y, m_MinSize.y, m_MaxSize.y) - rect.height;
return delta;
}
static MouseCursor GetCursor(Direction direction)
{
MouseCursor cursorStyle = MouseCursor.Arrow;
switch (direction)
{
case Direction.TopLeft:
case Direction.BottomRight:
cursorStyle = MouseCursor.ResizeUpLeft;
break;
case Direction.TopRight:
case Direction.BottomLeft:
cursorStyle = MouseCursor.ResizeUpRight;
break;
case Direction.Left:
case Direction.Right:
cursorStyle = MouseCursor.ResizeHorizontal;
break;
case Direction.Top:
case Direction.Bottom:
cursorStyle = MouseCursor.ResizeVertical;
break;
}
return cursorStyle;
}
public bool HasDirection(Direction target)
{
return (m_Direction & target) == target;
}
public bool HasMultipleDirections()
{
return (m_Direction & (m_Direction - 1)) != 0;
}
}
readonly Overlay m_Overlay;
readonly OverlayResizer[] m_Resizers;
public OverlayResizerGroup(Overlay overlay)
{
this.StretchToParentSize();
pickingMode = PickingMode.Ignore;
m_Resizers = new []
{
new OverlayResizer(overlay, Direction.Top) { name = "ResizerTop" },
new OverlayResizer(overlay, Direction.Bottom) { name = "ResizerBottom" },
new OverlayResizer(overlay, Direction.Left) { name = "ResizerLeft" },
new OverlayResizer(overlay, Direction.Right) { name = "ResizerRight" },
new OverlayResizer(overlay, Direction.TopLeft) { name = "ResizerTopLeft" },
new OverlayResizer(overlay, Direction.TopRight) { name = "ResizerTopRight" },
new OverlayResizer(overlay, Direction.BottomLeft) { name = "ResizerBottomLeft" },
new OverlayResizer(overlay, Direction.BottomRight) { name = "ResizerBottomRight" },
};
m_Overlay = overlay;
foreach (var resizer in m_Resizers)
Add(resizer);
overlay.containerChanged += OnOverlayContainerChanged;
overlay.layoutChanged += OnOverlayLayoutChanged;
overlay.floatingPositionChanged += OnOverlayPositionChanged;
overlay.collapsedChanged += OnOverlayCollaspedChanged;
m_Overlay.rootVisualElement.RegisterCallback<GeometryChangedEvent>(OnOverlayGeometryChanged);
UpdateResizerVisibility();
}
void OnOverlayLayoutChanged(Layout layout)
{
UpdateResizerVisibility();
}
void OnOverlayContainerChanged(OverlayContainer container)
{
UpdateResizerVisibility();
}
void OnOverlayGeometryChanged(GeometryChangedEvent evt)
{
UpdateResizerVisibility();
}
void OnOverlayPositionChanged(Vector3 position)
{
UpdateResizerVisibility();
}
void OnOverlayCollaspedChanged(bool collapsed)
{
UpdateResizerVisibility();
}
bool ContainerCanShowResizer(OverlayResizer resizer)
{
var container = m_Overlay.container;
if (container == null)
return false;
if (container is FloatingOverlayContainer)
return true;
if (container is ToolbarOverlayContainer)
return false;
var alignment = container.resolvedStyle.alignItems;
bool hide = false;
// Check the opposite direction. If the content is align to one side, hide resizer on that side
switch (alignment)
{
case Align.FlexStart:
hide |= resizer.HasDirection(container.isHorizontal ? Direction.Top : Direction.Left);
break;
case Align.FlexEnd:
hide |= resizer.HasDirection(container.isHorizontal ? Direction.Bottom : Direction.Right);
break;
}
return !hide;
}
void UpdateResizerVisibility()
{
bool globalHide = !m_Overlay.IsResizable();
foreach (var resizer in m_Resizers)
{
bool hide = globalHide || !ContainerCanShowResizer(resizer);
if (resizer.HasMultipleDirections())
{
hide |= Mathf.Approximately(m_Overlay.minSize.x, m_Overlay.maxSize.x);
hide |= Mathf.Approximately(m_Overlay.minSize.y, m_Overlay.maxSize.y);
}
else
{
if (resizer.HasDirection(Direction.Left) || resizer.HasDirection(Direction.Right))
hide |= Mathf.Approximately(m_Overlay.minSize.x, m_Overlay.maxSize.x);
if (resizer.HasDirection(Direction.Top) || resizer.HasDirection(Direction.Bottom))
hide |= Mathf.Approximately(m_Overlay.minSize.y, m_Overlay.maxSize.y);
}
if (m_Overlay.canvas != null)
{
var canvas = m_Overlay.canvas.rootVisualElement;
var canvasRect = canvas.rect;
var overlayRect = canvas.WorldToLocal(m_Overlay.rootVisualElement.worldBound);
if (resizer.HasDirection(Direction.Left))
hide |= overlayRect.xMin <= k_MinDistanceFromEdge;
if (resizer.HasDirection(Direction.Right))
hide |= overlayRect.xMax >= canvasRect.xMax - k_MinDistanceFromEdge;
if (resizer.HasDirection(Direction.Top))
hide |= overlayRect.yMin <= k_MinDistanceFromEdge;
if (resizer.HasDirection(Direction.Bottom))
hide |= overlayRect.yMax >= canvasRect.yMax - k_MinDistanceFromEdge;
}
resizer.style.display = hide ? DisplayStyle.None : DisplayStyle.Flex;
}
}
}
}
| UnityCsReference/Editor/Mono/Overlays/OverlayResizer.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayResizer.cs",
"repo_id": "UnityCsReference",
"token_count": 6298
} | 327 |
// Unity 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.Profiling;
using UnityEngine.Networking.PlayerConnection;
using UnityEditor;
using UnityEditorInternal;
using UnityEditorInternal.FrameDebuggerInternal;
using UnityEditor.Networking.PlayerConnection;
namespace UnityEditorInternal.FrameDebuggerInternal
{
internal class FrameDebuggerToolbarView
{
// Non-Serialized
[NonSerialized] private int m_PrevEventsLimit = 0;
[NonSerialized] private int m_PrevEventsCount = 0;
// Returns true if repaint is needed
public bool DrawToolbar(FrameDebuggerWindow frameDebugger, IConnectionState m_AttachToPlayerState)
{
Profiler.BeginSample("DrawToolbar");
GUILayout.BeginHorizontal(EditorStyles.toolbar);
DrawEnableDisableButton(frameDebugger, m_AttachToPlayerState, out bool needsRepaint);
DrawConnectionDropdown(frameDebugger, m_AttachToPlayerState, out bool isEnabled);
GUI.enabled = isEnabled;
DrawEventLimitSlider(frameDebugger, out int newLimit);
DrawPrevNextButtons(frameDebugger, ref newLimit);
GUILayout.EndHorizontal();
Profiler.EndSample();
return needsRepaint;
}
private void DrawEnableDisableButton(FrameDebuggerWindow frameDebuggerWindow, IConnectionState m_AttachToPlayerState, out bool needsRepaint)
{
needsRepaint = false;
EditorGUI.BeginChangeCheck();
bool wasEnabled = GUI.enabled;
GUI.enabled = m_AttachToPlayerState.connectedToTarget != ConnectionTarget.Editor || FrameDebuggerUtility.locallySupported;
GUIContent button = (FrameDebugger.enabled) ? FrameDebuggerStyles.TopToolbar.s_RecordButtonDisable : FrameDebuggerStyles.TopToolbar.s_RecordButtonEnable;
GUILayout.Toggle(FrameDebugger.enabled, button, EditorStyles.toolbarButtonLeft, GUILayout.MinWidth(80));
GUI.enabled = wasEnabled;
if (EditorGUI.EndChangeCheck())
{
frameDebuggerWindow.ToggleFrameDebuggerEnabled();
needsRepaint = true;
}
}
private void DrawConnectionDropdown(FrameDebuggerWindow frameDebuggerWindow, IConnectionState m_AttachToPlayerState, out bool isEnabled)
{
PlayerConnectionGUILayout.ConnectionTargetSelectionDropdown(m_AttachToPlayerState, EditorStyles.toolbarDropDown);
isEnabled = FrameDebugger.enabled;
if (isEnabled && ProfilerDriver.connectedProfiler != FrameDebuggerUtility.GetRemotePlayerGUID())
{
// Switch from local to remote debugger or vice versa
frameDebuggerWindow.OnConnectedProfilerChange();
}
}
private void DrawEventLimitSlider(FrameDebuggerWindow frameDebuggerWindow, out int newLimit)
{
newLimit = 0;
EditorGUI.BeginChangeCheck();
bool wasEnabled = GUI.enabled;
GUI.enabled = FrameDebuggerUtility.count > 1;
// We need to use Slider instead of IntSlider due to a bug where the invisible label makes
// the mouse cursor different when hovering over the leftmost 10-20% of the slider (UUM-17184)
// We add 0.5 to make it switch between frames like when we use a IntSlider.
newLimit = (int) (0.5f + EditorGUILayout.Slider(FrameDebuggerUtility.limit, 1, FrameDebuggerUtility.count));
GUI.enabled = wasEnabled;
if (EditorGUI.EndChangeCheck())
frameDebuggerWindow.ChangeFrameEventLimit(newLimit);
}
private void DrawPrevNextButtons(FrameDebuggerWindow frameDebuggerWindow, ref int newLimit)
{
bool wasEnabled = GUI.enabled;
GUI.enabled = newLimit > 1;
if (GUILayout.Button(FrameDebuggerStyles.TopToolbar.s_PrevFrame, EditorStyles.toolbarButton))
frameDebuggerWindow.ChangeFrameEventLimit(newLimit - 1);
GUI.enabled = newLimit < FrameDebuggerUtility.count;
if (GUILayout.Button(FrameDebuggerStyles.TopToolbar.s_NextFrame, EditorStyles.toolbarButtonRight))
frameDebuggerWindow.ChangeFrameEventLimit(newLimit + 1);
// If we had last event selected, and something changed in the scene so that
// number of events is different - then try to keep the last event selected.
if (m_PrevEventsLimit == m_PrevEventsCount)
if (FrameDebuggerUtility.count != m_PrevEventsCount && FrameDebuggerUtility.limit == m_PrevEventsLimit)
frameDebuggerWindow.ChangeFrameEventLimit(FrameDebuggerUtility.count);
// The number of events has changed...
if (FrameDebuggerUtility.count != m_PrevEventsCount)
{
frameDebuggerWindow.ReselectItemOnCountChange();
}
m_PrevEventsLimit = FrameDebuggerUtility.limit;
m_PrevEventsCount = FrameDebuggerUtility.count;
GUI.enabled = wasEnabled;
}
}
}
| UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerToolbarView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerToolbarView.cs",
"repo_id": "UnityCsReference",
"token_count": 2086
} | 328 |
// Unity 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 System.Text;
using UnityEditor.Build;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEditor.Modules;
namespace UnityEditor
{
// Resolution dialog setting
[Obsolete("The Display Resolution Dialog has been removed.", false)]
public enum ResolutionDialogSetting
{
// Never show the resolutions dialog.
Disabled = 0,
// Show the resolutions dialog on first launch.
Enabled = 1,
// Hide the resolutions dialog on first launch.
HiddenByDefault = 2,
}
public enum ScriptingImplementation
{
Mono2x = 0,
IL2CPP = 1,
WinRTDotNET = 2,
[Obsolete("CoreCLR support is still a work in progress and is disabled for now.")] // Hide from intellisense while CORECLR_FIXME
[EditorBrowsable(EditorBrowsableState.Never)]
CoreCLR = 3,
}
// Must be in sync with Il2CppCompilerConfiguration enum in SerializationMetaFlags.h
public enum Il2CppCompilerConfiguration
{
Debug = 0,
Release = 1,
Master = 2,
}
// Must be in sync with Il2CppStacktraceInformation enum in SerializationMetaFlags.h
public enum Il2CppStacktraceInformation
{
MethodOnly = 0,
MethodFileLineNumber = 1,
}
// Mac fullscreen mode
public enum MacFullscreenMode
{
[Obsolete("Capture Display mode is deprecated, Use FullscreenWindow instead")]
CaptureDisplay = 0,
// Fullscreen window.
FullscreenWindow = 1,
// Fullscreen window with Dock and Menu bar.
FullscreenWindowWithDockAndMenuBar = 2,
}
[Obsolete("D3D9 support has been removed")]
public enum D3D9FullscreenMode
{
[Obsolete("D3D9 support has been removed")]
ExclusiveMode = 0,
[Obsolete("D3D9 support has been removed")]
FullscreenWindow = 1,
}
// Direct3D 11 fullscreen mode
public enum D3D11FullscreenMode
{
// Exclusive mode.
ExclusiveMode = 0,
// Fullscreen window.
FullscreenWindow = 1,
}
// Must be in sync with StereoRenderingPath enum in GfxDeviceTypes.h
public enum StereoRenderingPath
{
// Slow multi pass method ( For reference only )
MultiPass = 0,
// Single pass stereo rendering
SinglePass = 1,
// Single pass stereo rendering with instancing
Instancing = 2
}
// Managed code stripping level - must be in sync with StrippingLevel enum in BuildTargetPlatformSpecific.h
public enum StrippingLevel
{
// Managed code stripping is disabled
Disabled = 0,
// Unused parts of managed code are stripped away
StripAssemblies = 1,
// Managed method bodies are stripped away. AOT platforms only.
StripByteCode = 2,
// Lightweight mscorlib version will be used at expense of limited compatibility.
UseMicroMSCorlib = 3
}
// Script call optimization level
public enum ScriptCallOptimizationLevel
{
// Default setting
SlowAndSafe = 0,
// Script method call overhead decreased at the expense of limited compatibility.
FastButNoExceptions = 1
}
// Default mobile device orientation
public enum UIOrientation
{
// Portrait
Portrait = 0,
// Portrait upside down
PortraitUpsideDown = 1,
// Landscape: clockwise from Portrait
LandscapeRight = 2,
// Landscape : counter-clockwise from Portrait
LandscapeLeft = 3,
// Auto Rotation Enabled
AutoRotation = 4
}
// Scripting runtime version
[Obsolete("ScriptingRuntimeVersion has been deprecated in 2019.3 now that legacy mono has been removed")]
public enum ScriptingRuntimeVersion
{
// .NET 3.5
Legacy = 0,
// .NET 4.6
Latest = 1
}
// .NET API compatibility level
public enum ApiCompatibilityLevel
{
// .NET 2.0
NET_2_0 = 1,
// .NET 2.0 Subset
NET_2_0_Subset = 2,
// .NET 4.6
NET_4_6 = 3,
// unity_web profile, currently unused. Formerly used by Samsung TV
NET_Web = 4,
// micro profile, used by Mono scripting backend if stripping level is set to "Use micro mscorlib"
NET_Micro = 5,
// .NET Standard 2.0
NET_Standard_2_0 = 6,
// Latest .NET Standard version Unity supports
NET_Standard = NET_Standard_2_0,
// .NET Framework 8 + .NET Standard 2.1 APIs
NET_Unity_4_8 = NET_4_6,
}
// Editor Assembly compatibility level
public enum EditorAssembliesCompatibilityLevel
{
// For now it will be the same as #2. In future updates, the default will be the same as #3.
Default = 1,
NET_Unity_4_8 = 2,
NET_Standard = 3,
}
public enum ManagedStrippingLevel
{
Disabled = 0,
Low = 1,
Medium = 2,
High = 3,
Minimal = 4,
}
// What to do on uncaught .NET exception (on iOS)
public enum ActionOnDotNetUnhandledException
{
// Silent exit
SilentExit = 0,
// Crash
Crash = 1
}
[Obsolete("SplashScreenStyle deprecated, Use PlayerSettings.SplashScreen.UnityLogoStyle instead")]
public enum SplashScreenStyle
{
Light = 0,
Dark = 1
}
// Must be in sync with GraphicsJobMode enum in GfxDeviceTypes.h
public enum GraphicsJobMode
{
Native = 0,
Legacy = 1,
Split
}
// Must be in sync with GfxThreadingMode enum in GfxDeviceTypes.h
public enum GfxThreadingMode
{
// Direct threading mode.
// Main thread writes native graphics commands and submits them directly.
Direct = 0,
// SingleThreaded mode.
// Main thread writes Unity graphics commands that it later reads and converts to native graphics commands.
NonThreaded = 1,
// MultiThreaded mode.
// Main thread writes Unity graphics commands. A Render thread reads Unity graphics commands and converts them to native graphics commands.
Threaded = 2,
// Legacy Graphics Jobs ("Jobified Rendering").
// Main thread writes Unity graphics commands and starts worker threads to do the same.
// A Render thread reads Unity graphics commands and converts them to native graphics commands.
ClientWorkerJobs = 3,
// Native Graphics Jobs.
// Main thread writes Unity graphics commands.
// Render thread reads Unity graphics commands and converts them to native graphics commands.
// The render thread also starts worker threads to write native graphics commands.
ClientWorkerNativeJobs = 4,
// Native Graphics Jobs without Render Thread.
// Main thread writes native graphics commands, starts worker threads to do the same, and submits them directly.
DirectNativeJobs = 5,
// Split Graphics Jobs.
// Main thread starts worker threads to write Unity graphics commands.
// Render thread reads Unity graphics commands converts them to native graphics commands.
// The render thread also starts worker threads to write native graphics commands.
SplitJobs = 6
}
// Must be in sync with MeshDeformation enum in GfxDeviceTypes.h
public enum MeshDeformation
{
CPU = 0,
GPU = 1,
GPUBatched = 2
}
// Must be in sync with IconKind enum in EditorOnlyPlayerSettings.h
public enum IconKind
{
Any = -1,
Application = 0,
Settings = 1,
Notification = 2,
Spotlight = 3,
Store = 4
}
// Keep in synch with LightmapEncodingQuality enum from GfxDeviceTypes.h
internal enum LightmapEncodingQuality
{
Low = 0,
Normal = 1,
High = 2
}
// Keep in synch with HDRCubemapEncodingQuality enum from GfxDeviceTypes.h
internal enum HDRCubemapEncodingQuality
{
Low = 0,
Normal = 1,
High = 2
}
// Must be in sync with ShaderPrecisionModel enum in EditorOnlyPlayerSettings.h
public enum ShaderPrecisionModel
{
PlatformDefault = 0,
Unified = 1,
}
public enum NormalMapEncoding
{
XYZ = 0,
DXT5nm = 1
}
public enum TextureCompressionFormat
{
Unknown = 0,
ETC = 1,
ETC2 = 2,
ASTC = 3,
PVRTC = 4,
DXTC = 5,
BPTC = 6,
DXTC_RGTC = 7
}
public enum InsecureHttpOption
{
NotAllowed = 0,
DevelopmentOnly = 1,
AlwaysAllowed = 2,
}
// Windows platform input APIs
// Keep in sync with WindowsGamepadBackendHint enum from PlayerSettings.h
public enum WindowsGamepadBackendHint
{
// Backend selected automatically based on platform support
WindowsGamepadBackendHintDefault = 0,
// XInput
WindowsGamepadBackendHintXInput = 1,
// GameInput
WindowsGamepadBackendHintWindowsGamingInput = 2
}
// Player Settings is where you define various parameters for the final game that you will build in Unity. Some of these values are used in the Resolution Dialog that launches when you open a standalone game.
[NativeClass(null)]
[NativeHeader("Editor/Mono/PlayerSettings.bindings.h")]
[NativeHeader("Runtime/Misc/BuildSettings.h")]
[NativeHeader("Runtime/Misc/PlayerSettings.h")]
[NativeHeader("Runtime/Misc/PlayerSettingsSplashScreen.h")]
[StaticAccessor("GetPlayerSettings()")]
public sealed partial class PlayerSettings : UnityEngine.Object
{
private PlayerSettings() {}
private static SerializedObject _serializedObject;
[FreeFunction("GetPlayerSettingsPtr")]
private static extern UnityEngine.Object InternalGetPlayerSettingsObject();
internal static void ValidateBuildTargetNameParameter(string buildTargetName, bool unknownIsValid = false)
{
// The empty string is the valid form of BuildTargetGroup.Unknown, so don't throw an execption for that case.
if (BuildPipeline.GetBuildTargetGroupByName(buildTargetName) == BuildTargetGroup.Unknown && (!unknownIsValid || buildTargetName != ""))
throw new ArgumentException($"The provided target platform group name ({buildTargetName}) is not valid.");
}
internal static SerializedObject GetSerializedObject()
{
if (_serializedObject == null)
_serializedObject = new SerializedObject(InternalGetPlayerSettingsObject());
return _serializedObject;
}
internal static SerializedProperty FindProperty(string name)
{
SerializedProperty property = GetSerializedObject().FindProperty(name);
if (property == null)
Debug.LogError("Failed to find:" + name);
return property;
}
[Obsolete("Use explicit API instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetPropertyInt(string name, int value, BuildTargetGroup target);
[Obsolete("Use explicit API instead.")]
public static void SetPropertyInt(string name, int value)
{
SetPropertyInt(name, value, BuildTargetGroup.Unknown);
}
[Obsolete("Use explicit API instead.")]
public static void SetPropertyInt(string name, int value, BuildTarget target)
{
SetPropertyInt(name, value, BuildPipeline.GetBuildTargetGroup(target));
}
[Obsolete("Use explicit API instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern int GetPropertyInt(string name, BuildTargetGroup target);
[Obsolete("Use explicit API instead.")]
public static int GetPropertyInt(string name)
{
return GetPropertyInt(name, BuildTargetGroup.Unknown);
}
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyOptionalInt(string name, ref int value, BuildTargetGroup target)
{
value = GetPropertyInt(name, target);
return true;
}
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyOptionalInt(string name, ref int value)
{
value = GetPropertyInt(name, BuildTargetGroup.Unknown);
return true;
}
[Obsolete("Use explicit API instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetPropertyBool(string name, bool value, BuildTargetGroup target);
[Obsolete("Use explicit API instead.")]
public static void SetPropertyBool(string name, bool value)
{
SetPropertyBool(name, value, BuildTargetGroup.Unknown);
}
[Obsolete("Use explicit API instead.")]
public static void SetPropertyBool(string name, bool value, BuildTarget target)
{
SetPropertyBool(name, value, BuildPipeline.GetBuildTargetGroup(target));
}
[Obsolete("Use explicit API instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool GetPropertyBool(string name, BuildTargetGroup target);
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyBool(string name)
{
return GetPropertyBool(name, BuildTargetGroup.Unknown);
}
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyOptionalBool(string name, ref bool value, BuildTargetGroup target)
{
value = GetPropertyBool(name, target);
return true;
}
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyOptionalBool(string name, ref bool value)
{
value = GetPropertyBool(name, BuildTargetGroup.Unknown);
return true;
}
[Obsolete("Use explicit API instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetPropertyString(string name, string value, BuildTargetGroup target);
[Obsolete("Use explicit API instead.")]
public static void SetPropertyString(string name, string value)
{
SetPropertyString(name, value, BuildTargetGroup.Unknown);
}
[Obsolete("Use explicit API instead.")]
public static void SetPropertyString(string name, string value, BuildTarget target)
{
SetPropertyString(name, value, BuildPipeline.GetBuildTargetGroup(target));
}
[Obsolete("Use explicit API instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern string GetPropertyString(string name, BuildTargetGroup target);
[Obsolete("Use explicit API instead.")]
public static string GetPropertyString(string name)
{
return GetPropertyString(name, BuildTargetGroup.Unknown);
}
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyOptionalString(string name, ref string value, BuildTargetGroup target)
{
value = GetPropertyString(name, target);
return true;
}
[Obsolete("Use explicit API instead.")]
public static bool GetPropertyOptionalString(string name, ref string value)
{
value = GetPropertyString(name, BuildTargetGroup.Unknown);
return true;
}
internal static extern void SetDirty();
// The name of your company.
public static extern string companyName { get; set; }
// The name of your product.
public static extern string productName { get; set; }
[Obsolete("Use PlayerSettings.SplashScreen.show instead")]
[StaticAccessor("GetPlayerSettings().GetSplashScreenSettings()")]
public static extern bool showUnitySplashScreen { get; set; }
[Obsolete("Use PlayerSettings.SplashScreen.unityLogoStyle instead")]
[StaticAccessor("GetPlayerSettings().GetSplashScreenSettings()")]
[NativeProperty("SplashScreenLogoStyle")]
public static extern SplashScreenStyle splashScreenStyle { get; set; }
/// Cloud project id.
[Obsolete("cloudProjectId is deprecated, use CloudProjectSettings.projectId instead")]
public static extern string cloudProjectId { get; }
internal static extern void SetCloudProjectId(string projectId);
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
internal static extern void SetCloudServiceEnabled(string serviceKey, bool enabled);
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
internal static extern bool GetCloudServiceEnabled(string serviceKey);
/// Uniquely identifies your product.
public static Guid productGUID
{
get { return new Guid(productGUIDRaw); }
}
/// *undocumented*
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
private static extern byte[] productGUIDRaw { get; }
// Set the color space for the current project
public static extern ColorSpace colorSpace { get; set; }
// Default horizontal dimension of stand-alone player window.
public static extern int defaultScreenWidth { get; set; }
// Default vertical dimension of stand-alone player window.
public static extern int defaultScreenHeight { get; set; }
// Default horizontal dimension of web player window.
public static extern int defaultWebScreenWidth { get; set; }
// Default vertical dimension of web player window.
public static extern int defaultWebScreenHeight { get; set; }
// Defines the behaviour of the Resolution Dialog on product launch.
[Obsolete("displayResolutionDialog has been removed.", false)]
public static extern ResolutionDialogSetting displayResolutionDialog { get; set; }
// If enabled, the game will default to fullscreen mode.
[Obsolete("(defaultIsFullScreen is deprecated, use fullScreenMode instead")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool defaultIsFullScreen { get; set; }
// If enabled, the game will default to native resolution in fullscreen mode.
public static extern bool defaultIsNativeResolution { get; set; }
// If enabled, the game will render at retina resolution
public static extern bool macRetinaSupport { get; set; }
// If enabled, your game will continue to run after lost focus.
public static extern bool runInBackground { get; set; }
// Defines if fullscreen games should darken secondary displays.
public static extern bool captureSingleScreen { get; set; }
// Write a log file with debugging information.
public static extern bool usePlayerLog { get; set; }
// Use resizable window in standalone player builds.
public static extern bool resizableWindow { get; set; }
// Should resolution be reset when native window size changes. Shared between iOS & Android platforms.
public static extern bool resetResolutionOnWindowResize { get; set; }
/// Bake collision meshes into the mesh asset.
public static extern bool bakeCollisionMeshes { get; set; }
// Enable receipt validation for the Mac App Store.
public static extern bool useMacAppStoreValidation { get; set; }
// Enable advanced optimiztions for Dedicated Server builds
public static extern bool dedicatedServerOptimizations { get; set; }
// Define how to handle fullscreen mode in Mac OS X standalones
[Obsolete("macFullscreenMode is deprecated, use fullScreenMode instead")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern MacFullscreenMode macFullscreenMode { get; set; }
// Define how to handle fullscreen mode with Direct3D 9
[Obsolete("d3d9FullscreenMode is deprecated, use fullScreenMode instead")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern D3D9FullscreenMode d3d9FullscreenMode { get; set; }
// Define how to handle fullscreen mode with Direct3D 11
[Obsolete("d3d11FullscreenMode is deprecated, use fullScreenMode instead")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern D3D11FullscreenMode d3d11FullscreenMode { get; set; }
[NativeProperty("FullscreenMode")]
public static extern FullScreenMode fullScreenMode { get; set; }
[Obsolete("This API is obsolete, and should no longer be used. Please use XRManagerSettings in the XR Management package instead.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool virtualRealitySupported { get; set; }
[NativeHeader("Runtime/Misc/PlayerSettings.h")]
[StaticAccessor("GetPlayerSettings()", StaticAccessorType.Dot)]
internal class PlayerSettings360StereoCapture
{
public static extern bool enable360StereoCapture
{
get;
set;
}
}
public static bool enable360StereoCapture
{
get { return PlayerSettings360StereoCapture.enable360StereoCapture; }
set { PlayerSettings360StereoCapture.enable360StereoCapture = value; }
}
[Obsolete("singlePassStereoRendering will be deprecated. Use stereoRenderingPath instead.")]
public static bool singlePassStereoRendering
{
get { return stereoRenderingPath == StereoRenderingPath.SinglePass; }
set { stereoRenderingPath = value ? StereoRenderingPath.SinglePass : StereoRenderingPath.MultiPass; }
}
public static extern StereoRenderingPath stereoRenderingPath { get; set; }
[Obsolete("protectGraphicsMemory is deprecated. This field has no effect.", false)]
public static bool protectGraphicsMemory { get { return false; } set {} }
public static extern bool enableFrameTimingStats { get; set; }
public static extern bool enableOpenGLProfilerGPURecorders { get; set; }
public static extern bool allowHDRDisplaySupport { get; set; }
public static extern bool useHDRDisplay { get; set; }
[Obsolete("D3DHDRBitDepth has been replaced by hdrBitDepth. (UnityUpgradable) -> hdrBitDepth", true)]
public static extern D3DHDRDisplayBitDepth D3DHDRBitDepth { [NativeName("GetHDRBitDepthForObseleteEnum")] get; [NativeName("SetHDRBitDepthForObseleteEnum")] set; }
public static extern HDRDisplayBitDepth hdrBitDepth { get; set; }
// What happens with the fullscreen Window when it runs in the background
public static extern bool visibleInBackground { get; set; }
// What happens the user presses OS specific full screen switch key combination
public static extern bool allowFullscreenSwitch { get; set; }
// Restrict standalone players to a single concurrent running instance.
public static extern bool forceSingleInstance { get; set; }
public static extern bool useFlipModelSwapchain { get; set; }
[NativeProperty(TargetType = TargetType.Field)]
public static extern bool openGLRequireES31
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
[NativeProperty(TargetType = TargetType.Field)]
public static extern bool openGLRequireES31AEP
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
[NativeProperty(TargetType = TargetType.Field)]
public static extern bool openGLRequireES32
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
// Set Maximum Vertex Threshold for Sprite Batching.
public static extern int spriteBatchVertexThreshold { get; set; }
// The image to display in the Resolution Dialog window.
[Obsolete("resolutionDialogBanner has been removed.", false)]
public static extern Texture2D resolutionDialogBanner { get; set; }
// The image to display on the Virtual Reality splash screen.
[StaticAccessor("GetPlayerSettings().GetSplashScreenSettings()")]
public static extern Texture2D virtualRealitySplashScreen { get; set; }
// The bundle identifier of the iPhone application.
[Obsolete("iPhoneBundleIdentifier is deprecated. Use PlayerSettings.SetApplicationIdentifier(NamedBuildTarget.iOS) instead.")]
public static string iPhoneBundleIdentifier
{
get { return GetApplicationIdentifier(NamedBuildTarget.iOS); }
set { SetApplicationIdentifier(NamedBuildTarget.iOS, value); }
}
// Note: If an empty list is returned, no icons are assigned specifically to the specified platform at this point,
[NativeMethod("GetPlatformIcons")]
internal static extern Texture2D[] GetIconsForPlatform(string platform, IconKind kind);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern Texture2D[] GetIconsForPlatformByKind(int layerCount, string platform, int kind, string subKind, int width, int height);
internal static void SetIconsForPlatform(string platform, Texture2D[] icons)
{
SetIconsForPlatform(platform, icons, IconKind.Any);
}
[NativeThrows]
[NativeMethod("SetPlatformIcons")]
internal static extern void SetIconsForPlatform(string platform, Texture2D[] icons, IconKind kind);
[NativeMethod("GetPlatformIconWidths")]
internal static extern int[] GetIconWidthsForPlatform(string platform, IconKind kind);
[NativeMethod("GetPlatformIconHeights")]
internal static extern int[] GetIconHeightsForPlatform(string platform, IconKind kind);
[NativeMethod("GetPlatformIconKinds")]
internal static extern IconKind[] GetIconKindsForPlatform(string platform);
public static extern UnityEngine.Object[] GetPreloadedAssets();
public static extern void SetPreloadedAssets(UnityEngine.Object[] assets);
internal static string GetPlatformName(BuildTargetGroup targetGroup)
{
return BuildPipeline.GetBuildTargetGroupName(targetGroup);
}
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern void GetBatchingForPlatform(BuildTarget platform, out int staticBatching, out int dynamicBatching);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern void SetBatchingForPlatform(BuildTarget platform, int staticBatching, int dynamicBatching);
public static bool GetStaticBatchingForPlatform(BuildTarget platform)
{
PlayerSettings.GetBatchingForPlatform(platform, out var staticBatching, out _);
return staticBatching > 0;
}
public static void SetStaticBatchingForPlatform(BuildTarget platform, bool enable)
{
PlayerSettings.GetBatchingForPlatform(platform, out _, out var dynamicBatching);
PlayerSettings.SetBatchingForPlatform(platform, enable == true ? 1 : 0, dynamicBatching);
}
public static bool GetDynamicBatchingForPlatform(BuildTarget platform)
{
PlayerSettings.GetBatchingForPlatform(platform, out _, out var dynamicBatching);
return dynamicBatching > 0;
}
public static void SetDynamicBatchingForPlatform(BuildTarget platform, bool enable)
{
PlayerSettings.GetBatchingForPlatform(platform, out var staticBatching, out _);
PlayerSettings.SetBatchingForPlatform(platform, staticBatching, enable == true ? 1 : 0);
}
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern int GetShaderChunkSizeInMBForPlatform(BuildTarget buildTarget);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetShaderChunkSizeInMBForPlatform(BuildTarget buildTarget, int sizeInMegabytes);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern int GetShaderChunkCountForPlatform(BuildTarget buildTarget);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetShaderChunkCountForPlatform(BuildTarget buildTarget, int chunkCount);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern int GetDefaultShaderChunkSizeInMB();
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetDefaultShaderChunkSizeInMB(int sizeInMegabytes);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern int GetDefaultShaderChunkCount();
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetDefaultShaderChunkCount(int chunkCount);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool GetOverrideShaderChunkSettingsForPlatform(BuildTarget buildTarget);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetOverrideShaderChunkSettingsForPlatform(BuildTarget buildTarget, bool value);
[NativeMethod("GetLightmapEncodingQuality")]
internal static extern LightmapEncodingQuality GetLightmapEncodingQualityForPlatform(BuildTarget platform);
[NativeMethod("SetLightmapEncodingQuality")]
internal static extern void SetLightmapEncodingQualityForPlatform(BuildTarget platform, LightmapEncodingQuality encodingQuality);
[NativeMethod("GetHDRCubemapEncodingQuality")]
internal static extern HDRCubemapEncodingQuality GetHDRCubemapEncodingQualityForPlatform(BuildTarget platform);
[NativeMethod("SetHDRCubemapEncodingQuality")]
internal static extern void SetHDRCubemapEncodingQualityForPlatform(BuildTarget platform, HDRCubemapEncodingQuality encodingQuality);
[FreeFunction("GetTargetPlatformGraphicsAPIAvailability")]
internal static extern UnityEngine.Rendering.GraphicsDeviceType[] GetSupportedGraphicsAPIs(BuildTarget platform);
[NativeMethod("GetPlatformGraphicsAPIs")]
public static extern UnityEngine.Rendering.GraphicsDeviceType[] GetGraphicsAPIs(BuildTarget platform);
public static void SetGraphicsAPIs(BuildTarget platform, UnityEngine.Rendering.GraphicsDeviceType[] apis)
{
SetGraphicsAPIsImpl(platform, apis);
// we do cache api list in player settings editor, so if we update from script we should forcibly update cache
PlayerSettingsEditor.SyncPlatformAPIsList(platform);
}
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
private static extern void SetGraphicsAPIsImpl(BuildTarget platform, UnityEngine.Rendering.GraphicsDeviceType[] apis);
[NativeMethod("GetPlatformAutomaticGraphicsAPIs")]
public static extern bool GetUseDefaultGraphicsAPIs(BuildTarget platform);
public static void SetUseDefaultGraphicsAPIs(BuildTarget platform, bool automatic)
{
SetUseDefaultGraphicsAPIsImpl(platform, automatic);
// we do cache api list in player settings editor, so if we update from script we should forcibly update cache
PlayerSettingsEditor.SyncPlatformAPIsList(platform);
}
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
private static extern void SetUseDefaultGraphicsAPIsImpl(BuildTarget platform, bool automatic);
// Set the output color space for the current project. This setting only
// defines the format of the final framebuffer and render textures
internal static extern ColorGamut[] GetColorGamuts();
internal static void SetColorGamuts(ColorGamut[] colorSpaces)
{
SetColorGamutsImpl(colorSpaces);
// Color space data is cached in player settings editor
PlayerSettingsEditor.SyncColorGamuts();
}
[NativeMethod("SetColorGamuts")]
private static extern void SetColorGamutsImpl(ColorGamut[] colorSpaces);
internal static extern string[] templateCustomKeys { get; set; }
public static extern void SetTemplateCustomValue(string name, string value);
public static extern string GetTemplateCustomValue(string name);
internal static extern string spritePackerPolicy
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly().spritePackerPolicy")]
[NativeMethod("c_str")]
get;
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
set;
}
// TargetGroup no longer defines the entire build targets space. Now build targets are better
// identified by a string key (wrapped into NamedBuildTarget), so all the following methods are being replaced.
[Obsolete("Use GetScriptingDefineSymbols(NamedBuildTarget buildTarget) instead")]
public static string GetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup) =>
GetScriptingDefineSymbols(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use GetScriptingDefineSymbols(NamedBuildTarget buildTarget, out string[] defines) instead")]
public static void GetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup, out string[] defines) =>
defines = ScriptingDefinesHelper.ConvertScriptingDefineStringToArray(GetScriptingDefineSymbolsForGroup(targetGroup));
[Obsolete("Use SetScriptingDefineSymbols(NamedBuildTarget buildTarget, string defines) instead")]
public static void SetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup, string defines) =>
SetScriptingDefineSymbols(NamedBuildTarget.FromBuildTargetGroup(targetGroup), defines);
[Obsolete("Use SetScriptingDefineSymbols(NamedBuildTarget buildTarget, string[] defines) instead")]
public static void SetScriptingDefineSymbolsForGroup(BuildTargetGroup targetGroup, string[] defines) =>
SetScriptingDefineSymbols(NamedBuildTarget.FromBuildTargetGroup(targetGroup), defines);
[Obsolete("Use GetAdditionalCompilerArguments(NamedBuildTarget buildTarget) instead")]
public static string[] GetAdditionalCompilerArgumentsForGroup(BuildTargetGroup targetGroup) =>
GetAdditionalCompilerArguments(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use SetAdditionalCompilerArguments(NamedBuildTarget buildTarget, string[] additionalCompilerArguments) instead")]
public static void SetAdditionalCompilerArgumentsForGroup(BuildTargetGroup targetGroup, string[] additionalCompilerArguments) =>
SetAdditionalCompilerArguments(NamedBuildTarget.FromBuildTargetGroup(targetGroup), additionalCompilerArguments);
[Obsolete("Use GetArchitecture(NamedBuildTarget buildTarget) instead")]
public static int GetArchitecture(BuildTargetGroup targetGroup) =>
GetArchitecture(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use SetArchitecture(NamedBuildTarget buildTarget, int architecture) instead")]
public static void SetArchitecture(BuildTargetGroup targetGroup, int architecture) =>
SetArchitecture(NamedBuildTarget.FromBuildTargetGroup(targetGroup), architecture);
[Obsolete("Use GetScriptingBackend(NamedBuildTarget buildTarget) instead")]
public static ScriptingImplementation GetScriptingBackend(BuildTargetGroup targetGroup) =>
GetScriptingBackend(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use SetScriptingBackend(NamedBuildTarget buildTarget, ScriptingImplementation backend) instead")]
public static void SetScriptingBackend(BuildTargetGroup targetGroup, ScriptingImplementation backend) =>
SetScriptingBackend(NamedBuildTarget.FromBuildTargetGroup(targetGroup), backend);
[Obsolete("Use GetDefaultScriptingBackend(NamedBuildTarget buildTarget) instead")]
public static ScriptingImplementation GetDefaultScriptingBackend(BuildTargetGroup targetGroup) =>
GetDefaultScriptingBackend(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use GetApplicationIdentifier(NamedBuildTarget buildTarget) instead")]
public static string GetApplicationIdentifier(BuildTargetGroup targetGroup) =>
GetApplicationIdentifier(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use SetApplicationIdentifier(NamedBuildTarget buildTarget, string identifier) instead")]
public static void SetApplicationIdentifier(BuildTargetGroup targetGroup, string identifier) =>
SetApplicationIdentifier(NamedBuildTarget.FromBuildTargetGroup(targetGroup), identifier);
[Obsolete("Use GetIl2CppCompilerConfiguration(NamedBuildTarget buildTarget) instead")]
public static Il2CppCompilerConfiguration GetIl2CppCompilerConfiguration(BuildTargetGroup targetGroup) =>
GetIl2CppCompilerConfiguration(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use SetIl2CppCompilerConfiguration(NamedBuildTarget buildTarget, Il2CppCompilerConfiguration configuration) instead")]
public static void SetIl2CppCompilerConfiguration(BuildTargetGroup targetGroup, Il2CppCompilerConfiguration configuration) =>
SetIl2CppCompilerConfiguration(NamedBuildTarget.FromBuildTargetGroup(targetGroup), configuration);
[Obsolete("GetIncrementalIl2CppBuild has no impact on the build process")]
public static bool GetIncrementalIl2CppBuild(BuildTargetGroup targetGroup) =>
GetIncrementalIl2CppBuild(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("SetIncrementalIl2CppBuild has no impact on the build process")]
public static void SetIncrementalIl2CppBuild(BuildTargetGroup targetGroup, bool enabled) =>
SetIncrementalIl2CppBuild(NamedBuildTarget.FromBuildTargetGroup(targetGroup), enabled);
[Obsolete("Use SetManagedStrippingLevel(NamedBuildTarget buildTarget, ManagedStrippingLevel level) instead")]
public static void SetManagedStrippingLevel(BuildTargetGroup targetGroup, ManagedStrippingLevel level) =>
SetManagedStrippingLevel(NamedBuildTarget.FromBuildTargetGroup(targetGroup), level);
[Obsolete("Use GetManagedStrippingLevel(NamedBuildTarget buildTarget) instead")]
public static ManagedStrippingLevel GetManagedStrippingLevel(BuildTargetGroup targetGroup) =>
GetManagedStrippingLevel(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use GetApiCompatibilityLevel(NamedBuildTarget buildTarget) instead")]
public static ApiCompatibilityLevel GetApiCompatibilityLevel(BuildTargetGroup buildTargetGroup) =>
GetApiCompatibilityLevel(NamedBuildTarget.FromBuildTargetGroup(buildTargetGroup));
[Obsolete("Use SetApiCompatibilityLevel(NamedBuildTarget buildTarget, ApiCompatibilityLevel value) instead")]
public static void SetApiCompatibilityLevel(BuildTargetGroup buildTargetGroup, ApiCompatibilityLevel value) =>
SetApiCompatibilityLevel(NamedBuildTarget.FromBuildTargetGroup(buildTargetGroup), value);
[Obsolete("Use GetMobileMTRendering(NamedBuildTarget buildTarget) instead")]
public static bool GetMobileMTRendering(BuildTargetGroup targetGroup) =>
GetMobileMTRendering(NamedBuildTarget.FromBuildTargetGroup(targetGroup));
[Obsolete("Use SetMobileMTRendering(NamedBuildTarget buildTarget, bool enable) instead")]
public static void SetMobileMTRendering(BuildTargetGroup targetGroup, bool enable) =>
SetMobileMTRendering(NamedBuildTarget.FromBuildTargetGroup(targetGroup), enable);
[Obsolete("Use GetNormalMapEncoding(NamedBuildTarget buildTarget) instead")]
public static NormalMapEncoding GetNormalMapEncoding(BuildTargetGroup platform) =>
GetNormalMapEncoding(NamedBuildTarget.FromBuildTargetGroup(platform));
[Obsolete("Use SetNormalMapEncoding(NamedBuildTarget buildTarget, NormalMapEncoding encoding) instead")]
public static void SetNormalMapEncoding(BuildTargetGroup platform, NormalMapEncoding encoding) =>
SetNormalMapEncoding(NamedBuildTarget.FromBuildTargetGroup(platform), encoding);
// Get user-specified symbols for script compilation for the given build target name.
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetUserScriptingDefineSymbols")]
private static extern string GetScriptingDefineSymbolsInternal(string buildTargetName);
public static string GetScriptingDefineSymbols(NamedBuildTarget buildTarget) =>
GetScriptingDefineSymbolsInternal(buildTarget.TargetName);
public static void GetScriptingDefineSymbols(NamedBuildTarget buildTarget, out string[] defines) =>
defines = ScriptingDefinesHelper.ConvertScriptingDefineStringToArray(GetScriptingDefineSymbols(buildTarget));
// Set user-specified symbols for script compilation for the given build target group.
public static void SetScriptingDefineSymbols(NamedBuildTarget buildTarget, string defines)
{
if (!string.IsNullOrEmpty(defines))
defines = string.Join(";", ScriptingDefinesHelper.ConvertScriptingDefineStringToArray(defines));
SetScriptingDefineSymbolsInternal(buildTarget.TargetName, defines);
}
public static void SetScriptingDefineSymbols(NamedBuildTarget buildTarget, string[] defines)
{
if (defines == null)
throw new ArgumentNullException(nameof(defines));
SetScriptingDefineSymbols(buildTarget, ScriptingDefinesHelper.ConvertScriptingDefineArrayToString(defines));
}
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetUserScriptingDefineSymbols")]
private static extern void SetScriptingDefineSymbolsInternal(string buildTargetName, string defines);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetAdditionalCompilerArguments")]
private static extern string[] GetAdditionalCompilerArgumentsInternal(string buildTargetName);
public static string[] GetAdditionalCompilerArguments(NamedBuildTarget buildTarget) =>
GetAdditionalCompilerArgumentsInternal(buildTarget.TargetName);
public static void SetAdditionalCompilerArguments(NamedBuildTarget buildTarget, string[] additionalCompilerArguments)
{
if (additionalCompilerArguments == null)
throw new ArgumentNullException(nameof(additionalCompilerArguments));
SetAdditionalCompilerArgumentsInternal(buildTarget.TargetName, additionalCompilerArguments);
}
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetAdditionalCompilerArguments")]
private static extern void SetAdditionalCompilerArgumentsInternal(string buildTargetName, string[] additionalCompilerArguments);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetPlatformArchitecture")]
private static extern int GetArchitectureInternal(string buildTargetName);
public static int GetArchitecture(NamedBuildTarget buildTarget) => GetArchitectureInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetPlatformArchitecture")]
private static extern void SetArchitectureInternal(string buildTargetName, int architecture);
public static void SetArchitecture(NamedBuildTarget buildTarget, int architecture) =>
SetArchitectureInternal(buildTarget.TargetName, architecture);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetPlatformScriptingBackend")]
private static extern ScriptingImplementation GetScriptingBackendInternal(string buildTargetName);
public static ScriptingImplementation GetScriptingBackend(NamedBuildTarget buildTarget) =>
GetScriptingBackendInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetPlatformScriptingBackend")]
private static extern void SetScriptingBackendInternal(string buildTargetName, ScriptingImplementation backend);
public static void SetScriptingBackend(NamedBuildTarget buildTarget, ScriptingImplementation backend) =>
SetScriptingBackendInternal(buildTarget.TargetName, backend);
[FreeFunction("GetDefaultScriptingBackendForGroup")]
internal static extern ScriptingImplementation GetDefaultScriptingBackendForGroup(BuildTargetGroup targetGroup);
public static ScriptingImplementation GetDefaultScriptingBackend(NamedBuildTarget buildTarget)
{
return GetDefaultScriptingBackendForGroup(buildTarget.ToBuildTargetGroup());
}
[NativeThrows]
[NativeMethod("GetCaptureStartupLogs")]
private static extern bool GetCaptureStartupLogsInternal(string buildTargetName);
public static bool GetCaptureStartupLogs(NamedBuildTarget buildTarget) =>
GetCaptureStartupLogsInternal(buildTarget.TargetName);
[NativeThrows]
[NativeMethod("SetCaptureStartupLogs")]
private static extern void SetCaptureStartupLogsInternal(string buildTargetName, bool enable);
public static void SetCaptureStartupLogs(NamedBuildTarget buildTarget, bool enable) =>
SetCaptureStartupLogsInternal(buildTarget.TargetName, enable);
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
internal static extern bool IsApplicationIdentifierValid(string name, BuildTargetGroup targetGroup);
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
internal static extern string SanitizeApplicationIdentifier(string name, BuildTargetGroup targetGroup);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetApplicationIdentifier")]
private static extern void SetApplicationIdentifierInternal(string buildTargetName, string identifier);
public static void SetApplicationIdentifier(NamedBuildTarget buildTarget, string identifier) =>
SetApplicationIdentifierInternal(buildTarget.TargetName, identifier);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetApplicationIdentifier")]
private static extern string GetApplicationIdentifierInternal(string buildTargetName);
public static string GetApplicationIdentifier(NamedBuildTarget buildTarget) =>
GetApplicationIdentifierInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetApplicationBuildNumber")]
internal static extern string GetBuildNumber(string buildTargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetApplicationBuildNumber")]
internal static extern void SetBuildNumber(string buildTargetName, string buildNumber);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetIl2CppCompilerConfiguration")]
private static extern void SetIl2CppCompilerConfigurationInternal(string buildTargetName, Il2CppCompilerConfiguration configuration);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetIl2CppCompilerConfiguration")]
private static extern Il2CppCompilerConfiguration GetIl2CppCompilerConfigurationInternal(string buildTargetName);
public static Il2CppCompilerConfiguration GetIl2CppCompilerConfiguration(NamedBuildTarget buildTarget) =>
GetIl2CppCompilerConfigurationInternal(buildTarget.TargetName);
public static void SetIl2CppCompilerConfiguration(NamedBuildTarget buildTarget, Il2CppCompilerConfiguration configuration)
{
var scriptingImpl = ModuleManager.GetScriptingImplementations(buildTarget);
if (scriptingImpl != null && !scriptingImpl.AllowIL2CPPCompilerConfigurationSelection())
{
Debug.LogWarning($"The C++ compiler configuration option does not apply to the {buildTarget.TargetName} platform as it is configured. Set the configuration in the generated IDE project instead.");
return;
}
SetIl2CppCompilerConfigurationInternal(buildTarget.TargetName, configuration);
}
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetIl2CppStacktraceInformation")]
private static extern Il2CppStacktraceInformation GetIl2CppStacktraceInformationInternal(string buildTargetName);
public static Il2CppStacktraceInformation GetIl2CppStacktraceInformation(NamedBuildTarget buildTarget) =>
GetIl2CppStacktraceInformationInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetIl2CppStacktraceInformation")]
private static extern void SetIl2CppStacktraceInformationInternal(string buildTargetName, Il2CppStacktraceInformation option);
public static void SetIl2CppStacktraceInformation(NamedBuildTarget buildTarget, Il2CppStacktraceInformation option)
{
if (buildTarget == NamedBuildTarget.WebGL && option == Il2CppStacktraceInformation.MethodFileLineNumber)
{
Debug.LogWarning("The \"Method Name, File Name, and Line Number\" option for IL2CPP stack traces is not supported on WebGL.");
option = Il2CppStacktraceInformation.MethodOnly;
}
SetIl2CppStacktraceInformationInternal(buildTarget.TargetName, option);
}
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetPlatformIncrementalIl2CppBuild")]
private static extern bool GetIncrementalIl2CppBuildInternal(string buildTargetName);
[Obsolete("GetIncrementalIl2CppBuild has no impact on the build process")]
public static bool GetIncrementalIl2CppBuild(NamedBuildTarget buildTarget) => GetIncrementalIl2CppBuildInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetPlatformIncrementalIl2CppBuild")]
private static extern void SetIncrementalIl2CppBuildInternal(string buildTargetName, bool enabled);
[Obsolete("SetIncrementalIl2CppBuild has no impact on the build process")]
public static void SetIncrementalIl2CppBuild(NamedBuildTarget buildTarget, bool enabled) =>
SetIncrementalIl2CppBuildInternal(buildTarget.TargetName, enabled);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetManagedStrippingLevel")]
private static extern void SetManagedStrippingLevelInternal(string buildTargetName, ManagedStrippingLevel level);
public static void SetManagedStrippingLevel(NamedBuildTarget buildTarget, ManagedStrippingLevel level) =>
SetManagedStrippingLevelInternal(buildTarget.TargetName, level);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetManagedStrippingLevel")]
private static extern ManagedStrippingLevel GetManagedStrippingLevelInternal(string buildTargetName);
public static ManagedStrippingLevel GetManagedStrippingLevel(NamedBuildTarget buildTarget) => GetManagedStrippingLevelInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetApiCompatibilityLevel")]
private static extern ApiCompatibilityLevel GetApiCompatibilityLevelInternal(string buildTargetName);
public static ApiCompatibilityLevel GetApiCompatibilityLevel(NamedBuildTarget buildTarget) => GetApiCompatibilityLevelInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetApiCompatibilityLevel")]
private static extern void SetApiCompatibilityLevelInternal(string buildTargetName, ApiCompatibilityLevel value);
public static void SetApiCompatibilityLevel(NamedBuildTarget buildTarget, ApiCompatibilityLevel value) =>
SetApiCompatibilityLevelInternal(buildTarget.TargetName, value);
internal static extern bool defaultEditorAssembliesCompatibilityLevel
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
}
internal static ApiCompatibilityLevel EditorAssemblyCompatibilityToApiCompatibility(EditorAssembliesCompatibilityLevel level)
{
switch (level)
{
case EditorAssembliesCompatibilityLevel.NET_Standard:
{
return ApiCompatibilityLevel.NET_Standard_2_0;
}
default:
{
return ApiCompatibilityLevel.NET_Unity_4_8;
}
}
}
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetEditorAssembliesCompatibilityLevel")]
private static extern EditorAssembliesCompatibilityLevel GetEditorAssembliesCompatibilityLevelInternal();
public static EditorAssembliesCompatibilityLevel GetEditorAssembliesCompatibilityLevel() => GetEditorAssembliesCompatibilityLevelInternal();
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetEditorAssembliesCompatibilityLevel")]
private static extern void SetEditorAssembliesCompatibilityLevelInternal(EditorAssembliesCompatibilityLevel value);
public static void SetEditorAssembliesCompatibilityLevel(EditorAssembliesCompatibilityLevel value) => SetEditorAssembliesCompatibilityLevelInternal(value);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetIl2CppCodeGeneration")]
private static extern Il2CppCodeGeneration GetIl2CppCodeGenerationInternal(string buildTargetName);
public static Il2CppCodeGeneration GetIl2CppCodeGeneration(NamedBuildTarget buildTarget) => GetIl2CppCodeGenerationInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetIl2CppCodeGeneration")]
private static extern void SetIl2CppCodeGenerationInternal(string buildTargetName, Il2CppCodeGeneration value);
public static void SetIl2CppCodeGeneration(NamedBuildTarget buildTarget, Il2CppCodeGeneration value) =>
SetIl2CppCodeGenerationInternal(buildTarget.TargetName, value);
[NativeThrows]
[NativeMethod("SetMobileMTRendering")]
private static extern void SetMobileMTRenderingInternal(string buildTargetName, bool enable);
public static void SetMobileMTRendering(NamedBuildTarget buildTarget, bool enable) =>
SetMobileMTRenderingInternal(buildTarget.TargetName, enable);
[NativeThrows]
[NativeMethod("GetMobileMTRendering")]
private static extern bool GetMobileMTRenderingInternal(string buildTargetName);
public static bool GetMobileMTRendering(NamedBuildTarget buildTarget) => GetMobileMTRenderingInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
[NativeMethod("GetNormalMapEncoding")]
private static extern NormalMapEncoding GetNormalMapEncodingInternal(string buildTargetName);
public static NormalMapEncoding GetNormalMapEncoding(NamedBuildTarget buildTarget) => GetNormalMapEncodingInternal(buildTarget.TargetName);
[NativeThrows]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
[NativeMethod("SetNormalMapEncoding")]
private static extern void SetNormalMapEncodingInternal(string buildTargetName, NormalMapEncoding encoding);
public static void SetNormalMapEncoding(NamedBuildTarget buildTarget, NormalMapEncoding encoding) =>
SetNormalMapEncodingInternal(buildTarget.TargetName, encoding);
[Obsolete("assemblyVersionValidation has been deprecated due to the introduction of binding redirects")]
public static bool assemblyVersionValidation
{
get => false;
set { }
}
[StaticAccessor("GetPlayerSettings().GetEditorOnly().additionalIl2CppArgs")]
[NativeMethod("c_str")]
public static extern string GetAdditionalIl2CppArgs();
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern void SetAdditionalIl2CppArgs(string additionalArgs);
[Obsolete("ScriptingRuntimeVersion has been deprecated in 2019.3 due to the removal of legacy mono")]
public static ScriptingRuntimeVersion scriptingRuntimeVersion
{
get { return ScriptingRuntimeVersion.Latest; }
set {}
}
public static extern bool suppressCommonWarnings
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
public static extern bool allowUnsafeCode
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
internal static extern bool UseDeterministicCompilation
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
[Obsolete("Use of reference assemblies is always enabled")]
public static bool useReferenceAssemblies
{
get { return true; }
set {}
}
internal static extern bool gcWBarrierValidation
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
public static extern bool gcIncremental
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
set;
}
// Xbox 360 title id
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static string xboxTitleId
{
get { return String.Empty; }
set {}
}
// Xbox 360 ImageXex override configuration file path
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static string xboxImageXexFilePath
{
get { return String.Empty; }
}
// Xbox 360 SPA file path
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static string xboxSpaFilePath
{
get { return String.Empty; }
}
// Xbox 360 auto-generation of _SPAConfig.cs
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxGenerateSpa
{
get { return false; }
}
// Xbox 360 Enable XboxLive guest accounts
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxEnableGuest
{
get { return false; }
}
// Xbox 360 Kinect resource file deployment
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxDeployKinectResources
{
get { return false; }
}
// Xbox 360 Kinect Head Orientation file deployment
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxDeployKinectHeadOrientation
{
get { return false; }
set {}
}
// Xbox 360 Kinect Head Position file deployment
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxDeployKinectHeadPosition
{
get { return false; }
set {}
}
// Xbox 360 splash screen
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static Texture2D xboxSplashScreen
{
get { return null; }
}
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static int xboxAdditionalTitleMemorySize
{
get { return 0; }
set {}
}
// Xbox 360 Kinect title flag - if false, the Kinect APIs are inactive
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxEnableKinect
{
get { return false; }
}
// Xbox 360 Kinect automatic skeleton tracking.
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxEnableKinectAutoTracking
{
get { return false; }
}
// Xbox 360 Kinect Enable Speech Engine
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static bool xboxEnableSpeech
{
get { return false; }
}
// Xbox 360 Kinect Speech DB
[Obsolete("Xbox 360 has been removed in >=5.5")]
public static UInt32 xboxSpeechDB
{
get { return 0; }
}
[NativeProperty("GPUSkinning")]
public static extern bool gpuSkinning { get; set; }
[NativeProperty("MeshDeformation")]
public static extern MeshDeformation meshDeformation { get; set; }
public static bool graphicsJobs
{
get { return GetGraphicsJobsForPlatform(EditorUserBuildSettings.activeBuildTarget); }
set { SetGraphicsJobsForPlatform(EditorUserBuildSettings.activeBuildTarget, value); }
}
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern bool GetGraphicsJobsForPlatform(BuildTarget platform);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern void SetGraphicsJobsForPlatform(BuildTarget platform, bool graphicsJobs);
public static GraphicsJobMode graphicsJobMode
{
get { return GetGraphicsJobModeForPlatform(EditorUserBuildSettings.activeBuildTarget); }
set { SetGraphicsJobModeForPlatform(EditorUserBuildSettings.activeBuildTarget, value); }
}
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern GraphicsJobMode GetGraphicsJobModeForPlatform(BuildTarget platform);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern void SetGraphicsJobModeForPlatform(BuildTarget platform, GraphicsJobMode gfxJobMode);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern GfxThreadingMode GetGraphicsThreadingModeForPlatform(BuildTarget platform);
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
internal static extern void SetGraphicsThreadingModeForPlatform(BuildTarget platform, GfxThreadingMode gfxJobMode);
[StaticAccessor("GetPlayerSettings()")]
public static extern bool GetWsaHolographicRemotingEnabled();
[StaticAccessor("GetPlayerSettings()")]
public static extern void SetWsaHolographicRemotingEnabled(bool enabled);
// Xbox 360 Pix Texture Capture
public static extern bool xboxPIXTextureCapture { get; }
// Xbox 360 Avatars
public static extern bool xboxEnableAvatar { get; }
// Xbox One resolution options
public static extern int xboxOneResolution { get; }
/// Whether internal profiler is enabled on iOS
public static extern bool enableInternalProfiler { get; set; }
/// What to do on unhandled .NET exceptions on iOS
public static extern ActionOnDotNetUnhandledException actionOnDotNetUnhandledException { get; set; }
/// Whether to log Objective-C uncaught exceptions on iOS
public static extern bool logObjCUncaughtExceptions { get; set; }
/// Whether to enable the Crash Reporter API on iOS
public static extern bool enableCrashReportAPI { get; set; }
// Application (before 5.6 bundle) identifier was shared between iOS, Android and Tizen TV platforms before 5.6.
public static string applicationIdentifier
{
get { return GetApplicationIdentifier(NamedBuildTarget.FromActiveSettings(EditorUserBuildSettings.activeBuildTarget)); }
set
{
Debug.LogWarning("PlayerSettings.applicationIdentifier only changes the identifier for the currently active platform. Please use SetApplicationIdentifier to set it for any platform");
SetApplicationIdentifier(NamedBuildTarget.FromActiveSettings(EditorUserBuildSettings.activeBuildTarget), value);
}
}
// Application bundle version for the VisionOS platform
[NativeProperty("VisionOSApplicationVersion")]
public static extern string visionOSBundleVersion { get; set; }
// Application bundle version for the TVOS platform
[NativeProperty("TVOSApplicationVersion")]
public static extern string tvOSBundleVersion { get; set; }
// Application bundle version shared between iOS & Android platforms
[NativeProperty("ApplicationVersion")]
public static extern string bundleVersion { get; set; }
// Should status bar be hidden. Shared between iOS & Android platforms
[NativeProperty("UIStatusBarHidden")]
public static extern bool statusBarHidden { get; set; }
// Code stripping level
[Obsolete("strippingLevel is deprecated, Use PlayerSettings.GetManagedStrippingLevel()/PlayerSettings.SetManagedStrippingLevel() instead. StripByteCode and UseMicroMSCorlib are no longer supported.")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern StrippingLevel strippingLevel { get; set; }
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
internal static extern void ReinitialiseShaderCompiler(string platformSDKEnvVar, string EnvVarValue);
// Strip Engine code
public static extern bool stripEngineCode { get; set; }
// Default screen orientation for mobiles
[NativeProperty("DefaultScreenOrientation")]
public static extern UIOrientation defaultInterfaceOrientation { get; set; }
// Is auto-rotation to portrait supported?
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool allowedAutorotateToPortrait { get; set; }
// Is auto-rotation to portrait upside-down supported?
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool allowedAutorotateToPortraitUpsideDown { get; set; }
// Is auto-rotation to landscape right supported?
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool allowedAutorotateToLandscapeRight { get; set; }
// Is auto-rotation to landscape left supported?
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool allowedAutorotateToLandscapeLeft { get; set; }
// Let the OS autorotate the screen as the device orientation changes.
[NativeProperty("UseAnimatedAutoRotation")]
public static extern bool useAnimatedAutorotation { get; set; }
// 32-bit Display Buffer is used
public static extern bool use32BitDisplayBuffer { get; set; }
// Preserve framebuffer alpha, iOS and Android only. Enables rendering Unity on top of native UI.
public static extern bool preserveFramebufferAlpha { get; set; }
// .NET API compatibility level
[Obsolete("apiCompatibilityLevel is deprecated. Use PlayerSettings.GetApiCompatibilityLevel()/PlayerSettings.SetApiCompatibilityLevel() instead.")]
public static ApiCompatibilityLevel apiCompatibilityLevel
{
get { return GetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup); }
set { SetApiCompatibilityLevel(EditorUserBuildSettings.activeBuildTargetGroup, value); }
}
// Should unused [[Mesh]] components be excluded from game build?
public static extern bool stripUnusedMeshComponents { get; set; }
// Don't do fuzzy variant selection in the player. If the requested variant is not there, use error shader.
public static extern bool strictShaderVariantMatching { get; set; }
// Should unused mips be excluded from texture build?
public static extern bool mipStripping { get; set; }
// Is the advanced version being used?
[StaticAccessor("GetBuildSettings()")]
[NativeProperty("hasAdvancedVersion", TargetType.Field)]
public static extern bool advancedLicense { get; }
// Additional AOT compilation options. Shared by AOT platforms.
public static extern string aotOptions { get; set; }
public static extern Texture2D defaultCursor { get; set; }
public static extern Vector2 cursorHotspot { get; set; }
// Accelerometer update frequency
public static extern int accelerometerFrequency { get; set; }
// Is multi-threaded rendering enabled?
public static extern bool MTRendering { get; set; }
[NativeMethod("GetStackTraceType")]
public static extern StackTraceLogType GetStackTraceLogType(LogType logType);
[NativeMethod("SetStackTraceType")]
public static extern void SetStackTraceLogType(LogType logType, StackTraceLogType stackTraceType);
[NativeMethod("GetGlobalStackTraceType")]
internal static extern StackTraceLogType GetGlobalStackTraceLogType(LogType logType);
[NativeMethod("SetGlobalStackTraceType")]
internal static extern void SetGlobalStackTraceLogType(LogType logType, StackTraceLogType stackTraceType);
[Obsolete("Use UnityEditor.PlayerSettings.SetGraphicsAPIs/GetGraphicsAPIs instead")]
public static bool useDirect3D11
{
get { return GetUseDefaultGraphicsAPIs(BuildTarget.StandaloneWindows); }
set {} // setter does nothing; D3D11 is always the fallback
}
internal static extern bool submitAnalytics { get; set; }
[Obsolete("Use VREditor.GetStereoDeviceEnabled instead")]
[StaticAccessor("PlayerSettingsBindings", StaticAccessorType.DoubleColon)]
public static extern bool stereoscopic3D { get; set; }
// Defines whether the application will request audio focus, muting all other audio sources.
public static extern bool muteOtherAudioSources { get; set; }
internal static extern bool playModeTestRunnerEnabled { get; set; }
internal static extern bool runPlayModeTestAsEditModeTest { get; set; }
// Defines whether the BlendShape weight range in SkinnedMeshRenderers is clamped
public static extern bool legacyClampBlendShapeWeights { get; set; }
// If enabled, metal API validation will be turned on in the editor
[NativeProperty("MetalAPIValidation")]
public static extern bool enableMetalAPIValidation
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)]
set;
}
[FreeFunction("GetPlayerSettings().GetLightmapStreamingEnabled")]
internal static extern bool GetLightmapStreamingEnabledForPlatformGroup(BuildTargetGroup platformGroup);
[FreeFunction("GetPlayerSettings().SetLightmapStreamingEnabled")]
internal static extern void SetLightmapStreamingEnabledForPlatformGroup(BuildTargetGroup platformGroup, bool lightmapStreamingEnabled);
[FreeFunction("GetPlayerSettings().GetLightmapStreamingPriority")]
internal static extern int GetLightmapStreamingPriorityForPlatformGroup(BuildTargetGroup platformGroup);
[FreeFunction("GetPlayerSettings().SetLightmapStreamingPriority")]
internal static extern void SetLightmapStreamingPriorityForPlatformGroup(BuildTargetGroup platformGroup, int lightmapStreamingPriority);
[FreeFunction("GetPlayerSettings().GetLoadStoreDebugModeEnabled")]
internal static extern bool GetLoadStoreDebugModeEnabledForPlatformGroup(BuildTargetGroup platformGroup);
[FreeFunction("GetPlayerSettings().SetLoadStoreDebugModeEnabled")]
internal static extern void SetLoadStoreDebugModeEnabledForPlatformGroup(BuildTargetGroup platformGroup, bool loadStoreDebugModeEnabled);
[FreeFunction("GetPlayerSettings().GetLoadStoreDebugModeEditorOnly")]
internal static extern bool GetLoadStoreDebugModeEditorOnlyForPlatformGroup(BuildTargetGroup platformGroup);
[FreeFunction("GetPlayerSettings().SetLoadStoreDebugModeEditorOnly")]
internal static extern void SetLoadStoreDebugModeEditorOnlyForPlatformGroup(BuildTargetGroup platformGroup, bool loadStoreDebugModeEnabled);
[FreeFunction("GetPlayerSettings().GetDisableOldInputManagerSupport")]
internal static extern bool GetDisableOldInputManagerSupport();
[FreeFunction("GetPlayerSettings().GetWindowsGamepadBackendHint")]
internal static extern WindowsGamepadBackendHint GetWindowsGamepadBackendHint();
[FreeFunction("GetPlayerSettings().SetWindowsGamepadBackendHint")]
internal static extern void SetWindowsGamepadBackendHint(WindowsGamepadBackendHint value);
// The input API backend used on Windows platforms
public static WindowsGamepadBackendHint windowsGamepadBackendHint
{
get { return GetWindowsGamepadBackendHint(); }
set { SetWindowsGamepadBackendHint(value); }
}
[StaticAccessor("GetPlayerSettings()")]
[NativeMethod("GetVirtualTexturingSupportEnabled")]
public static extern bool GetVirtualTexturingSupportEnabled();
[StaticAccessor("GetPlayerSettings()")]
[NativeMethod("SetVirtualTexturingSupportEnabled")]
public static extern void SetVirtualTexturingSupportEnabled(bool enabled);
[StaticAccessor("GetPlayerSettings()")]
[NativeMethod("OnVirtualTexturingChanged")]
internal static extern bool OnVirtualTexturingChanged();
public static extern InsecureHttpOption insecureHttpOption { get; set; }
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
public static extern ShaderPrecisionModel GetShaderPrecisionModel();
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
public static extern void SetShaderPrecisionModel(ShaderPrecisionModel model);
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
internal static extern TextureCompressionFormat GetDefaultTextureCompressionFormat(BuildTarget platform);
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
internal static extern void SetDefaultTextureCompressionFormat(BuildTarget platform, TextureCompressionFormat format);
[NativeMethod("GetTextureCompressionFormats")]
[StaticAccessor("GetPlayerSettings().GetEditorOnly()")]
internal static extern TextureCompressionFormat[] GetTextureCompressionFormatsImpl(BuildTarget platform);
[NativeMethod("SetTextureCompressionFormats")]
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()")]
internal static extern void SetTextureCompressionFormatsImpl(BuildTarget platform, TextureCompressionFormat[] formats);
[FreeFunction("GetPlayerSettings().GetEditorOnly().RecompileScripts")]
internal static extern void RecompileScripts(string reason, bool refreshProject = true);
internal static extern bool isHandlingScriptRecompile
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)]
set;
}
// note that we dont expose it in ui (yet) and keep it hidden on purpose
// when the time comes we can totally rename this before making it public
[NativeProperty("IOSCopyPluginsCodeInsteadOfSymlink")]
internal static extern bool iosCopyPluginsCodeInsteadOfSymlink
{
[StaticAccessor("GetPlayerSettings().GetEditorOnly()", StaticAccessorType.Dot)]
get;
[StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)]
set;
}
internal static extern bool platformRequiresReadableAssets { get; set; }
}
}
| UnityCsReference/Editor/Mono/PlayerSettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PlayerSettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 28152
} | 329 |
// 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 System;
namespace UnityEditor
{
public partial class PlayerSettings : UnityEngine.Object
{
public static extern bool vulkanEnableSetSRGBWrite { get; set; }
public static extern UInt32 vulkanNumSwapchainBuffers { get; set; }
public static extern bool vulkanEnableLateAcquireNextImage { get; set; }
[Obsolete("Vulkan SW command buffers are deprecated, vulkanUseSWCommandBuffers will be ignored.")]
public static bool vulkanUseSWCommandBuffers { get { return false; } set {} }
public static extern bool vulkanEnablePreTransform { get; set; }
}
}
| UnityCsReference/Editor/Mono/PlayerSettingsVulkan.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PlayerSettingsVulkan.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 257
} | 330 |
// Unity 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.IMGUI.Controls;
using UnityEditor.SceneManagement;
using Object = UnityEngine.Object;
namespace UnityEditor
{
class PrefabOverridesTreeView : TreeView
{
PrefabOverrides m_AllModifications;
bool m_Debug = false;
string m_PrefabAssetPath { get; set; }
GameObject m_PrefabInstanceRoot { get; set; }
GameObject m_PrefabAssetRoot { get; set; }
int m_LastShownPreviewWindowRowID = -1;
PrefabOverridesWindow m_Window;
enum ToggleValue { FALSE, TRUE, MIXED }
enum ItemType { PREFAB_OBJECT, ADDED_OBJECT, REMOVED_OBJECT }
class PrefabOverridesTreeViewItem : TreeViewItem
{
public PrefabOverridesTreeViewItem(int id, int depth, string displayName) : base(id, depth, displayName)
{
}
public PrefabOverride singleModification;
public Texture overlayIcon;
public ToggleValue included { get; set; }
public ItemType type
{
get { return m_Type; }
set
{
m_Type = value;
overlayIcon = null;
if (m_Type == ItemType.ADDED_OBJECT)
overlayIcon = EditorGUIUtility.IconContent("PrefabOverlayAdded Icon").image;
else if (m_Type == ItemType.REMOVED_OBJECT)
overlayIcon = EditorGUIUtility.IconContent("PrefabOverlayRemoved Icon").image;
}
}
ItemType m_Type;
public Object obj
{
get { return m_Obj; }
set
{
m_Obj = value;
icon = (m_Obj is GameObject) ? PrefabUtility.GetIconForGameObject((GameObject)m_Obj) : AssetPreview.GetMiniThumbnail(m_Obj);
}
}
Object m_Obj;
public string propertyPath { get; set; }
}
// Represents all possible modifications to a Prefab instance.
class PrefabOverrides
{
List<ObjectOverride> m_ObjectOverrides = new List<ObjectOverride>();
List<AddedComponent> m_AddedComponents = new List<AddedComponent>();
List<RemovedComponent> m_RemovedComponents = new List<RemovedComponent>();
List<AddedGameObject> m_AddedGameObjects = new List<AddedGameObject>();
List<RemovedGameObject> m_RemovedGameObjects = new List<RemovedGameObject>();
public List<ObjectOverride> objectOverrides { get { return m_ObjectOverrides; } set { m_ObjectOverrides = value; } }
public List<AddedComponent> addedComponents { get { return m_AddedComponents; } set { m_AddedComponents = value; } }
public List<RemovedComponent> removedComponents { get { return m_RemovedComponents; } set { m_RemovedComponents = value; } }
public List<AddedGameObject> addedGameObjects { get { return m_AddedGameObjects; } set { m_AddedGameObjects = value; } }
public List<RemovedGameObject> removedGameObjects { get { return m_RemovedGameObjects; } set { m_RemovedGameObjects = value; } }
}
static PrefabOverrides GetPrefabOverrides(GameObject prefabInstance, bool includeDefaultOverrides = false)
{
if (!PrefabUtility.IsPartOfNonAssetPrefabInstance(prefabInstance))
{
Debug.LogError("GeneratePrefabOverrides should only be called with GameObjects that are part of a prefab");
return new PrefabOverrides();
}
var mods = new PrefabOverrides();
mods.objectOverrides = PrefabOverridesUtility.GetObjectOverrides(prefabInstance, includeDefaultOverrides);
mods.addedComponents = PrefabOverridesUtility.GetAddedComponents(prefabInstance);
mods.removedComponents = PrefabOverridesUtility.GetRemovedComponents(prefabInstance);
mods.addedGameObjects = PrefabOverridesUtility.GetAddedGameObjects(prefabInstance);
mods.removedGameObjects = PrefabOverridesUtility.GetRemovedGameObjects(prefabInstance);
return mods;
}
public bool hasModifications { get; private set; }
public bool hasApplicableModifications { get; private set; }
public bool IsValidTargetPrefabInstance()
{
if (m_PrefabInstanceRoot == null)
return false;
return PrefabUtility.GetPrefabInstanceStatus(m_PrefabInstanceRoot) == PrefabInstanceStatus.Connected;
}
public PrefabOverridesTreeView(GameObject selectedGameObject, TreeViewState state, PrefabOverridesWindow window) : base(state)
{
m_SelectedGameObject = selectedGameObject;
m_Window = window;
rowHeight = 18f;
enableItemHovering = true;
}
public void SetApplyTarget(GameObject prefabInstanceRoot, GameObject prefabAssetRoot, string prefabAssetPath)
{
m_PrefabInstanceRoot = prefabInstanceRoot;
m_PrefabAssetRoot = prefabAssetRoot;
m_PrefabAssetPath = prefabAssetPath;
Reload();
ExpandAll();
EnableAllItems(true);
}
public void CullNonExistingItemsFromSelection()
{
for (int i = state.selectedIDs.Count - 1; i >= 0; i--)
{
if (TreeViewUtility.FindItem(state.selectedIDs[i], rootItem) == null)
state.selectedIDs.RemoveAt(i);
}
if (state.selectedIDs.Count != 1 && PopupWindowWithoutFocus.IsVisible())
PopupWindowWithoutFocus.Hide();
}
void BuildPrefabOverridesPerObject(out Dictionary<int, PrefabOverrides> instanceIDToPrefabOverridesMap)
{
instanceIDToPrefabOverridesMap = new Dictionary<int, PrefabOverrides>();
foreach (var modifiedObject in m_AllModifications.objectOverrides)
{
int instanceID = 0;
if (modifiedObject.instanceObject is GameObject)
instanceID = modifiedObject.instanceObject.GetInstanceID();
else if (modifiedObject.instanceObject is Component)
instanceID = ((Component)modifiedObject.instanceObject).gameObject.GetInstanceID();
if (instanceID != 0)
{
PrefabOverrides modificationsForObject = GetPrefabOverridesForObject(instanceID, instanceIDToPrefabOverridesMap);
modificationsForObject.objectOverrides.Add(modifiedObject);
}
}
foreach (var addedGameObject in m_AllModifications.addedGameObjects)
{
int instanceID = addedGameObject.instanceGameObject.GetInstanceID();
PrefabOverrides modificationsForObject = GetPrefabOverridesForObject(instanceID, instanceIDToPrefabOverridesMap);
modificationsForObject.addedGameObjects.Add(addedGameObject);
}
foreach (var removedGameObject in m_AllModifications.removedGameObjects)
{
int instanceID = removedGameObject.parentOfRemovedGameObjectInInstance.gameObject.GetInstanceID();
PrefabOverrides modificationsForObject = GetPrefabOverridesForObject(instanceID, instanceIDToPrefabOverridesMap);
modificationsForObject.removedGameObjects.Add(removedGameObject);
}
foreach (var addedComponent in m_AllModifications.addedComponents)
{
// This is possible if there's a component with a missing script.
if (addedComponent.instanceComponent == null)
continue;
int instanceID = addedComponent.instanceComponent.gameObject.GetInstanceID();
PrefabOverrides modificationsForObject = GetPrefabOverridesForObject(instanceID, instanceIDToPrefabOverridesMap);
modificationsForObject.addedComponents.Add(addedComponent);
}
foreach (var removedComponent in m_AllModifications.removedComponents)
{
// This is possible if there's a component with a missing script.
if (removedComponent.assetComponent == null)
continue;
int instanceID = removedComponent.containingInstanceGameObject.gameObject.GetInstanceID();
PrefabOverrides modificationsForObject = GetPrefabOverridesForObject(instanceID, instanceIDToPrefabOverridesMap);
modificationsForObject.removedComponents.Add(removedComponent);
}
}
internal void ComparisonPopupClosed(Object instanceObject, bool ownerNeedsRefresh)
{
if(ownerNeedsRefresh)
ReloadOverridesDisplay();
if (instanceObject != null && instanceObject is GameObject)
SyncTreeViewItemNameForGameObject((GameObject)instanceObject);
}
void SyncTreeViewItemNameForGameObject(GameObject gameObject)
{
if (gameObject == null)
return;
foreach (var item in GetRows())
{
var poItem = item as PrefabOverridesTreeViewItem;
if (poItem != null && poItem.obj == gameObject)
{
item.displayName = poItem.obj.name;
Repaint();
return;
}
}
}
protected override TreeViewItem BuildRoot()
{
Debug.Assert(m_PrefabInstanceRoot != null, "We should always have a valid apply target");
// Inner prefab asset root.
m_AllModifications = GetPrefabOverrides(m_PrefabInstanceRoot, false);
Dictionary<int, PrefabOverrides> instanceIDToPrefabOverridesMap;
BuildPrefabOverridesPerObject(out instanceIDToPrefabOverridesMap);
var hiddenRoot = new TreeViewItem { id = 0, depth = -1, displayName = "Hidden Root" };
var idSequence = new IdSequence();
hasApplicableModifications = false;
hasModifications = AddTreeViewItemRecursive(hiddenRoot, m_PrefabInstanceRoot, instanceIDToPrefabOverridesMap, idSequence);
if (!hasModifications)
hiddenRoot.AddChild(new TreeViewItem { id = 1, depth = 0, displayName = "No Overrides" });
else
{
bool CanAnyPropertiesBeApplied()
{
if (m_AllModifications.addedComponents.Count != 0 || m_AllModifications.removedComponents.Count != 0 || m_AllModifications.addedGameObjects.Count != 0 || m_AllModifications.removedGameObjects.Count != 0)
return true;
foreach (var objectOverride in m_AllModifications.objectOverrides)
{
if (PrefabUtility.HasApplicableObjectOverrides(objectOverride.instanceObject, false))
return true;
}
return false;
}
hasApplicableModifications = CanAnyPropertiesBeApplied();
}
if (m_Debug)
AddDebugItems(hiddenRoot, idSequence);
return hiddenRoot;
}
void AddDebugItems(TreeViewItem hiddenRoot, IdSequence idSequence)
{
var debugItem = new TreeViewItem(idSequence.get(), 0, "<Debug raw list of modifications>");
foreach (var mod in m_AllModifications.addedGameObjects)
debugItem.AddChild(new TreeViewItem(idSequence.get(), debugItem.depth + 1, mod.instanceGameObject.name + " (Added GameObject)"));
foreach (var mod in m_AllModifications.removedGameObjects)
debugItem.AddChild(new TreeViewItem(idSequence.get(), debugItem.depth + 1, mod.assetGameObject.name + " (Removed GameObject)"));
foreach (var mod in m_AllModifications.addedComponents)
debugItem.AddChild(new TreeViewItem(idSequence.get(), debugItem.depth + 1, mod.instanceComponent.GetType() + " (Added Component)"));
foreach (var mod in m_AllModifications.removedComponents)
debugItem.AddChild(new TreeViewItem(idSequence.get(), debugItem.depth + 1, mod.assetComponent.GetType() + " (Removed Component)"));
hiddenRoot.AddChild(new TreeViewItem()); // spacer
hiddenRoot.AddChild(debugItem);
}
// Returns true if input gameobject or any of its descendants have modifications, otherwise returns false.
bool AddTreeViewItemRecursive(TreeViewItem parentItem, GameObject gameObject, Dictionary<int, PrefabOverrides> prefabOverrideMap, IdSequence idSequence)
{
var gameObjectItem = new PrefabOverridesTreeViewItem
(
gameObject.GetInstanceID(),
parentItem.depth + 1,
gameObject.name
);
gameObjectItem.obj = gameObject;
// We don't know yet if this item should be added to the parent.
bool shouldAddGameObjectItemToParent = false;
PrefabOverrides objectModifications;
prefabOverrideMap.TryGetValue(gameObject.GetInstanceID(), out objectModifications);
if (objectModifications != null)
{
// Added GameObject - note that this earlies out!
AddedGameObject addedGameObjectData = objectModifications.addedGameObjects.Find(x => x.instanceGameObject == gameObject);
if (addedGameObjectData != null)
{
gameObjectItem.singleModification = addedGameObjectData;
gameObjectItem.type = ItemType.ADDED_OBJECT;
parentItem.AddChild(gameObjectItem);
return true;
}
else
{
// Modified GameObject
ObjectOverride modifiedGameObjectData = objectModifications.objectOverrides.Find(x => x.instanceObject == gameObject);
if (modifiedGameObjectData != null)
{
gameObjectItem.singleModification = modifiedGameObjectData;
gameObjectItem.type = ItemType.PREFAB_OBJECT;
shouldAddGameObjectItemToParent = true;
}
}
// Added components and component modifications
foreach (var component in gameObject.GetComponents(typeof(Component)))
{
// GetComponents will return Missing Script components as null, we will skip them here to prevent NullReferenceExceptions. (case 1197599)
if (component == null)
continue;
// Skip coupled components (they are merged into the display of their owning component)
if (component.IsCoupledComponent())
continue;
var componentItem = new PrefabOverridesTreeViewItem
(
component.GetInstanceID(),
gameObjectItem.depth + 1,
ObjectNames.GetInspectorTitle(component)
);
componentItem.obj = component;
AddedComponent addedComponentData = objectModifications.addedComponents.Find(x => x.instanceComponent == component);
if (addedComponentData != null)
{
// Skip coupled components (they are merged into the display of their owning component)
if (addedComponentData.instanceComponent.IsCoupledComponent())
continue;
componentItem.singleModification = addedComponentData;
componentItem.type = ItemType.ADDED_OBJECT;
gameObjectItem.AddChild(componentItem);
shouldAddGameObjectItemToParent = true;
}
else
{
var coupledComponent = component.GetCoupledComponent();
ObjectOverride modifiedObjectData = objectModifications.objectOverrides.Find(x => x.instanceObject == component);
ObjectOverride modifiedCoupledObjectData = (coupledComponent != null) ? objectModifications.objectOverrides.Find(x => x.instanceObject == coupledComponent) : null;
if (modifiedObjectData != null || modifiedCoupledObjectData != null)
{
// If only the coupled component has modifications, create an
// ObjectOverride object for the main component since it doesn't exist yet.
if (modifiedObjectData == null)
modifiedObjectData = new ObjectOverride() { instanceObject = component };
modifiedObjectData.coupledOverride = modifiedCoupledObjectData;
componentItem.singleModification = modifiedObjectData;
componentItem.type = ItemType.PREFAB_OBJECT;
gameObjectItem.AddChild(componentItem);
shouldAddGameObjectItemToParent = true;
}
}
}
// Removed components
foreach (var removedComponent in objectModifications.removedComponents)
{
// Skip coupled components (they are merged into the display of their owning component)
if (removedComponent.assetComponent.IsCoupledComponent())
continue;
var removedComponentItem = new PrefabOverridesTreeViewItem
(
idSequence.get(),
gameObjectItem.depth + 1,
ObjectNames.GetInspectorTitle(removedComponent.assetComponent)
);
removedComponentItem.obj = removedComponent.assetComponent;
removedComponentItem.singleModification = removedComponent;
removedComponentItem.type = ItemType.REMOVED_OBJECT;
gameObjectItem.AddChild(removedComponentItem);
shouldAddGameObjectItemToParent = true;
}
}
// Recurse into children
foreach (Transform childTransform in gameObject.transform)
{
var childGameObject = childTransform.gameObject;
shouldAddGameObjectItemToParent |= AddTreeViewItemRecursive(gameObjectItem, childGameObject, prefabOverrideMap, idSequence);
}
if (objectModifications != null)
{
// Removed GameObjects
foreach (var removedGameObject in objectModifications.removedGameObjects)
{
string objectName = removedGameObject.assetGameObject.name;
var instanceModifications = PrefabUtility.GetPropertyModifications(gameObject);
foreach (var mod in instanceModifications)
{
if (mod.target == removedGameObject.assetGameObject && mod.propertyPath == "m_Name")
{
objectName = mod.value;
break;
}
}
var removedGameObjectItem = new PrefabOverridesTreeViewItem
(
idSequence.get(),
gameObjectItem.depth + 1,
objectName
);
removedGameObjectItem.obj = removedGameObject.assetGameObject;
removedGameObjectItem.singleModification = removedGameObject;
removedGameObjectItem.type = ItemType.REMOVED_OBJECT;
gameObjectItem.AddChild(removedGameObjectItem);
shouldAddGameObjectItemToParent = true;
}
}
if (shouldAddGameObjectItemToParent)
{
parentItem.AddChild(gameObjectItem);
if (maxDepthItem == null || gameObjectItem.depth > maxDepthItem.depth)
maxDepthItem = gameObjectItem;
return true;
}
return false;
}
static PrefabOverrides GetPrefabOverridesForObject(int instanceID, Dictionary<int, PrefabOverrides> map)
{
PrefabOverrides modificationsForObject;
if (!map.TryGetValue(instanceID, out modificationsForObject))
{
modificationsForObject = new PrefabOverrides();
map[instanceID] = modificationsForObject;
}
return modificationsForObject;
}
public void EnableAllItems(bool enable)
{
var topItem = rootItem.children[0] as PrefabOverridesTreeViewItem;
if (topItem != null)
UpdateChildrenIncludedState(topItem, enable);
}
static void UpdateChildrenIncludedState(PrefabOverridesTreeViewItem item, bool v)
{
item.included = v ? ToggleValue.TRUE : ToggleValue.FALSE;
if (item.hasChildren)
{
foreach (var child in item.children)
{
UpdateChildrenIncludedState(child as PrefabOverridesTreeViewItem, v);
}
}
}
protected override void RowGUI(RowGUIArgs args)
{
baseIndent = 4f;
var item = args.item as PrefabOverridesTreeViewItem;
if (item == null)
return;
// Grey out items that does not have overrides
using (new EditorGUI.DisabledScope(item.singleModification == null))
{
base.RowGUI(args);
}
// Draw overlay icon.
if (Event.current.type == EventType.Repaint)
{
if (item.overlayIcon != null)
{
Rect rect = GetRowRect(args.row);
rect.xMin += GetContentIndent(args.item);
rect.width = 16;
GUI.DrawTexture(rect, item.overlayIcon, ScaleMode.ScaleToFit);
}
}
}
internal void ReloadOverridesDisplay()
{
// Driven properties are ignored when collecting overrides.
// Properties that affect which properties are driven may have changed
// due to an apply or revert since we last reloaded the overrides display.
// Execute a layout call to get driven properties into a stable state
// before collecting overrides.
Canvas.ForceUpdateCanvases();
if (m_Window != null)
m_Window.RefreshStatus();
}
protected override void SelectionChanged(IList<int> selectedIds)
{
DoPreviewPopup();
}
protected override void SingleClickedItem(int id)
{
// Ensure preview is shown when clicking on an already selected item
// (the preview might have been closed).
DoPreviewPopup();
}
void DoPreviewPopup()
{
if (state.selectedIDs.Count != 1)
{
PopupWindowWithoutFocus.Hide();
return;
}
var item = FindItem(state.selectedIDs[0], rootItem) as PrefabOverridesTreeViewItem;
if (item == null || item.obj == null)
return;
if (PopupWindowWithoutFocus.IsVisible())
{
if (item.id == m_LastShownPreviewWindowRowID)
return;
}
int row = FindRowOfItem(item);
if (row == -1)
return;
Rect buttonRect = GetRowRect(row);
buttonRect.width = EditorGUIUtility.currentViewWidth;
Object rowObject = item.obj;
Object instance, source;
if (item.type == ItemType.REMOVED_OBJECT)
{
instance = null;
source = rowObject;
}
else if (item.type == ItemType.ADDED_OBJECT)
{
instance = rowObject;
source = null;
}
else
{
instance = rowObject;
source = PrefabUtility.GetCorrespondingObjectFromSource(rowObject);
}
m_LastShownPreviewWindowRowID = item.id;
PopupWindowWithoutFocus.Show(
buttonRect,
new ComparisonViewPopup(source, instance, item.singleModification, this),
new[] { PopupLocation.Right, PopupLocation.Left, PopupLocation.Below });
}
public GameObject selectedGameObject
{
get { return m_SelectedGameObject; }
}
GameObject m_SelectedGameObject;
public float maxItemWidth { get { return maxDepthItem != null ? GetContentIndent(maxDepthItem) + k_FixedContentWidth : 0; } }
const float k_FixedContentWidth = 150f;
TreeViewItem maxDepthItem { get; set; }
struct ChangedModification
{
public Object target { get; set; }
public string propertyPath { get; set; }
}
public PrefabOverride FindOverride(int itemId)
{
var item = FindItem(itemId, rootItem) as PrefabOverridesTreeViewItem;
if (item == null)
return null;
return item.singleModification;
}
class IdSequence
{
public int get() { return m_NextId++; }
int m_NextId = 1;
}
class ComparisonViewPopup : PopupWindowContent
{
readonly PrefabOverridesTreeView m_Owner;
readonly PrefabOverride m_Modification;
readonly Object m_Source;
readonly Object m_Instance;
readonly Editor m_SourceEditor;
readonly Editor m_InstanceEditor;
readonly bool m_Unappliable;
const float k_HeaderHeight = 25f;
const float k_ScrollbarWidth = 13;
Vector2 m_PreviewSize = new Vector2(600f, 0);
Vector2 m_Scroll;
bool m_RenderOverlayAfterResizeChange;
bool m_OwnerNeedsRefresh;
static class Styles
{
public static GUIStyle borderStyle = new GUIStyle("grey_border");
public static GUIStyle centeredLabelStyle = new GUIStyle(EditorStyles.label);
public static GUIStyle headerGroupStyle = new GUIStyle();
public static GUIStyle headerStyle = new GUIStyle(EditorStyles.boldLabel);
public static GUIContent sourceContent = EditorGUIUtility.TrTextContent("Prefab Source");
public static GUIContent instanceContent = EditorGUIUtility.TrTextContent("Override");
public static GUIContent removedContent = EditorGUIUtility.TrTextContent("Removed");
public static GUIContent addedContent = EditorGUIUtility.TrTextContent("Added");
public static GUIContent noModificationsContent = EditorGUIUtility.TrTextContent("No Overrides");
public static GUIContent applyContent = EditorGUIUtility.TrTextContent("Apply", "Apply overrides on this object.");
public static GUIContent revertContent = EditorGUIUtility.TrTextContent("Revert", "Revert overrides on this object.");
static Styles()
{
centeredLabelStyle.alignment = TextAnchor.UpperCenter;
centeredLabelStyle.padding = new RectOffset(3, 3, 3, 3);
headerGroupStyle.padding = new RectOffset(0, 0, 3, 3);
headerStyle.alignment = TextAnchor.MiddleLeft;
headerStyle.padding.left = 5;
headerStyle.padding.top = 1;
}
}
public ComparisonViewPopup(Object source, Object instance, PrefabOverride modification, PrefabOverridesTreeView owner)
{
m_Owner = owner;
m_Source = source;
m_Instance = instance;
m_Modification = modification;
if (modification != null)
{
m_Unappliable = !PrefabUtility.IsPartOfPrefabThatCanBeAppliedTo(modification.GetAssetObject());
}
else
{
m_Unappliable = false;
}
if (m_Source != null)
{
m_SourceEditor = Editor.CreateEditor(m_Source);
}
if (m_Instance != null)
{
m_InstanceEditor = Editor.CreateEditor(m_Instance);
}
if (m_Source == null || m_Instance == null || m_Modification == null)
m_PreviewSize.x /= 2;
if (modification is ObjectOverride)
Undo.postprocessModifications += RecheckOverrideStatus;
}
public override void OnClose()
{
Undo.postprocessModifications -= RecheckOverrideStatus;
m_Owner.ComparisonPopupClosed(m_Instance, m_OwnerNeedsRefresh);
base.OnClose();
if (m_SourceEditor != null)
Object.DestroyImmediate(m_SourceEditor);
if (m_InstanceEditor != null)
Object.DestroyImmediate(m_InstanceEditor);
}
UndoPropertyModification[] RecheckOverrideStatus(UndoPropertyModification[] modifications)
{
if (m_Instance == null || !PrefabUtility.HasObjectOverride(m_Instance))
{
// Delay update and close since if there's multiple undo events, RecheckOverrideStatus
// gets called for each, and we only want to recheck after the last one.
// This fixes an issue where the tree view would still show a component with no more
// modifications on it, if it was a component with a coupled component.
EditorApplication.tick -= UpdateAndCloseOnNextTick;
EditorApplication.tick += UpdateAndCloseOnNextTick;
}
return modifications;
}
void UpdateAndCloseOnNextTick()
{
EditorApplication.tick -= UpdateAndCloseOnNextTick;
UpdateAndClose();
}
bool UpdatePreviewHeight(float height)
{
if (height > 0 && m_PreviewSize.y != height)
{
m_PreviewSize.y = height;
return true;
}
return false;
}
public override void OnGUI(Rect rect)
{
bool scroll = (m_PreviewSize.y > rect.height - k_HeaderHeight);
if (scroll)
rect.width -= k_ScrollbarWidth + 1;
else
// We overdraw border by one pixel to the right, so subtract here to account for that.
rect.width -= 1;
EditorGUIUtility.wideMode = true;
EditorGUIUtility.labelWidth = 120;
int middleCol = Mathf.RoundToInt((rect.width - 1) * 0.5f);
if (Event.current.type == EventType.Repaint)
EditorStyles.viewBackground.Draw(rect, GUIContent.none, 0);
if (m_Modification == null)
{
DrawHeader(
new Rect(rect.x, rect.y, rect.width, k_HeaderHeight),
Styles.noModificationsContent);
m_PreviewSize.y = 0;
return;
}
Rect scrollRectPosition =
new Rect(
rect.x,
rect.y + k_HeaderHeight,
rect.width + (scroll ? k_ScrollbarWidth : 0),
rect.height - k_HeaderHeight);
Rect viewPosition = new Rect(0, 0, rect.width, m_PreviewSize.y);
if (m_Source != null && m_Instance != null)
{
Rect sourceHeaderRect = new Rect(rect.x, rect.y, middleCol, k_HeaderHeight);
Rect instanceHeaderRect = new Rect(rect.x + middleCol, rect.y, rect.xMax - middleCol + (scroll ? k_ScrollbarWidth : 0), k_HeaderHeight);
DrawHeader(sourceHeaderRect, Styles.sourceContent);
DrawHeader(instanceHeaderRect, Styles.instanceContent);
DrawRevertApplyButtons(instanceHeaderRect);
m_Scroll = GUI.BeginScrollView(scrollRectPosition, m_Scroll, viewPosition);
{
var leftColumnHeight = DrawEditor(new Rect(0, 0, middleCol, m_PreviewSize.y), m_SourceEditor, true, EditorGUIUtility.ComparisonViewMode.Original);
var rightColumnHeight = DrawEditor(new Rect(middleCol, 0, rect.xMax - middleCol, m_PreviewSize.y), m_InstanceEditor, false, EditorGUIUtility.ComparisonViewMode.Modified);
if (UpdatePreviewHeight(Math.Max(leftColumnHeight, rightColumnHeight)))
m_RenderOverlayAfterResizeChange = true;
}
GUI.EndScrollView();
}
else
{
GUIContent headerContent;
Editor editor;
bool disable;
if (m_Source != null)
{
headerContent = Styles.removedContent;
editor = m_SourceEditor;
disable = true;
}
else
{
headerContent = Styles.addedContent;
editor = m_InstanceEditor;
disable = false;
}
Rect headerRect = new Rect(rect.x, rect.y, rect.width, k_HeaderHeight);
DrawHeader(headerRect, headerContent);
DrawRevertApplyButtons(headerRect);
m_Scroll = GUI.BeginScrollView(scrollRectPosition, m_Scroll, viewPosition);
float columnHeight = DrawEditor(new Rect(0, 0, rect.width, m_PreviewSize.y), editor, disable, EditorGUIUtility.ComparisonViewMode.Modified);
if (UpdatePreviewHeight(columnHeight))
m_RenderOverlayAfterResizeChange = true;
GUI.EndScrollView();
}
if (m_RenderOverlayAfterResizeChange && Event.current.type == EventType.Repaint)
{
m_RenderOverlayAfterResizeChange = false;
// The comparison view resizes a frame delayed due to having to wait for the first render to
// layout the contents. This creates a distorted rendering because the last frame rendered is rendered
// to the new window size. We therefore 'clear' the comparison view after a resize change by rendering
// a quad on top with the background color so the distorted rendering is not shown to the user.
// Fixes case 1069062.
GUI.Label(rect, GUIContent.none, EditorStyles.viewBackground);
editorWindow.Repaint();
}
}
void DrawHeader(Rect rect, GUIContent label)
{
EditorGUI.LabelField(rect, label, Styles.headerStyle);
// Overdraw border by one pixel to the right, so adjacent borders overlap.
// Don't overdraw down, since overlapping scroll view can make controls overlap divider line.
GUI.Label(new Rect(rect.x, rect.y, rect.width + 1, rect.height), GUIContent.none, Styles.borderStyle);
}
void DrawRevertApplyButtons(Rect rect)
{
GUILayout.BeginArea(rect);
GUILayout.BeginHorizontal(Styles.headerGroupStyle);
GUILayout.FlexibleSpace();
if (GUILayout.Button(Styles.revertContent, EditorStyles.miniButton, GUILayout.Width(55)))
{
m_Modification.Revert();
UpdateAndClose();
GUIUtility.ExitGUI();
}
using (new EditorGUI.DisabledScope(m_Unappliable))
{
Rect applyRect = GUILayoutUtility.GetRect(GUIContent.none, "MiniPulldown", GUILayout.Width(55));
if (EditorGUI.DropdownButton(applyRect, Styles.applyContent, FocusType.Passive))
{
GenericMenu menu = new GenericMenu();
m_Modification.HandleApplyMenuItems(menu, Apply);
menu.DropDown(applyRect);
}
}
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
void Apply(object prefabAssetPathObject)
{
string prefabAssetPath = (string)prefabAssetPathObject;
if (!PrefabUtility.PromptAndCheckoutPrefabIfNeeded(prefabAssetPath, PrefabUtility.SaveVerb.Apply))
return;
m_Modification.Apply(prefabAssetPath);
EditorUtility.ForceRebuildInspectors(); // handles applying RemovedComponents
UpdateAndClose();
}
void UpdateAndClose()
{
m_OwnerNeedsRefresh = true;
editorWindow?.Close();
}
float DrawEditor(Rect rect, Editor editor, bool disabled, EditorGUIUtility.ComparisonViewMode comparisonViewMode)
{
rect.xMin += 1;
EditorGUIUtility.ResetGUIState();
EditorGUIUtility.wideMode = true;
EditorGUIUtility.labelWidth = 120;
EditorGUIUtility.comparisonViewMode = comparisonViewMode;
EditorGUIUtility.leftMarginCoord = rect.x;
GUILayout.BeginArea(rect);
Rect editorRect = EditorGUILayout.BeginVertical();
{
using (new EditorGUI.DisabledScope(disabled))
{
if (editor == null)
{
GUI.enabled = true;
GUILayout.Label("None - this should not happen.", Styles.centeredLabelStyle);
}
else
{
EditorGUI.BeginChangeCheck();
if (editor.target is GameObject)
{
editor.DrawHeader();
}
else
{
EditorGUIUtility.hierarchyMode = true;
EditorGUILayout.InspectorTitlebar(true, editor);
EditorGUILayout.BeginVertical(EditorStyles.inspectorDefaultMargins);
editor.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
}
if (EditorGUI.EndChangeCheck())
m_OwnerNeedsRefresh = true;
}
}
}
EditorGUILayout.EndVertical();
GUILayout.EndArea();
// Overdraw border by one pixel in all directions.
GUI.Label(new Rect(rect.x - 1, -1, rect.width + 2, m_PreviewSize.y + 2), GUIContent.none, Styles.borderStyle);
return editorRect.height;
}
public override Vector2 GetWindowSize()
{
return new Vector2(m_PreviewSize.x, m_PreviewSize.y + k_HeaderHeight + 1f);
}
}
}
}
| UnityCsReference/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverridesTreeView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Prefabs/PrefabOverrides/PrefabOverridesTreeView.cs",
"repo_id": "UnityCsReference",
"token_count": 20168
} | 331 |
// 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<DoubleCurvePresetLibrary> 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<DoubleCurve> m_PresetSelectedCallback;
public DoubleCurvePresetsContentsForPopupWindow(DoubleCurve doubleCurveToSave, System.Action<DoubleCurve> presetSelectedCallback)
{
m_DoubleCurve = doubleCurveToSave;
m_PresetSelectedCallback = presetSelectedCallback;
}
public override void OnClose()
{
m_CurveLibraryEditorState.TransferEditorPrefsState(false);
}
public PresetLibraryEditor<DoubleCurvePresetLibrary> 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<DoubleCurvePresetLibrary>(extension, SaveType.Text);
m_CurveLibraryEditor = new PresetLibraryEditor<DoubleCurvePresetLibrary>(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<DoubleCurve> defaults = new List<DoubleCurve>();
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<DoubleCurve> GetUnsignedSingleCurveDefaults(bool signedRange)
{
List<DoubleCurve> defaults = new List<DoubleCurve>();
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<DoubleCurve> GetUnsignedDoubleCurveDefaults()
{
List<DoubleCurve> defaults = new List<DoubleCurve>();
defaults.Add(new DoubleCurve(new AnimationCurve(CurveEditorWindow.GetConstantKeys(0f)), new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), false));
return defaults;
}
static List<DoubleCurve> GetSignedDoubleCurveDefaults()
{
List<DoubleCurve> defaults = new List<DoubleCurve>();
defaults.Add(new DoubleCurve(new AnimationCurve(CurveEditorWindow.GetConstantKeys(-1f)), new AnimationCurve(CurveEditorWindow.GetConstantKeys(1f)), true));
return defaults;
}
}
}
| UnityCsReference/Editor/Mono/PresetLibraries/DoubleCurvePresetsContentsForPopupWindow.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PresetLibraries/DoubleCurvePresetsContentsForPopupWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 2944
} | 332 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEditorInternal;
using System.Collections.Generic;
using System.Linq;
namespace UnityEditor
{
internal class PopupList : PopupWindowContent
{
public delegate void OnSelectCallback(ListElement element);
static EditorGUI.RecycledTextEditor s_RecycledEditor = new EditorGUI.RecycledTextEditor();
static string s_TextFieldName = "ProjectBrowserPopupsTextField";
static int s_TextFieldHash = s_TextFieldName.GetHashCode();
public enum Gravity
{
Top,
Bottom
}
public class ListElement
{
public GUIContent m_Content;
private float m_FilterScore;
private bool m_Selected;
private bool m_WasSelected;
private bool m_PartiallySelected;
private bool m_Enabled;
private string[] m_Types;
public ListElement(string text, bool selected, float score) : this(text, new [] { text }, selected, score) { }
public ListElement(string text, string[] types, bool selected, float score)
{
m_Content = new GUIContent(text);
if (!string.IsNullOrEmpty(m_Content.text))
{
char[] a = m_Content.text.ToCharArray();
a[0] = char.ToUpper(a[0]);
m_Content.text = new string(a);
}
m_Types = types;
m_Selected = selected;
filterScore = score;
m_PartiallySelected = false;
m_Enabled = true;
}
public ListElement(string text, bool selected)
{
m_Content = new GUIContent(text);
m_Selected = selected;
filterScore = 0;
m_PartiallySelected = false;
m_Enabled = true;
}
public ListElement(string text) : this(text, false)
{
}
public float filterScore
{
get
{
return m_WasSelected ? float.MaxValue : m_FilterScore;
}
set
{
m_FilterScore = value;
ResetScore();
}
}
public bool selected
{
get
{
return m_Selected;
}
set
{
m_Selected = value;
if (m_Selected)
m_WasSelected = true;
}
}
public bool enabled
{
get
{
return m_Enabled;
}
set
{
m_Enabled = value;
}
}
public bool partiallySelected
{
get
{
return m_PartiallySelected;
}
set
{
m_PartiallySelected = value;
if (m_PartiallySelected)
m_WasSelected = true;
}
}
public string text
{
get
{
return m_Content.text;
}
set
{
m_Content.text = value;
}
}
public IEnumerable<string> types
{
get
{
return m_Types;
}
}
public void ResetScore()
{
m_WasSelected = m_Selected || m_PartiallySelected;
}
}
public class InputData
{
public List<ListElement> m_ListElements;
public bool m_CloseOnSelection;
public bool m_AllowCustom;
public bool m_EnableAutoCompletion = true;
public bool m_SortAlphabetically;
public OnSelectCallback m_OnSelectCallback;
public int m_MaxCount;
public InputData()
{
m_ListElements = new List<ListElement>();
}
public void DeselectAll()
{
foreach (ListElement element in m_ListElements)
{
element.selected = false;
element.partiallySelected = false;
}
}
public void ResetScores()
{
foreach (var element in m_ListElements)
element.ResetScore();
}
public virtual IEnumerable<ListElement> BuildQuery(string prefix)
{
if (prefix == "")
return m_ListElements;
else
return m_ListElements.Where(
element => element.m_Content.text.StartsWith(prefix, System.StringComparison.OrdinalIgnoreCase)
);
}
public IEnumerable<ListElement> GetFilteredList(string prefix)
{
IEnumerable<ListElement> res = BuildQuery(prefix);
if (m_MaxCount > 0)
res = res.OrderByDescending(element => element.filterScore).Take(m_MaxCount);
if (m_SortAlphabetically)
return res.OrderBy(element => element.text.ToLower());
else
return res;
}
public int GetFilteredCount(string prefix)
{
IEnumerable<ListElement> res = BuildQuery(prefix);
if (m_MaxCount > 0)
res = res.Take(m_MaxCount);
return res.Count();
}
public void AddElement(string label, string[] types)
{
var res = new ListElement(label, types, false, -1);
m_ListElements.Add(res);
}
public ListElement NewOrMatchingElement(string label)
{
foreach (var element in m_ListElements)
{
if (element.text.Equals(label, StringComparison.OrdinalIgnoreCase))
return element;
}
var res = new ListElement(label, false, -1);
m_ListElements.Add(res);
return res;
}
}
private class Styles
{
public GUIStyle menuItem = "MenuItem";
public GUIStyle menuItemMixed = "MenuItemMixed";
public GUIStyle background = "grey_border";
public GUIStyle customTextField;
public GUIStyle customTextFieldCancelButton;
public GUIStyle customTextFieldCancelButtonEmpty;
public Styles()
{
customTextField = new GUIStyle(EditorStyles.toolbarSearchField);
customTextFieldCancelButton = new GUIStyle(EditorStyles.toolbarSearchFieldCancelButton);
customTextFieldCancelButtonEmpty = new GUIStyle(EditorStyles.toolbarSearchFieldCancelButtonEmpty);
}
}
// Static
static Styles s_Styles;
// State
private InputData m_Data;
// Layout
const float k_LineHeight = 16;
const float k_TextFieldHeight = 16;
const float k_Margin = 10;
Gravity m_Gravity;
string m_EnteredTextCompletion = "";
string m_EnteredText = "";
int m_SelectedCompletionIndex = 0;
public PopupList(InputData inputData) : this(inputData, null) {}
public PopupList(InputData inputData, string initialSelectionLabel)
{
m_Data = inputData;
m_Data.ResetScores();
SelectNoCompletion();
m_Gravity = Gravity.Top;
if (initialSelectionLabel != null)
{
m_EnteredTextCompletion = initialSelectionLabel;
UpdateCompletion();
}
}
public override void OnClose()
{
if (m_Data != null)
m_Data.ResetScores();
}
public virtual float GetWindowHeight()
{
int count = (m_Data.m_MaxCount == 0) ? m_Data.GetFilteredCount(m_EnteredText) : m_Data.m_MaxCount;
return count * k_LineHeight + 2 * k_Margin + (m_Data.m_AllowCustom ? k_TextFieldHeight : 0);
}
public virtual float GetWindowWidth()
{
return 150f;
}
public override Vector2 GetWindowSize()
{
return new Vector2(GetWindowWidth(), GetWindowHeight());
}
public override void OnGUI(Rect windowRect)
{
Event evt = Event.current;
// We do not use the layout event
if (evt.type == EventType.Layout)
return;
if (s_Styles == null)
s_Styles = new Styles();
if (evt.type == EventType.KeyDown && evt.keyCode == KeyCode.Escape)
{
editorWindow.Close();
GUIUtility.ExitGUI();
}
if (m_Gravity == Gravity.Bottom)
{
DrawList(editorWindow, windowRect);
DrawCustomTextField(editorWindow, windowRect);
}
else
{
DrawCustomTextField(editorWindow, windowRect);
DrawList(editorWindow, windowRect);
}
// Background with 1 pixel border (rendered above content)
if (evt.type == EventType.Repaint)
s_Styles.background.Draw(new Rect(windowRect.x, windowRect.y, windowRect.width, windowRect.height), false, false, false, false);
}
private void DrawCustomTextField(EditorWindow editorWindow, Rect windowRect)
{
if (!m_Data.m_AllowCustom)
return;
Event evt = Event.current;
bool enableAutoCompletion = m_Data.m_EnableAutoCompletion;
bool closeWindow = false;
bool useEventBeforeTextField = false;
bool clearText = false;
string textBeforeEdit = CurrentDisplayedText();
// Handle "special" keyboard input
if (evt.type == EventType.KeyDown)
{
switch (evt.keyCode)
{
case KeyCode.Comma:
case KeyCode.Space:
case KeyCode.Tab:
case KeyCode.Return:
if (textBeforeEdit != "")
{
// Toggle state
if (m_Data.m_OnSelectCallback != null)
m_Data.m_OnSelectCallback(m_Data.NewOrMatchingElement(textBeforeEdit));
if (evt.keyCode == KeyCode.Tab || evt.keyCode == KeyCode.Comma)
clearText = true; // to ease multiple entries (it is unlikely that the same filter is used more than once)
// Auto close
if (m_Data.m_CloseOnSelection || evt.keyCode == KeyCode.Return)
closeWindow = true;
}
useEventBeforeTextField = true;
break;
case KeyCode.Delete:
case KeyCode.Backspace:
enableAutoCompletion = false;
// Don't use the event yet, so the textfield below can get it and delete the selection
break;
case KeyCode.DownArrow:
ChangeSelectedCompletion(1);
useEventBeforeTextField = true;
break;
case KeyCode.UpArrow:
ChangeSelectedCompletion(-1);
useEventBeforeTextField = true;
break;
case KeyCode.None:
if (evt.character == ' ' || evt.character == ',')
useEventBeforeTextField = true;
break;
}
}
string textFieldText;
// Draw textfield
{
bool dummy = false;
Rect pos = new Rect(windowRect.x + k_Margin / 2, windowRect.y + (m_Gravity == Gravity.Top ? (k_Margin / 2) : (windowRect.height - k_TextFieldHeight - k_Margin / 2)), windowRect.width - k_Margin - 14, k_TextFieldHeight);
GUI.SetNextControlName(s_TextFieldName);
EditorGUI.FocusTextInControl(s_TextFieldName);
int id = EditorGUIUtility.GetControlID(s_TextFieldHash, FocusType.Keyboard, pos);
if (useEventBeforeTextField)
evt.Use(); // We have to delay this until after we get the control id, otherwise the id we get is just -1
if (GUIUtility.keyboardControl == 0)
GUIUtility.keyboardControl = id;
textFieldText = EditorGUI.DoTextField(s_RecycledEditor, id, pos, textBeforeEdit, s_Styles.customTextField, null, out dummy, false, false, false);
Rect buttonRect = pos;
buttonRect.x += pos.width;
buttonRect.width = 14;
// Draw "clear textfield" button (X)
if ((GUI.Button(buttonRect, GUIContent.none, textFieldText != "" ? s_Styles.customTextFieldCancelButton : s_Styles.customTextFieldCancelButtonEmpty) && textFieldText != "")
|| clearText)
{
textFieldText = EditorGUI.s_OriginalText = s_RecycledEditor.text = "";
s_RecycledEditor.cursorIndex = 0;
s_RecycledEditor.selectIndex = 0;
enableAutoCompletion = false;
}
}
// Handle autocompletion
if (textBeforeEdit != textFieldText)
{
m_EnteredText = (0 <= s_RecycledEditor.cursorIndex && s_RecycledEditor.cursorIndex < textFieldText.Length) ? textFieldText.Substring(0, s_RecycledEditor.cursorIndex) : textFieldText;
if (enableAutoCompletion)
UpdateCompletion();
else
SelectNoCompletion();
}
if (closeWindow)
editorWindow.Close();
}
private string CurrentDisplayedText()
{
return m_EnteredTextCompletion != "" ? m_EnteredTextCompletion : m_EnteredText;
}
private void UpdateCompletion()
{
if (!m_Data.m_EnableAutoCompletion)
return;
IEnumerable<string> query = m_Data.GetFilteredList(m_EnteredText).Select(element => element.text);
if (m_EnteredTextCompletion != "" && m_EnteredTextCompletion.StartsWith(m_EnteredText, System.StringComparison.OrdinalIgnoreCase))
{
m_SelectedCompletionIndex = query.TakeWhile(element => element != m_EnteredTextCompletion).Count();
// m_EnteredTextCompletion is already correct
}
else
{
// Clamp m_SelectedCompletionIndex to 0..query.Count () - 1
if (m_SelectedCompletionIndex < 0)
m_SelectedCompletionIndex = 0;
else if (m_SelectedCompletionIndex >= query.Count())
m_SelectedCompletionIndex = query.Count() - 1;
m_EnteredTextCompletion = query.Skip(m_SelectedCompletionIndex).DefaultIfEmpty("").FirstOrDefault();
}
AdjustRecycledEditorSelectionToCompletion();
}
private void ChangeSelectedCompletion(int change)
{
int count = m_Data.GetFilteredCount(m_EnteredText);
if (m_SelectedCompletionIndex == -1 && change < 0) // specal case for initial selection
m_SelectedCompletionIndex = count;
int index = count > 0 ? (m_SelectedCompletionIndex + change + count) % count : 0;
SelectCompletionWithIndex(index);
}
private void SelectCompletionWithIndex(int index)
{
m_SelectedCompletionIndex = index;
m_EnteredTextCompletion = "";
UpdateCompletion();
}
private void SelectNoCompletion()
{
m_SelectedCompletionIndex = -1;
m_EnteredTextCompletion = "";
AdjustRecycledEditorSelectionToCompletion();
}
private void AdjustRecycledEditorSelectionToCompletion()
{
if (m_EnteredTextCompletion != "")
{
s_RecycledEditor.text = m_EnteredTextCompletion;
EditorGUI.s_OriginalText = m_EnteredTextCompletion;
s_RecycledEditor.cursorIndex = m_EnteredText.Length;
s_RecycledEditor.selectIndex = m_EnteredTextCompletion.Length; //the selection goes from s_RecycledEditor.cursorIndex (already set by DoTextField) to s_RecycledEditor.selectIndex
}
}
private void DrawList(EditorWindow editorWindow, Rect windowRect)
{
Event evt = Event.current;
int i = -1;
foreach (var element in m_Data.GetFilteredList(m_EnteredText))
{
i++;
Rect rect = new Rect(windowRect.x, windowRect.y + k_Margin + i * k_LineHeight + (m_Gravity == Gravity.Top && m_Data.m_AllowCustom ? k_TextFieldHeight : 0), windowRect.width, k_LineHeight);
switch (evt.type)
{
case EventType.Repaint:
{
GUIStyle style = element.partiallySelected ? s_Styles.menuItemMixed : s_Styles.menuItem;
bool selected = element.selected || element.partiallySelected;
bool focused = false;
bool isHover = i == m_SelectedCompletionIndex;
bool isActive = selected;
using (new EditorGUI.DisabledScope(!element.enabled))
{
GUIContent content = element.m_Content;
style.Draw(rect, content, isHover, isActive, selected, focused);
}
}
break;
case EventType.MouseDown:
{
if (Event.current.button == 0 && rect.Contains(Event.current.mousePosition) && element.enabled)
{
// Toggle state
if (m_Data.m_OnSelectCallback != null)
m_Data.m_OnSelectCallback(element);
evt.Use();
// Auto close
if (m_Data.m_CloseOnSelection)
editorWindow.Close();
}
}
break;
case EventType.MouseMove:
{
if (rect.Contains(Event.current.mousePosition))
{
SelectCompletionWithIndex(i);
evt.Use();
}
}
break;
}
}
}
}
}
| UnityCsReference/Editor/Mono/ProjectBrowser/ProjectBrowserPopups.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ProjectBrowser/ProjectBrowserPopups.cs",
"repo_id": "UnityCsReference",
"token_count": 10797
} | 333 |
// Unity 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.Collections.Generic;
using System.Linq;
using System.Collections;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using JSONObject = System.Collections.IDictionary;
namespace UnityEditor
{
[NativeHeader("Editor/Src/SJSON.h"),
StaticAccessor("SJSON", StaticAccessorType.DoubleColon)]
internal static class SJSON
{
public static extern string Encode([NotNull] JSONObject t);
public static extern string EncodeObject(object o);
[NativeThrows] public static extern JSONObject Decode([NotNull] byte[] sjson);
[NativeThrows] public static extern object DecodeObject([NotNull] byte[] sjson);
public static JSONObject Load(string path)
{
if (String.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
var readResult = File.ReadAllBytes(path);
try
{
return Decode(readResult);
}
catch (UnityException ex)
{
throw new UnityException(ex.Message.Replace("(memory)", $"({path})"));
}
}
public static JSONObject LoadString(string json)
{
if (String.IsNullOrEmpty(json))
throw new ArgumentNullException(nameof(json));
try
{
return Decode(Encoding.UTF8.GetBytes(json));
}
catch (UnityException ex)
{
throw new UnityException(ex.Message.Replace("(memory)", "(string)"), ex);
}
}
public static byte[] GetBytes(JSONObject data)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
return Encoding.UTF8.GetBytes(Encode(data));
}
public static bool Save(JSONObject h, string path)
{
var s = Encode(h);
if (File.Exists(path))
{
var oldS = File.ReadAllText(path, Encoding.GetEncoding(0));
if (s.Equals(oldS))
return false;
}
var bytes = Encoding.UTF8.GetBytes(s);
File.WriteAllBytes(path, bytes);
return true;
}
[RequiredByNativeCode]
internal static JSONObject CreateJSONObject()
{
return new Dictionary<string, object>(1);
}
[RequiredByNativeCode]
internal static void AddJSONKeyValue(JSONObject ht, string key, object value)
{
ht.Add(key, value);
}
[RequiredByNativeCode]
internal static string[] GetKeys(JSONObject ht)
{
return ht.Keys.Cast<string>().ToArray();
}
[RequiredByNativeCode]
internal static object GetValue(JSONObject ht, string key)
{
return ht[key];
}
[RequiredByNativeCode]
internal static int GetArrayCount(object obj)
{
var list = obj as ICollection;
if (list != null)
return list.Count;
var array = obj as Array;
if (array != null)
return array.Length;
var count = 0;
var enumerable = obj as IEnumerable;
if (enumerable != null)
{
foreach (var e in enumerable)
count++;
}
return count;
}
[RequiredByNativeCode]
internal static object GetArrayElement(object obj, int index)
{
var list = obj as IList;
if (list != null)
return list[index];
var enumerable = obj as IEnumerable;
if (enumerable == null)
return null;
return Enumerable.ElementAt(enumerable.Cast<object>(), index);
}
internal static bool TryGetValue(JSONObject data, string key, out object value)
{
value = null;
if (data == null || !data.Contains(key))
return false;
value = data[key];
return true;
}
}
}
| UnityCsReference/Editor/Mono/SJSON.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SJSON.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2095
} | 334 |
// 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.SceneManagement
{
public sealed partial class PrefabStage : PreviewSceneStage
{
// Not using API Updater for now since it doesn't support updating to a virtual property,
// and this caused API Updader tests to fail.
// (UnityUpgradable) -> assetPath
[Obsolete("prefabAssetPath has been deprecated. Use assetPath instead.")]
public string prefabAssetPath
{
get { return m_PrefabAssetPath; }
}
}
}
| UnityCsReference/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.deprecated.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/PrefabStage/PrefabStage.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 234
} | 335 |
// Unity 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 Object = UnityEngine.Object;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.Rendering;
namespace UnityEditor
{
public abstract class LightingWindowEnvironmentSection
{
public virtual void OnEnable() {}
public virtual void OnDisable() {}
public virtual void OnInspectorGUI() {}
}
internal class LightingWindowEnvironmentTab : LightingWindow.WindowTab
{
class Styles
{
public static readonly GUIContent OtherSettings = EditorGUIUtility.TrTextContent("Other Settings");
}
class DefaultEnvironmentSectionExtension : LightingWindowEnvironmentSection
{
Editor m_EnvironmentEditor;
Editor environmentEditor
{
get
{
if (m_EnvironmentEditor == null || m_EnvironmentEditor.target == null)
{
Editor.CreateCachedEditor(RenderSettings.GetRenderSettings(), typeof(LightingEditor), ref m_EnvironmentEditor);
}
return m_EnvironmentEditor;
}
}
public override void OnInspectorGUI()
{
environmentEditor.OnInspectorGUI();
}
public override void OnDisable()
{
if (m_EnvironmentEditor != null)
{
Object.DestroyImmediate(m_EnvironmentEditor);
m_EnvironmentEditor = null;
}
}
}
LightingWindowEnvironmentSection m_EnvironmentSection;
Editor m_FogEditor;
Editor m_OtherRenderingEditor;
SavedBool m_ShowOtherSettings;
Object m_RenderSettings = null;
Vector2 m_ScrollPosition = Vector2.zero;
Type m_SRP;
Object renderSettings
{
get
{
if (m_RenderSettings == null || m_RenderSettings != RenderSettings.GetRenderSettings())
m_RenderSettings = RenderSettings.GetRenderSettings();
return m_RenderSettings;
}
}
LightingWindowEnvironmentSection environmentEditor
{
get
{
var currentSRP = GraphicsSettings.currentRenderPipelineAssetType;
if (m_EnvironmentSection != null && m_SRP != currentSRP)
{
m_SRP = currentSRP;
m_EnvironmentSection.OnDisable();
m_EnvironmentSection = null;
}
if (m_EnvironmentSection == null)
{
var extensionType = RenderPipelineEditorUtility.GetDerivedTypesSupportedOnCurrentPipeline<LightingWindowEnvironmentSection>().FirstOrDefault() ?? typeof(DefaultEnvironmentSectionExtension);
LightingWindowEnvironmentSection extension = (LightingWindowEnvironmentSection)Activator.CreateInstance(extensionType);
m_EnvironmentSection = extension;
m_EnvironmentSection.OnEnable();
}
return m_EnvironmentSection;
}
}
Editor fogEditor
{
get
{
if (m_FogEditor == null || m_FogEditor.target == null || m_FogEditor.target != RenderSettings.GetRenderSettings())
{
Editor.CreateCachedEditor(renderSettings, typeof(FogEditor), ref m_FogEditor);
}
return m_FogEditor;
}
}
Editor otherRenderingEditor
{
get
{
if (m_OtherRenderingEditor == null || m_OtherRenderingEditor.target == null || m_OtherRenderingEditor.target != RenderSettings.GetRenderSettings())
{
Editor.CreateCachedEditor(renderSettings, typeof(OtherRenderingEditor), ref m_OtherRenderingEditor);
}
return m_OtherRenderingEditor;
}
}
public void OnEnable()
{
m_SRP = GraphicsSettings.currentRenderPipelineAssetType;
m_ShowOtherSettings = new SavedBool($"LightingWindow.ShowOtherSettings", true);
}
public void OnDisable()
{
ClearCachedProperties();
}
void ClearCachedProperties()
{
if (m_EnvironmentSection != null)
{
m_EnvironmentSection.OnDisable();
m_EnvironmentSection = null;
}
if (m_FogEditor != null)
{
Object.DestroyImmediate(m_FogEditor);
m_FogEditor = null;
}
if (m_OtherRenderingEditor != null)
{
Object.DestroyImmediate(m_OtherRenderingEditor);
m_OtherRenderingEditor = null;
}
}
public void OnGUI()
{
EditorGUIUtility.hierarchyMode = true;
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
if (!SupportedRenderingFeatures.active.overridesEnvironmentLighting)
environmentEditor.OnInspectorGUI();
OtherSettingsGUI();
EditorGUILayout.EndScrollView();
}
public void OnSummaryGUI()
{
LightingWindow.Summary();
}
public void OnSelectionChange()
{
}
void OtherSettingsGUI()
{
if (SupportedRenderingFeatures.active.overridesFog && SupportedRenderingFeatures.active.overridesOtherLightingSettings)
return;
m_ShowOtherSettings.value = EditorGUILayout.FoldoutTitlebar(m_ShowOtherSettings.value, Styles.OtherSettings, true);
if (m_ShowOtherSettings.value)
{
EditorGUI.indentLevel++;
if (!SupportedRenderingFeatures.active.overridesFog)
fogEditor.OnInspectorGUI();
if (!SupportedRenderingFeatures.active.overridesOtherLightingSettings)
otherRenderingEditor.OnInspectorGUI();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
}
public bool HasHelpGUI()
{
return true;
}
}
} // namespace
| UnityCsReference/Editor/Mono/SceneModeWindows/LightingWindowEnvironmentTab.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneModeWindows/LightingWindowEnvironmentTab.cs",
"repo_id": "UnityCsReference",
"token_count": 3245
} | 336 |
// 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.Overlays;
namespace UnityEditor
{
public partial class SceneView
{
[Overlay(typeof(SceneView), k_OverlayID, k_DisplayName)]
internal class SceneViewIsolationOverlay : TransientSceneViewOverlay
{
public const string k_OverlayID = "Scene View/Scene Visibility";
const string k_DisplayName = "Isolation View";
bool m_ShouldDisplay;
internal static class Styles
{
public static GUIContent isolationModeExitButton = EditorGUIUtility.TrTextContent("Exit", "Exit isolation mode");
}
public override bool visible => m_ShouldDisplay;
public override void OnCreated()
{
SceneVisibilityManager.currentStageIsIsolated += CurrentStageIsolated;
CurrentStageIsolated(SceneVisibilityState.isolation);
}
public override void OnWillBeDestroyed()
{
SceneVisibilityManager.currentStageIsIsolated -= CurrentStageIsolated;
}
void CurrentStageIsolated(bool isolated)
{
m_ShouldDisplay = isolated;
}
public override void OnGUI()
{
if (GUILayout.Button(Styles.isolationModeExitButton, GUILayout.MinWidth(120)))
{
SceneVisibilityManager.instance.ExitIsolation();
}
}
}
}
}
// namespace
| UnityCsReference/Editor/Mono/SceneView/SceneViewOverlays.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneView/SceneViewOverlays.cs",
"repo_id": "UnityCsReference",
"token_count": 745
} | 337 |
// 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<TDerived, TValue> : 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<TDerived>();
s_Instance.hideFlags = HideFlags.HideAndDontSave;
}
return s_Instance;
}
}
public TValue this[string preferencesFileName]
{
get
{
return Load(preferencesFileName);
}
}
private TValue CreateNewValue()
{
TValue value = ScriptableObject.CreateInstance<TValue>();
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.");
}
}
}
| UnityCsReference/Editor/Mono/ScriptableSingletonDictionary.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ScriptableSingletonDictionary.cs",
"repo_id": "UnityCsReference",
"token_count": 2310
} | 338 |
// 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
{
/// Marks the type of a [[CompilerMessage]]
internal enum CompilerMessageType
{
/// The message is an error. The compilation has failed.
Error = 0,
/// The message is an warning only. If there are no error messages, the compilation has completed successfully.
Warning = 1,
// This message type is required because "Info" is an accepted action type in Microsoft rule set files:
// https://docs.microsoft.com/en-us/visualstudio/code-quality/working-in-the-code-analysis-rule-set-editor?view=vs-2019
Information = 2
}
/// This struct should be returned from GetCompilerMessages() on ScriptCompilerBase implementations
internal struct CompilerMessage
{
/// The text of the error or warning message
public string message;
/// The path name of the file the message refers to
public string file;
/// The line in the source file the message refers to
public int line;
/// The column of the line the message refers to
public int column;
/// The type of the message. Either Error or Warning
public CompilerMessageType type;
//This field is dead and not used. The reason it's still here is that its used through [InternalsVibislbeTo] by the burst package (as of oktober2020), so we cannot yet remove this
// ReSharper disable once NotAccessedField.Global
internal string assemblyName;
}
}
| UnityCsReference/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/Compilers/ScriptCompilerBase.cs",
"repo_id": "UnityCsReference",
"token_count": 543
} | 339 |
// Unity 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.Threading.Tasks;
using Bee.Core;
using NiceIO;
namespace UnityEditor.Scripting.ScriptCompilation
{
static class UnityBeeDriverProfilerSession
{
private static NPath m_CurrentPlayerBuildProfilerOutputFile;
private static int m_BeeDriverForCurrentPlayerBuildIndex;
private static TinyProfiler2 _tinyProfiler;
private static Stack<IDisposable> m_ProfilerSections = new Stack<IDisposable>();
private static List<Task> m_TasksToWaitForBeforeFinishing = new();
public static TinyProfiler2 ProfilerInstance => _tinyProfiler;
static public void Start(NPath path)
{
m_CurrentPlayerBuildProfilerOutputFile = path;
m_BeeDriverForCurrentPlayerBuildIndex = 0;
m_TasksToWaitForBeforeFinishing.Clear();
_tinyProfiler = new TinyProfiler2();
}
static public void Finish()
{
if (m_CurrentPlayerBuildProfilerOutputFile == null)
return;
foreach (var task in m_TasksToWaitForBeforeFinishing)
task.Wait();
_tinyProfiler.Write(m_CurrentPlayerBuildProfilerOutputFile.ToString(), new ChromeTraceOptions
{
ProcessName = "Unity",
ProcessId = System.Diagnostics.Process.GetCurrentProcess().Id,
ProcessSortIndex = -100
});
m_CurrentPlayerBuildProfilerOutputFile = null;
_tinyProfiler = null;
}
static public void BeginSection(string name)
{
if (m_CurrentPlayerBuildProfilerOutputFile != null)
{
m_ProfilerSections.Push(_tinyProfiler.Section(name));
}
}
static public void EndSection()
{
if (m_CurrentPlayerBuildProfilerOutputFile != null)
{
m_ProfilerSections.Pop().Dispose();
}
}
static public void AddTaskToWaitForBeforeFinishing(Task t) => m_TasksToWaitForBeforeFinishing.Add(t);
static public bool PerformingPlayerBuild => m_CurrentPlayerBuildProfilerOutputFile != null;
static public NPath GetTraceEventsOutputForPlayerBuild()
{
if (!PerformingPlayerBuild)
throw new ArgumentException();
NPath path = $"{m_CurrentPlayerBuildProfilerOutputFile.Parent}/{m_CurrentPlayerBuildProfilerOutputFile.FileName}_{m_BeeDriverForCurrentPlayerBuildIndex++}.traceevents";
_tinyProfiler.AddExternalTraceEventsFile(path.ToString());
return path;
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/UnityBeeDriverProfilerSession.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/BeeDriver/UnityBeeDriverProfilerSession.cs",
"repo_id": "UnityCsReference",
"token_count": 1196
} | 340 |
// 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
{
internal class ExpressionNotValidException : Exception
{
public ExpressionNotValidException(string expression)
: base(expression) {}
public ExpressionNotValidException(string message, string expression)
: base($"{message} : {expression}") {}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/ExpressionNotValidException.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/ExpressionNotValidException.cs",
"repo_id": "UnityCsReference",
"token_count": 168
} | 341 |
// Unity 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.Linq;
using UnityEditor.Scripting.Compilers;
using UnityEditor.Compilation;
namespace UnityEditor.Scripting.ScriptCompilation
{
[Flags]
internal enum TargetAssemblyType
{
Undefined = 0,
Predefined = 1,
Custom = 2
}
internal enum EditorCompatibility
{
NotCompatibleWithEditor = 0,
CompatibleWithEditor = 1
}
[DebuggerDisplay("{Filename}")]
internal class TargetAssembly
{
public string Filename { get; private set; }
public AssemblyFlags Flags { get; private set; }
public string PathPrefix { get; private set; }
public string[] AdditionalPrefixes { get; set; }
public Func<string, int> PathFilter { get; private set; }
public Func<ScriptAssemblySettings, string[], bool> IsCompatibleFunc { get; private set; }
public List<TargetAssembly> References { get; set; }
public List<string> ExplicitPrecompiledReferences { get; set; }
public TargetAssemblyType Type { get; private set; }
public string[] Defines { get; set; }
public string[] ResponseFileDefines { get; set; }
public string RootNamespace { get; set; }
public ScriptCompilerOptions CompilerOptions { get; set; }
public List<VersionDefine> VersionDefines { get; set; }
public string AsmDefPath { get; set; }
public int MaxPathLength { get; private set; }
public TargetAssembly()
{
References = new List<TargetAssembly>();
Defines = null;
}
public TargetAssembly(string name,
AssemblyFlags flags,
TargetAssemblyType type,
string pathPrefix,
string[] additionalPrefixes,
Func<string, int> pathFilter,
Func<ScriptAssemblySettings, string[], bool> compatFunc,
ScriptCompilerOptions compilerOptions) : this()
{
Filename = name;
Flags = flags;
PathPrefix = pathPrefix;
AdditionalPrefixes = additionalPrefixes;
PathFilter = pathFilter;
IsCompatibleFunc = compatFunc;
Type = type;
CompilerOptions = compilerOptions;
ExplicitPrecompiledReferences = new List<string>();
VersionDefines = new List<VersionDefine>();
if (PathPrefix != null)
MaxPathLength = PathPrefix.Length;
if (AdditionalPrefixes != null)
MaxPathLength = UnityEngine.Mathf.Max(MaxPathLength, AdditionalPrefixes.Max(am => am.Length));
}
public string FullPath(string outputDirectory)
{
return AssetPath.Combine(outputDirectory, Filename);
}
public EditorCompatibility editorCompatibility
{
get
{
bool isCompatibleWithEditor = IsCompatibleFunc == null ||
IsCompatibleFunc(new ScriptAssemblySettings { BuildTarget = BuildTarget.NoTarget, CompilationOptions = EditorScriptCompilationOptions.BuildingForEditor }, null);
return isCompatibleWithEditor
? EditorCompatibility.CompatibleWithEditor
: EditorCompatibility.NotCompatibleWithEditor;
}
}
public override string ToString()
{
return string.Format("{0} ({1})", Filename, Type);
}
protected bool Equals(TargetAssembly other)
{
return string.Equals(Filename, other.Filename) && Flags == other.Flags && Type == other.Type;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((TargetAssembly)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (Filename != null ? Filename.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (int)Flags;
hashCode = (hashCode * 397) ^ (int)Type;
return hashCode;
}
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/TargetAssembly.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/TargetAssembly.cs",
"repo_id": "UnityCsReference",
"token_count": 2037
} | 342 |
// Unity 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 Object = UnityEngine.Object;
namespace UnityEditor.SearchService
{
[AttributeUsage(AttributeTargets.Class)]
public class ObjectSelectorEngineAttribute : Attribute
{}
[Flags]
public enum VisibleObjects
{
None = 0,
Assets = 1,
Scene = 1 << 1,
All = Assets | Scene
}
public partial class ObjectSelectorSearchContext : ISearchContext
{
public Guid guid { get; } = Guid.NewGuid();
public SearchEngineScope engineScope { get; protected set; } = ObjectSelectorSearch.EngineScope;
public Object currentObject { get; set; }
public Object[] editedObjects { get; set; }
public IEnumerable<Type> requiredTypes { get; set; }
public IEnumerable<string> requiredTypeNames { get; set; }
public VisibleObjects visibleObjects { get; set; }
public IEnumerable<int> allowedInstanceIds { get; set; }
internal SearchFilter searchFilter { get; set; }
}
public interface IObjectSelectorEngine : ISelectorEngine {}
[InitializeOnLoad]
public static class ObjectSelectorSearch
{
static SearchApiBaseImp<ObjectSelectorEngineAttribute, IObjectSelectorEngine> s_EngineImp;
static SearchApiBaseImp<ObjectSelectorEngineAttribute, IObjectSelectorEngine> engineImp
{
get
{
if (s_EngineImp == null)
StaticInit();
return s_EngineImp;
}
}
public const SearchEngineScope EngineScope = SearchEngineScope.ObjectSelector;
static ObjectSelectorSearch()
{
EditorApplication.tick += StaticInit;
}
private static void StaticInit()
{
EditorApplication.tick -= StaticInit;
s_EngineImp = s_EngineImp ?? new SearchApiBaseImp<ObjectSelectorEngineAttribute, IObjectSelectorEngine>(EngineScope, "Object Selector");
}
internal static bool SelectObject(ObjectSelectorSearchContext context, Action<Object, bool> onObjectSelectorClosed, Action<Object> onObjectSelectedUpdated)
{
var activeEngine = engineImp.activeSearchEngine;
try
{
return activeEngine.SelectObject(context, onObjectSelectorClosed, onObjectSelectedUpdated);
}
catch (Exception ex)
{
engineImp.HandleUserException(ex);
return false;
}
}
internal static void SetSearchFilter(string searchFilter, ObjectSelectorSearchContext context)
{
var activeEngine = engineImp.activeSearchEngine;
activeEngine.SetSearchFilter(context, searchFilter);
}
internal static bool HasEngineOverride()
{
return engineImp.HasEngineOverride();
}
internal static void BeginSession(ObjectSelectorSearchContext context)
{
engineImp.BeginSession(context);
}
internal static void EndSession(ObjectSelectorSearchContext context)
{
engineImp.EndSession(context);
}
internal static void BeginSearch(string query, ObjectSelectorSearchContext context)
{
engineImp.BeginSearch(query, context);
}
internal static void EndSearch(ObjectSelectorSearchContext context)
{
engineImp.EndSearch(context);
}
internal static IObjectSelectorEngine GetActiveSearchEngine()
{
return engineImp.GetActiveSearchEngine();
}
internal static void SetActiveSearchEngine(string searchEngineName)
{
engineImp.SetActiveSearchEngine(searchEngineName);
}
public static void RegisterEngine(IObjectSelectorEngine engine)
{
engineImp.RegisterEngine(engine);
}
public static void UnregisterEngine(IObjectSelectorEngine engine)
{
engineImp.UnregisterEngine(engine);
}
}
class ObjectSelectorSearchSessionHandler : SearchSessionHandler
{
public ObjectSelectorSearchSessionHandler()
: base(SearchEngineScope.ObjectSelector) {}
public bool SelectObject(Action<Object, bool> onObjectSelectorClosed, Action<Object> onObjectSelectedUpdated)
{
using (new SearchSessionOptionsApplicator(m_Api, m_Options))
return ObjectSelectorSearch.SelectObject((ObjectSelectorSearchContext)context, onObjectSelectorClosed, onObjectSelectedUpdated);
}
public void SetSearchFilter(string searchFilter)
{
using (new SearchSessionOptionsApplicator(m_Api, m_Options))
ObjectSelectorSearch.SetSearchFilter(searchFilter, (ObjectSelectorSearchContext)context);
}
}
}
| UnityCsReference/Editor/Mono/Search/ObjectSelectorSearch.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Search/ObjectSelectorSearch.cs",
"repo_id": "UnityCsReference",
"token_count": 2008
} | 343 |
// 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.IMGUI.Controls;
using UnityEngine.Profiling;
namespace UnityEditor
{
internal class SerializedPropertyTable
{
internal delegate SerializedPropertyTreeView.Column[] HeaderDelegate();
SerializedPropertyDataStore.GatherDelegate m_GatherDelegate;
HeaderDelegate m_HeaderDelegate;
bool m_Initialized;
TreeViewState m_TreeViewState;
MultiColumnHeaderState m_MultiColumnHeaderState;
SerializedPropertyTreeView m_TreeView;
SerializedPropertyDataStore m_DataStore;
float m_ColumnHeaderHeight;
string m_SerializationUID;
readonly float m_FilterHeight = 20;
bool m_ShowFilterGUI;
public SerializedPropertyTable(string serializationUID, SerializedPropertyDataStore.GatherDelegate gatherDelegate, HeaderDelegate headerDelegate, bool showFilterGUI)
{
m_SerializationUID = serializationUID;
m_GatherDelegate = gatherDelegate;
m_HeaderDelegate = headerDelegate;
m_ShowFilterGUI = showFilterGUI;
}
void InitIfNeeded()
{
if (m_Initialized)
return;
if (m_TreeViewState == null)
m_TreeViewState = new TreeViewState();
if (m_MultiColumnHeaderState == null)
{
SerializedPropertyTreeView.Column[] columns = m_HeaderDelegate();
string[] propNames = GetPropertyNames(columns);
m_MultiColumnHeaderState = new MultiColumnHeaderState(columns);
m_DataStore = new SerializedPropertyDataStore(propNames, m_GatherDelegate);
}
var header = new MultiColumnHeader(m_MultiColumnHeaderState);
m_ColumnHeaderHeight = header.height;
m_TreeView = new SerializedPropertyTreeView(m_TreeViewState, header, m_DataStore, m_ShowFilterGUI);
m_TreeView.DeserializeState(m_SerializationUID);
m_TreeView.Reload();
m_Initialized = true;
}
string[] GetPropertyNames(SerializedPropertyTreeView.Column[] columns)
{
string[] propNames = new string[columns.Length];
for (int i = 0; i < columns.Length; i++)
propNames[i] = columns[i].propertyName;
return propNames;
}
public void OnInspectorUpdate()
{
if (m_TreeView != null)
{
m_TreeView.Update();
}
}
public void OnHierarchyChange()
{
if (m_TreeView != null)
{
m_TreeView.Update();
}
}
public void OnSelectionChange()
{
OnSelectionChange(Selection.instanceIDs);
}
public void OnSelectionChange(int[] instanceIDs)
{
if (m_TreeView != null)
{
m_TreeView.SetSelection(instanceIDs);
}
}
public void OnGUI()
{
Profiler.BeginSample("SerializedPropertyTable.OnGUI");
InitIfNeeded();
Rect r = GUILayoutUtility.GetRect(0, float.MaxValue, 0, float.MaxValue);
if (Event.current.type == EventType.Layout)
{
Profiler.EndSample();
return;
}
float tableHeight = r.height - m_FilterHeight;
// filter rect
r.height = m_FilterHeight;
Rect filterRect = r;
// table rect
r.height = tableHeight;
r.y += m_FilterHeight;
Rect tableRect = r;
// filter
m_TreeView.OnFilterGUI(filterRect);
// table
Profiler.BeginSample("TreeView.OnGUI");
m_TreeView.OnGUI(tableRect);
Profiler.EndSample();
if (m_TreeView.IsFilteredDirty())
m_TreeView.Reload();
Profiler.EndSample();
}
public void OnDisable()
{
if (m_TreeView != null)
m_TreeView.SerializeState(m_SerializationUID);
}
}
}
| UnityCsReference/Editor/Mono/SerializedProperty/SerializedPropertyTable.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SerializedProperty/SerializedPropertyTable.cs",
"repo_id": "UnityCsReference",
"token_count": 2353
} | 344 |
// Unity 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 UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
using DebuggerDisplayAttribute = System.Diagnostics.DebuggerDisplayAttribute;
namespace UnityEditor
{
public class ShaderData
{
public class Subshader
{
internal enum Type
{
Runtime,
Serialized
}
internal ShaderData m_Data;
internal int m_SubshaderIndex;
private Func<Shader, int, ShaderTagId, ShaderTagId> m_FindTagValue;
internal Subshader(ShaderData data, int subshaderIndex, Type type = Type.Runtime)
{
m_Data = data;
m_SubshaderIndex = subshaderIndex;
m_FindTagValue = type == Type.Serialized ? s_SerializedFindTagValue : s_RuntimeFindTagValue;
}
internal Shader SourceShader => m_Data.SourceShader;
public int PassCount => ShaderUtil.GetShaderTotalPassCount(m_Data.SourceShader, m_SubshaderIndex);
public int LevelOfDetail => ShaderUtil.GetSubshaderLOD(m_Data.SourceShader, m_SubshaderIndex);
private static Func<Shader, int, ShaderTagId, ShaderTagId> s_SerializedFindTagValue = (Shader sourceShader, int subshaderIndex, ShaderTagId tag) =>
new ShaderTagId { id = ShaderUtil.FindSerializedSubShaderTagValue(sourceShader, subshaderIndex, tag.id) };
private static Func<Shader, int, ShaderTagId, ShaderTagId> s_RuntimeFindTagValue = (Shader sourceShader, int subshaderIndex, ShaderTagId tag) =>
{
if (subshaderIndex < 0 || subshaderIndex >= sourceShader.subshaderCount)
{
Debug.LogErrorFormat("Subshader index is incorrect: {0}, shader {1} has {2} subshaders.", subshaderIndex, sourceShader, sourceShader.subshaderCount);
return ShaderTagId.none;
}
return sourceShader.FindSubshaderTagValue(subshaderIndex, tag);
};
public ShaderTagId FindTagValue(ShaderTagId tag) => m_FindTagValue(SourceShader, m_SubshaderIndex, tag);
public Pass GetPass(int passIndex)
{
if (passIndex < 0 || passIndex >= PassCount)
{
Debug.LogErrorFormat("Pass index is incorrect: {0}, shader {1} has {2} passes.", passIndex, SourceShader, PassCount);
return null;
}
return new Pass(this, passIndex);
}
}
public class Pass
{
Subshader m_Subshader;
int m_PassIndex;
internal Pass(Subshader subshader, int passIndex)
{
m_Subshader = subshader;
m_PassIndex = passIndex;
}
internal Shader SourceShader { get { return m_Subshader.m_Data.SourceShader; } }
internal int SubshaderIndex { get { return m_Subshader.m_SubshaderIndex; } }
public string SourceCode { get { return ShaderUtil.GetShaderPassSourceCode(SourceShader, SubshaderIndex, m_PassIndex); } }
public string Name { get { return ShaderUtil.GetShaderPassName(SourceShader, SubshaderIndex, m_PassIndex); } }
public bool IsGrabPass { get { return ShaderUtil.IsGrabPass(SourceShader, SubshaderIndex, m_PassIndex); } }
public UnityEngine.Rendering.ShaderTagId FindTagValue(UnityEngine.Rendering.ShaderTagId tagName)
{
int id = ShaderUtil.FindPassTagValue(SourceShader, m_Subshader.m_SubshaderIndex, m_PassIndex, tagName.id);
return new UnityEngine.Rendering.ShaderTagId { id = id };
}
public bool HasShaderStage(ShaderType shaderType)
{
return ShaderUtil.PassHasShaderStage(SourceShader, SubshaderIndex, m_PassIndex, shaderType);
}
internal static GraphicsTier kNoGraphicsTier = (GraphicsTier)(-1);
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget)
{
return CompileVariant(shaderType, keywords, shaderCompilerPlatform, buildTarget, false);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, bool forExternalTool)
{
var platformKeywords = ShaderUtil.GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform, buildTarget, kNoGraphicsTier);
return ShaderUtil.CompileShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, kNoGraphicsTier, forExternalTool);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, GraphicsTier tier)
{
return CompileVariant(shaderType, keywords, shaderCompilerPlatform, buildTarget, tier, false);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, GraphicsTier tier, bool forExternalTool)
{
var platformKeywords = ShaderUtil.GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform, buildTarget, tier);
return ShaderUtil.CompileShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, tier, forExternalTool);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords)
{
return CompileVariant(shaderType, keywords, shaderCompilerPlatform, buildTarget, platformKeywords, false);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, bool forExternalTool)
{
return ShaderUtil.CompileShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, kNoGraphicsTier, forExternalTool);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, GraphicsTier tier)
{
return CompileVariant(shaderType, keywords, shaderCompilerPlatform, buildTarget, platformKeywords, tier, false);
}
public VariantCompileInfo CompileVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, GraphicsTier tier, bool forExternalTool)
{
return ShaderUtil.CompileShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, tier, forExternalTool);
}
public PreprocessedVariant PreprocessVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, bool stripLineDirectives)
{
var platformKeywords = ShaderUtil.GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform, buildTarget, kNoGraphicsTier);
return ShaderUtil.PreprocessShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, kNoGraphicsTier, stripLineDirectives);
}
public PreprocessedVariant PreprocessVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, GraphicsTier tier, bool stripLineDirectives)
{
var platformKeywords = ShaderUtil.GetShaderPlatformKeywordsForBuildTarget(shaderCompilerPlatform, buildTarget, tier);
return ShaderUtil.PreprocessShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, tier, stripLineDirectives);
}
public PreprocessedVariant PreprocessVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, bool stripLineDirectives)
{
return ShaderUtil.PreprocessShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, kNoGraphicsTier, stripLineDirectives);
}
public PreprocessedVariant PreprocessVariant(ShaderType shaderType, string[] keywords,
ShaderCompilerPlatform shaderCompilerPlatform, BuildTarget buildTarget, BuiltinShaderDefine[] platformKeywords, GraphicsTier tier, bool stripLineDirectives)
{
return ShaderUtil.PreprocessShaderVariant(SourceShader, SubshaderIndex, m_PassIndex, shaderType, platformKeywords, keywords, shaderCompilerPlatform, buildTarget, tier, stripLineDirectives);
}
}
public int ActiveSubshaderIndex => ShaderUtil.GetShaderActiveSubshaderIndex(SourceShader);
public int SubshaderCount => ShaderUtil.GetShaderSubshaderCount(SourceShader);
public int SerializedSubshaderCount => ShaderUtil.GetShaderSerializedSubshaderCount(SourceShader);
public Shader SourceShader { get; private set; }
public Subshader ActiveSubshader
{
get
{
var index = ActiveSubshaderIndex;
if (index < 0 || index >= SubshaderCount)
return null;
return new Subshader(this, index);
}
}
internal ShaderData(Shader sourceShader)
{
Assert.IsNotNull(sourceShader);
this.SourceShader = sourceShader;
}
public Subshader GetSubshader(int index)
{
if (index < 0 || index >= SubshaderCount)
{
Debug.LogErrorFormat("Subshader index is incorrect: {0}, shader {1} has {2} subshaders.", index, SourceShader, SubshaderCount);
return null;
}
return new Subshader(this, index);
}
public Subshader GetSerializedSubshader(int index)
{
if (index < 0 || index >= SerializedSubshaderCount)
{
Debug.LogErrorFormat("Serialized Subshader index is incorrect: {0}, shader {1} has {2} serialized subshaders.", index, SourceShader, SerializedSubshaderCount);
return null;
}
return new Subshader(this, index, Subshader.Type.Serialized);
}
public struct PreprocessedVariant
{
public bool Success { get; }
public ShaderMessage[] Messages { get; }
public string PreprocessedCode { get; }
}
//
// Experimental reflection information and raw compiled data access. Used for Tiny shader export.
//
public struct VariantCompileInfo
{
public bool Success { get; }
public ShaderMessage[] Messages { get; }
public byte[] ShaderData { get; }
public VertexAttribute[] Attributes { get; }
public ConstantBufferInfo[] ConstantBuffers { get; }
public TextureBindingInfo[] TextureBindings { get; }
}
[DebuggerDisplay("cbuffer {Name} ({Size} bytes)")]
public struct ConstantBufferInfo
{
public string Name { get; }
public int Size { get; }
public ConstantInfo[] Fields { get; }
}
[DebuggerDisplay("{ConstantType} {Name} ({DataType} {Columns}x{Rows})")]
public struct ConstantInfo
{
public string Name { get; }
public int Index { get; }
public ShaderConstantType ConstantType { get; }
public ShaderParamType DataType { get; }
public int Rows { get; }
public int Columns { get; }
public int ArraySize { get; }
// only relevant if ConstantType == Struct
public int StructSize { get; }
public ConstantInfo[] StructFields { get; }
}
[DebuggerDisplay("{Dim} {Name}")]
public struct TextureBindingInfo
{
public string Name { get; }
public int Index { get; }
public int SamplerIndex { get; }
public bool Multisampled { get; }
public int ArraySize { get; }
public TextureDimension Dim { get; }
}
}
public partial class ShaderUtil
{
public static ShaderData GetShaderData(Shader shader)
{
return new ShaderData(shader);
}
// GetShaderMessageCount includes warnings, this function filters them out
public static bool ShaderHasError(Shader shader)
{
FetchCachedMessages(shader);
var errors = GetShaderMessages(shader);
return errors.Any(x => x.severity == ShaderCompilerMessageSeverity.Error);
}
public static bool ShaderHasWarnings(Shader shader)
{
FetchCachedMessages(shader);
var errors = GetShaderMessages(shader);
return errors.Any(x => x.severity == ShaderCompilerMessageSeverity.Warning);
}
internal static extern bool PassHasShaderStage(Shader s, int subshaderIndex, int passIndex, ShaderType shaderType);
internal static bool MaterialsUseInstancingShader(SerializedProperty materialsArray)
{
if (materialsArray.hasMultipleDifferentValues)
return false;
for (int i = 0; i < materialsArray.arraySize; ++i)
{
var material = materialsArray.GetArrayElementAtIndex(i).objectReferenceValue as Material;
if (material != null && material.enableInstancing && material.shader != null && HasInstancing(material.shader))
return true;
}
return false;
}
}
}
| UnityCsReference/Editor/Mono/ShaderUtil.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ShaderUtil.cs",
"repo_id": "UnityCsReference",
"token_count": 6305
} | 345 |
// Unity 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 UnityEditorInternal;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Rendering;
using UnityEngine.Scripting;
namespace UnityEditor
{
[NativeClass(null)]
[NativeHeader("Runtime/BaseClasses/TagManager.h")]
internal sealed class TagManager : ProjectSettingsBase
{
private TagManager() {}
[StaticAccessor("GetTagManager()", StaticAccessorType.Dot)]
internal static extern int GetDefinedLayerCount();
public extern string[] tags { [NativeMethod("GetTagNames")] get; }
[NativeMethod]
internal extern void AddSortingLayer();
[NativeMethod]
internal extern int GetSortingLayerCount();
[NativeMethod]
internal extern void UpdateSortingLayersOrder();
[NativeMethod]
internal extern bool IsSortingLayerDefault(int index);
[NativeMethod]
internal extern string GetSortingLayerName(int index);
[NativeMethod]
internal extern void SetSortingLayerName(int index, string name);
[NativeMethod("StringToTagAddIfUnavailable")]
extern int StringToTagAddIfUnavailable(string tag);
/*
* After adding a tag, set the TagManager as dirty. We may not call "SetDirty" in "StringToTagAddIfUnavailable" itself because
* it may be called off of the main thread.
*/
internal int AddTag(string tag)
{
int result = StringToTagAddIfUnavailable(tag);
EditorUtility.SetDirty(this);
return result;
}
[NativeMethod]
internal extern void RemoveTag(string tag);
internal static void GetDefinedLayers(ref string[] layerNames, ref int[] layerValues)
{
var definedLayerCount = GetDefinedLayerCount();
if (layerNames == null)
layerNames = new string[definedLayerCount];
else if (layerNames.Length != definedLayerCount)
Array.Resize(ref layerNames, definedLayerCount);
if (layerValues == null)
layerValues = new int[definedLayerCount];
else if (layerValues.Length != definedLayerCount)
Array.Resize(ref layerValues, definedLayerCount);
Internal_GetDefinedLayers(layerNames, layerValues);
}
[FreeFunction("GetTagManager().GetDefinedLayers")]
static extern void Internal_GetDefinedLayers([Out] string[] layerNames, [Out] int[] layerValues);
[NativeMethod]
internal extern bool IsIndexReservedForDefaultRenderingLayer(int index);
[NativeMethod]
internal extern bool TryAddRenderingLayerName(string name);
[NativeMethod]
internal extern int GetRenderingLayerCount();
[NativeMethod]
internal extern bool TryRemoveLastRenderingLayerName();
[FreeFunction("GetTagManager().TrySetRenderingLayerName")]
internal static extern bool Internal_TrySetRenderingLayerName(int index, string name);
[FreeFunction("GetTagManager().TryAddRenderingLayerName")]
internal static extern bool Internal_TryAddRenderingLayerName(string name);
[NativeMethod]
internal extern int StringToRenderingLayer(string name);
[NativeMethod]
internal extern string RenderingLayerToString(int index);
}
}
| UnityCsReference/Editor/Mono/TagManager.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/TagManager.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1342
} | 346 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.EditorTools;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace UnityEditor
{
abstract class PrimitiveColliderTool<T> : EditorTool where T : Collider
{
public override GUIContent toolbarIcon
{
get { return PrimitiveBoundsHandle.editModeButton; }
}
protected abstract PrimitiveBoundsHandle boundsHandle { get; }
protected abstract void CopyColliderPropertiesToHandle(T collider);
protected abstract void CopyHandlePropertiesToCollider(T collider);
protected Vector3 InvertScaleVector(Vector3 scaleVector)
{
for (int axis = 0; axis < 3; ++axis)
scaleVector[axis] = scaleVector[axis] == 0f ? 0f : 1f / scaleVector[axis];
return scaleVector;
}
public override void OnToolGUI(EditorWindow window)
{
foreach (var obj in targets)
{
if (!(obj is T collider) || Mathf.Approximately(collider.transform.lossyScale.sqrMagnitude, 0f))
continue;
// 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(collider);
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(collider);
}
}
}
}
protected static Vector3 TransformColliderCenterToHandleSpace(Transform colliderTransform, Vector3 colliderCenter)
{
return Handles.inverseMatrix * (colliderTransform.localToWorldMatrix * colliderCenter);
}
protected static Vector3 TransformHandleCenterToColliderSpace(Transform colliderTransform, Vector3 handleCenter)
{
return colliderTransform.localToWorldMatrix.inverse * (Handles.matrix * handleCenter);
}
}
}
| UnityCsReference/Editor/Mono/Tools/PrimitiveColliderTool.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Tools/PrimitiveColliderTool.cs",
"repo_id": "UnityCsReference",
"token_count": 1105
} | 347 |
// Unity 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.SceneManagement;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static class BindingsStyleHelpers
{
internal static event Action<VisualElement, SerializedProperty> updateBindingStateStyle;
static EventCallback<PointerUpEvent> s_RightClickMenuCallback;
static Action<VisualElement, SerializedProperty> s_UpdateElementStyleFromProperty;
static Action<VisualElement, SerializedProperty> s_UpdatePrefabStateStyleFromProperty;
// Lets us bypass the default right click menu to show our own.
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static Func<VisualElement, bool> HandleRightClickMenu;
static BindingsStyleHelpers()
{
s_RightClickMenuCallback = RightClickFieldMenuEvent;
s_UpdateElementStyleFromProperty = UpdateElementStyleFromProperty;
s_UpdatePrefabStateStyleFromProperty = UpdatePrefabStateStyleFromProperty;
}
private enum BarType
{
PrefabOverride,
LiveProperty
}
private static void UpdateElementRecursively(VisualElement element, SerializedProperty prop, Action<VisualElement, SerializedProperty> updateCallback)
{
VisualElement elementToUpdate = element;
if (element is Foldout foldout)
{
// We only want to apply override styles onto the Foldout header, not the entire contents.
elementToUpdate = foldout.toggle;
}
else if (element.ClassListContains(BaseCompositeField<int, IntegerField, int>.ussClassName)
|| element is BoundsField || element is BoundsIntField)
{
// The problem with compound fields is that they are bound at the parent level using
// their parent value data type. For example, a Vector3Field is bound to the parent
// SerializedProperty which uses the Vector3 data type. However, animation overrides
// are not stored on the parent SerializedProperty but on the component child
// SerializedProperties. So even though we're bound to the parent property, we still
// have to dive inside and example the child SerializedProperties (ie. x, y, z, height)
// and override the animation styles individually.
var compositeField = element;
// The element we style in the main pass is going to be just the label.
if (element is IPrefixLabel prefixLabel)
elementToUpdate = prefixLabel.labelElement;
else
elementToUpdate = element.Q(className: BaseField<int>.labelUssClassName);
// Go through the inputs and find any that match the names of the child PropertyFields.
var propCopy = prop.Copy();
var endProperty = propCopy.GetEndProperty();
propCopy.NextVisible(true); // Expand the first child.
do
{
if (SerializedProperty.EqualContents(propCopy, endProperty))
break;
var subInputName = "unity-" + propCopy.name + "-input";
var subInput = compositeField.Q(subInputName);
if (subInput == null)
continue;
UpdateElementRecursively(subInput, propCopy, updateCallback);
}
while (propCopy.NextVisible(false)); // Never expand children.
}
if (elementToUpdate != null)
{
updateCallback(elementToUpdate, prop);
}
}
internal static void UpdateElementStyle(VisualElement element, SerializedProperty prop)
{
if (element == null)
return;
UpdateElementRecursively(element, prop, s_UpdateElementStyleFromProperty);
}
private static void UpdateElementStyleFromProperty(VisualElement element, SerializedProperty prop)
{
if (element is IMixedValueSupport mixedValuePropertyField)
mixedValuePropertyField.showMixedValue = prop.hasMultipleDifferentValues;
// It's possible for there to be no label in a compound field, for example. So, nothing to style.
if (element == null)
return;
// Handle prefab state.
UpdatePrefabStateStyleFromProperty(element, prop);
// Handle live property state.
UpdateLivePropertyStyleFromProperty(element, prop);
// Handle dynamic states
updateBindingStateStyle?.Invoke(element, prop);
// Handle animated state.
// Since we handle compound fields above, the element here will always be a single field
// (or not a field at all). This means we can perform a faster query and search for
// a single element.
var inputElement = element.Q(className: BaseField<int>.inputUssClassName);
if (inputElement == null)
{
return;
}
bool animated = AnimationMode.IsPropertyAnimated(prop.serializedObject.targetObject, prop.propertyPath);
bool candidate = AnimationMode.IsPropertyCandidate(prop.serializedObject.targetObject, prop.propertyPath);
bool recording = AnimationMode.InAnimationRecording();
inputElement.EnableInClassList(BindingExtensions.animationRecordedUssClassName, animated && recording);
inputElement.EnableInClassList(BindingExtensions.animationCandidateUssClassName, animated && !recording && candidate);
inputElement.EnableInClassList(BindingExtensions.animationAnimatedUssClassName, animated && !recording && !candidate);
}
internal static void UpdateLivePropertyStyleFromProperty(VisualElement element, SerializedProperty prop)
{
bool handleLivePropertyState = false;
if (EditorApplication.isPlaying && SerializedObject.GetLivePropertyFeatureGlobalState())
{
try
{
var component = prop.serializedObject.targetObject as Component;
handleLivePropertyState = (component != null && !component.gameObject.scene.isSubScene) || prop.isLiveModified;
}
catch (Exception)
{
return;
}
}
if (handleLivePropertyState)
{
if (!element.ClassListContains(BindingExtensions.livePropertyUssClassName))
{
var container = FindPrefabOverrideOrLivePropertyBarCompatibleParent(element);
var barContainer = container?.livePropertyYellowBarsContainer;
element.AddToClassList(BindingExtensions.livePropertyUssClassName);
if (container != null && barContainer != null)
{
var livePropertyBar = new VisualElement();
livePropertyBar.name = BindingExtensions.livePropertyBarName;
livePropertyBar.userData = element;
livePropertyBar.AddToClassList(BindingExtensions.livePropertyBarUssClassName);
barContainer.Add(livePropertyBar);
element.SetProperty(BindingExtensions.livePropertyBarName, livePropertyBar);
// We need to try and set the bar style right away, even if the container
// didn't compute its layout yet. This is for when the override is done after
// everything has been layed out.
UpdatePrefabOverrideOrLivePropertyBarStyle(livePropertyBar);
// We intentionally re-register this event on the container per element and
// never unregister.
container.RegisterCallback<GeometryChangedEvent, BarType>(UpdatePrefabOverrideOrLivePropertyBarStyleEvent, BarType.LiveProperty);
element.RegisterCallback<DetachFromPanelEvent>(_ =>
{
element.RemoveFromClassList(BindingExtensions.livePropertyUssClassName);
livePropertyBar.RemoveFromHierarchy();
});
}
}
}
else if (element.ClassListContains(BindingExtensions.livePropertyUssClassName))
{
element.RemoveFromClassList(BindingExtensions.livePropertyUssClassName);
var container = FindPrefabOverrideOrLivePropertyBarCompatibleParent(element);
var barContainer = container?.livePropertyYellowBarsContainer;
if (container != null && barContainer != null)
{
var livePropertyBar = element.GetProperty(BindingExtensions.livePropertyBarName) as VisualElement;
if (livePropertyBar != null)
livePropertyBar.RemoveFromHierarchy();
}
}
}
internal static void UpdatePrefabStateStyle(VisualElement element, SerializedProperty prop)
{
if (element == null)
return;
UpdateElementRecursively(element, prop, s_UpdatePrefabStateStyleFromProperty);
}
internal static void UpdateLivePropertyStateStyle(VisualElement element, SerializedProperty prop)
{
if (element == null)
return;
UpdateElementRecursively(element, prop, UpdateLivePropertyStyleFromProperty);
}
static bool ComponentIsPrefabOverride(Component comp)
{
return comp != null &&
PrefabUtility.GetCorrespondingConnectedObjectFromSource(comp.gameObject) != null &&
PrefabUtility.GetCorrespondingObjectFromSource(comp) == null;
}
private static void UpdatePrefabStateStyleFromProperty(VisualElement element, SerializedProperty prop)
{
bool handlePrefabState = false;
try
{
// This can throw if the serialized object changes type under our feet
handlePrefabState = prop.serializedObject.targetObjects.Length == 1 &&
prop.isInstantiatedPrefab &&
(prop.prefabOverride || ComponentIsPrefabOverride(prop.serializedObject.targetObject as Component));
}
catch
{
return;
}
// Handle prefab state.
if (handlePrefabState)
{
if (!element.ClassListContains(BindingExtensions.prefabOverrideUssClassName))
{
var container = FindPrefabOverrideOrLivePropertyBarCompatibleParent(element);
var barContainer = container?.prefabOverrideBlueBarsContainer;
element.AddToClassList(BindingExtensions.prefabOverrideUssClassName);
if (container != null && barContainer != null)
{
// Ideally, this blue bar would be a child of the field and just move
// outside the field in absolute offsets to hug the side of the field's
// container. However, right now we need to have overflow:hidden on
// fields because of case 1105567 (the inputs can grow beyond the field).
// Therefore, we have to add the blue bars as children of the container
// and move them down beside their respective field.
var prefabOverrideBar = new VisualElement();
prefabOverrideBar.name = BindingExtensions.prefabOverrideBarName;
prefabOverrideBar.userData = element;
string ussClass = PrefabUtility.CanPropertyBeAppliedToSource(prop) ? BindingExtensions.prefabOverrideBarUssClassName : BindingExtensions.prefabOverrideBarNotApplicableUssClassName;
prefabOverrideBar.AddToClassList(ussClass);
barContainer.Add(prefabOverrideBar);
element.SetProperty(BindingExtensions.prefabOverrideBarName, prefabOverrideBar);
// We need to try and set the bar style right away, even if the container
// didn't compute its layout yet. This is for when the override is done after
// everything has been layed out.
UpdatePrefabOverrideOrLivePropertyBarStyle(prefabOverrideBar);
// We intentionally re-register this event on the container per element and
// never unregister.
container.RegisterCallback<GeometryChangedEvent, BarType>(UpdatePrefabOverrideOrLivePropertyBarStyleEvent, BarType.PrefabOverride);
element.RegisterCallback<DetachFromPanelEvent>(_ =>
{
element.RemoveFromClassList(BindingExtensions.prefabOverrideUssClassName);
prefabOverrideBar.RemoveFromHierarchy();
});
}
}
}
else if (element.ClassListContains(BindingExtensions.prefabOverrideUssClassName))
{
element.RemoveFromClassList(BindingExtensions.prefabOverrideUssClassName);
var container = FindPrefabOverrideOrLivePropertyBarCompatibleParent(element);
var barContainer = container?.prefabOverrideBlueBarsContainer;
if (container != null && barContainer != null)
{
var prefabOverrideBar = element.GetProperty(BindingExtensions.prefabOverrideBarName) as VisualElement;
if (prefabOverrideBar != null)
prefabOverrideBar.RemoveFromHierarchy();
}
}
if (PrefabUtility.IsPropertyBeingDrivenByPrefabStage(prop))
{
element.SetEnabled(false);
element.tooltip = PrefabStage.s_PrefabInContextPreviewValuesTooltip;
}
}
private static InspectorElement FindPrefabOverrideOrLivePropertyBarCompatibleParent(VisualElement field)
{
// For now we only support these blue prefab override bars and yellow live property bars within an InspectorElement.
return field.GetFirstAncestorOfType<InspectorElement>();
}
private static void UpdatePrefabOverrideOrLivePropertyBarStyle(VisualElement bar)
{
var element = bar.userData as VisualElement;
var container = FindPrefabOverrideOrLivePropertyBarCompatibleParent(element);
if (container == null)
return;
// Move the bar to where the control is in the container.
var top = element.worldBound.y - container.worldBound.y;
if (float.IsNaN(top)) // If this is run before the container has been layed out.
return;
var elementHeight = element.resolvedStyle.height;
if (float.IsNaN(elementHeight))
{
// This event is added due to an issue where container is fully resolved, but this element is not.
// This happens each time when entering play mode.
element.RegisterCallback<GeometryChangedEvent, VisualElement>(ReUpdateLivePropertyBarStyleEvent, bar);
return;
}
// This is needed so if you have 2 overridden fields their blue
// bars touch (and it looks like one long bar). They normally wouldn't
// because most fields have a small margin.
var bottomOffset = element.resolvedStyle.marginBottom;
var topOffset = element.resolvedStyle.marginTop;
bar.style.top = top - topOffset;
bar.style.height = elementHeight + bottomOffset + topOffset;
bar.style.left = 0.0f;
}
private static void UpdatePrefabOverrideOrLivePropertyBarStyleEvent(GeometryChangedEvent evt, BarType barType)
{
var container = evt.target as InspectorElement;
if (container == null)
return;
var barContainer = barType switch
{
BarType.PrefabOverride => container.Q(BindingExtensions.prefabOverrideBarContainerName),
BarType.LiveProperty => container.Q(BindingExtensions.livePropertyBarContainerName),
_ => throw new ArgumentOutOfRangeException(nameof(barType), barType, null)
};
if (barContainer == null)
return;
// If the userData parent has been removed then we should remove all bars as the component has been removed.
for (var i = 0; i < barContainer.childCount; i++)
{
var element = barContainer[i].userData as VisualElement;
if (element == null || FindPrefabOverrideOrLivePropertyBarCompatibleParent(element) != null) continue;
switch (barType)
{
case BarType.PrefabOverride:
{
element.RemoveFromClassList(BindingExtensions.prefabOverrideUssClassName);
var prefabOverridePropertyBar = element.GetProperty(BindingExtensions.prefabOverrideBarName) as VisualElement;
prefabOverridePropertyBar?.RemoveFromHierarchy();
break;
}
case BarType.LiveProperty:
{
element.RemoveFromClassList(BindingExtensions.livePropertyUssClassName);
var livePropertyBar = element.GetProperty(BindingExtensions.livePropertyBarName) as VisualElement;
livePropertyBar?.RemoveFromHierarchy();
break;
}
default:
throw new ArgumentOutOfRangeException(nameof(barType), barType, null);
}
return;
}
for (var i = 0; i < barContainer.childCount; i++)
UpdatePrefabOverrideOrLivePropertyBarStyle(barContainer[i]);
}
private static void ReUpdateLivePropertyBarStyleEvent(GeometryChangedEvent evt, VisualElement bar)
{
var element = evt.elementTarget;
if (element == null)
return;
element.UnregisterCallback<GeometryChangedEvent, VisualElement>(ReUpdateLivePropertyBarStyleEvent);
UpdatePrefabOverrideOrLivePropertyBarStyle(bar);
}
// Stop ContextClickEvent because the context menu in the UITk inspector is shown on PointerUpEvent and not on ContextualMenuPopulateEvent (UUM-11643).
static void StopContextClickEvent(ContextClickEvent e)
{
e.StopImmediatePropagation();
}
internal static void RegisterRightClickMenu(Label field, SerializedProperty property)
{
field.userData = property.Copy();
field.RegisterCallback(s_RightClickMenuCallback, InvokePolicy.IncludeDisabled, TrickleDown.TrickleDown);
field.RegisterCallback<ContextClickEvent>(StopContextClickEvent, TrickleDown.TrickleDown);
}
internal static void RegisterRightClickMenu<TValue>(BaseField<TValue> field, SerializedProperty property)
{
field.userData = property.Copy();
field.RegisterCallback(s_RightClickMenuCallback, InvokePolicy.IncludeDisabled, TrickleDown.TrickleDown);
field.RegisterCallback<ContextClickEvent>(StopContextClickEvent, TrickleDown.TrickleDown);
}
internal static void RegisterRightClickMenu(Foldout field, SerializedProperty property)
{
var toggle = field.Q<Toggle>(className: Foldout.toggleUssClassName);
if (toggle != null)
{
toggle.userData = property.Copy();
toggle.RegisterCallback(s_RightClickMenuCallback, InvokePolicy.IncludeDisabled, TrickleDown.TrickleDown);
toggle.RegisterCallback<ContextClickEvent>(StopContextClickEvent, TrickleDown.TrickleDown);
}
}
internal static void UnregisterRightClickMenu<TValue>(BaseField<TValue> field)
{
field.userData = null;
field.UnregisterCallback(s_RightClickMenuCallback);
field.UnregisterCallback<ContextClickEvent>(StopContextClickEvent);
}
internal static void UnregisterRightClickMenu(Foldout field)
{
var toggle = field.Q<Toggle>(className: Foldout.toggleUssClassName);
toggle?.UnregisterCallback(s_RightClickMenuCallback);
toggle?.UnregisterCallback<ContextClickEvent>(StopContextClickEvent);
}
internal static void RightClickFieldMenuEvent(PointerUpEvent evt)
{
if (evt.button != (int)MouseButton.RightMouse)
return;
var element = evt.currentTarget as VisualElement;
bool handledExternally = HandleRightClickMenu?.Invoke(element) == true;
var property = element?.userData as SerializedProperty;
if (property == null || handledExternally)
return;
var wasEnabled = GUI.enabled;
if (!element.enabledInHierarchy)
GUI.enabled = false;
try
{
Event.ignoreGuiDepth = true;
Event.current = evt.imguiEvent;
var menu = EditorGUI.FillPropertyContextMenu(property, null, null, element);
GUI.enabled = wasEnabled;
if (menu == null)
return;
var dropdownMenu = ConvertGenericMenuToDropdownMenu(menu);
element.panel.contextualMenuManager.DisplayMenu(evt, element, dropdownMenu);
evt.StopPropagation();
}
finally
{
Event.ignoreGuiDepth = false;
}
}
static DropdownMenu ConvertGenericMenuToDropdownMenu(GenericMenu menu)
{
var dropdownMenu = new DropdownMenu();
foreach (var menuItem in menu.menuItems)
{
if (menuItem.separator)
{
dropdownMenu.AppendSeparator(menuItem.content.text);
}
else
{
var statusCallback = MenuItemToActionStatusCallback(menuItem);
if (menuItem.func != null)
{
dropdownMenu.AppendAction(menuItem.content.text, _ => menuItem.func(), statusCallback);
}
else if (menuItem.func2 != null)
{
dropdownMenu.AppendAction(menuItem.content.text, action => menuItem.func2(action.userData), statusCallback, menuItem.userData);
}
else
{
dropdownMenu.AppendAction(menuItem.content.text, null, statusCallback);
}
}
}
return dropdownMenu;
}
static readonly Dictionary<DropdownMenuAction.Status, Func<DropdownMenuAction, DropdownMenuAction.Status>> s_StatusCallbacks = new()
{
{ DropdownMenuAction.Status.Normal, DropdownMenuAction.AlwaysEnabled },
{ DropdownMenuAction.Status.Disabled, DropdownMenuAction.AlwaysDisabled },
};
static Func<DropdownMenuAction, DropdownMenuAction.Status> MenuItemToActionStatusCallback(GenericMenu.MenuItem menuItem)
{
var status = DropdownMenuAction.Status.None;
if (menuItem.func != null || menuItem.func2 != null)
{
status |= DropdownMenuAction.Status.Normal;
}
else
{
status |= DropdownMenuAction.Status.Disabled;
}
if (menuItem.on)
status |= DropdownMenuAction.Status.Checked;
// Cached callbacks
if (!s_StatusCallbacks.TryGetValue(status, out var callback))
{
callback = action => status;
s_StatusCallbacks[status] = callback;
}
return callback;
}
}
}
| UnityCsReference/Editor/Mono/UIElements/Bindings/BindingStyleHelpers.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/Bindings/BindingStyleHelpers.cs",
"repo_id": "UnityCsReference",
"token_count": 11239
} | 348 |
// Unity 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.UIElements;
namespace UnityEditor.UIElements
{
/// <summary>
/// Creates a breadcrumb UI element for the toolbar to help users navigate a hierarchy. For example, the visual scripting breadcrumb toolbar makes it easier to explore scripts because users can jump to any level of the script by clicking a breadcrumb item. For more information, refer to [[wiki:UIE-uxml-element-ToolbarBreadcrumbs|UXML element ToolbarBreadcrumbs]].
/// </summary>
/// <remarks>
/// Represents a breadcrumb trail to facilitate navigation between related items in a hierarchy.
/// </remarks>
/// <example>
/// <code>
/// <![CDATA[
/// using UnityEngine;
/// using UnityEngine.UIElements;
/// using UnityEditor.UIElements;
///
/// public class CreateBreadcrumbsHelper
/// {
/// ToolbarBreadcrumbs breadcrumbs;
/// public void CreateBreadcrumbs(VisualElement root)
/// {
/// var toolbar = new Toolbar();
/// root.Add(toolbar);
/// breadcrumbs = new ToolbarBreadcrumbs();
/// toolbar.Add(breadcrumbs);
/// breadcrumbs.PushItem("myItemGrandParent", GoToRoot);
/// breadcrumbs.PushItem("myItemParent", () => breadcrumbs.PopItem());
/// breadcrumbs.PushItem("myItem");
/// }
///
/// void GoToRoot()
/// {
/// while (breadcrumbs.childCount > 1)
/// breadcrumbs.PopItem();
/// }
/// }
/// ]]>
/// </code>
/// </example>
public class ToolbarBreadcrumbs : VisualElement
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new ToolbarBreadcrumbs();
}
/// <summary>
/// Instantiates a <see cref="ToolbarBreadcrumbs"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlFactory : UxmlFactory<ToolbarBreadcrumbs> {}
/// <summary>
/// A Unity style sheet (USS) class for the main ToolbarBreadcrumbs container.
/// </summary>
public static readonly string ussClassName = "unity-toolbar-breadcrumbs";
/// <summary>
/// A Unity style sheet (USS) class for individual items in a breadcrumb toolbar.
/// </summary>
public static readonly string itemClassName = ussClassName + "__item";
/// <summary>
/// A Unity style sheet (USS) class for the first element or item in a breadcrumb toolbar.
/// </summary>
public static readonly string firstItemClassName = ussClassName + "__first-item";
private class BreadcrumbItem : ToolbarButton
{
public BreadcrumbItem(Action clickEvent) :
base(clickEvent)
{
Toolbar.SetToolbarStyleSheet(this);
RemoveFromClassList(ussClassName);
AddToClassList(itemClassName);
}
}
/// <summary>
/// Constructs a breadcrumb UI element for the toolbar to help users navigate a hierarchy.
/// </summary>
public ToolbarBreadcrumbs()
{
Toolbar.SetToolbarStyleSheet(this);
AddToClassList(ussClassName);
}
/// <summary>
/// Adds an item to the end of the breadcrumbs, which makes that item the deepest item in the hierarchy.
/// </summary>
/// <param name="label">The text to display for the item in the breadcrumb toolbar.</param>
/// <param name="clickedEvent">The action to perform when the a users clicks the item in the toolbar.</param>
public void PushItem(string label, Action clickedEvent = null)
{
BreadcrumbItem breadcrumbItem = new BreadcrumbItem(clickedEvent) { text = label };
breadcrumbItem.EnableInClassList(firstItemClassName, childCount == 0);
Add(breadcrumbItem);
}
/// <summary>
/// Removes the last item in the breadcrumb toolbar, which is the deepest item in the hierarchy.
/// </summary>
public void PopItem()
{
if (Children().Any() && Children().Last() is BreadcrumbItem)
RemoveAt(childCount - 1);
else
throw new InvalidOperationException("Last child isn't a BreadcrumbItem");
}
}
}
| UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/ToolbarBreadcrumbs.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/ToolbarBreadcrumbs.cs",
"repo_id": "UnityCsReference",
"token_count": 1880
} | 349 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.UIElements
{
/// <summary>
/// Create decorators (additional <see cref="VisualElement"/>s) for the Inspector window.
/// </summary>
/// <remarks>
/// Unity automatically calls the methods in this interface for instances added to <see cref="EditorElement.AddDecorator(IEditorElementDecorator)"/>.
/// </remarks>
/// <seealso cref="EditorElement.RemoveDecorator(IEditorElementDecorator)"/>
internal interface IEditorElementDecorator
{
/// <summary>
/// Invoked once when the hierarchy element is constructed.
/// You can create and return a <see cref="VisualElement"/> that appears after the given editor in the InspectorWindow.
/// </summary>
/// <param name="editor">The editor to create the footer decorator.</param>
/// <returns>A footer <see cref="VisualElement"/> for the editor or null if you don't want to create a decorator.</returns>
VisualElement OnCreateFooter(Editor editor);
}
}
| UnityCsReference/Editor/Mono/UIElements/Inspector/IEditorElementDecorator.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/Inspector/IEditorElementDecorator.cs",
"repo_id": "UnityCsReference",
"token_count": 382
} | 350 |
// Unity 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.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.SceneManagement;
using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
namespace UnityEditor
{
public enum ObjectChangeKind : ushort
{
None = 0,
// The contents of the scene have changed in a way where no information on what specifically has changed can be provided
ChangeScene = 1,
CreateGameObjectHierarchy = 2,
// The contents of anything in a sub-hierarchy has changed
// (The game object and children might have been deleted, a new game object addded, parenting might have changed)
// Any prefab merge results in StructuralHierarchy change on all instances
ChangeGameObjectStructureHierarchy = 3,
// The contents of a game object has changed. Components were removed, added or changed.
ChangeGameObjectStructure = 4,
// The parent of the game object has changed
ChangeGameObjectParent = 5,
// A property of a loaded component or game object has changed
ChangeGameObjectOrComponentProperties = 6,
// The entire hierarchy will be destroyed after the callback is invoked
DestroyGameObjectHierarchy = 7,
// The Object (Any asset type) has been created
CreateAssetObject = 8,
// The Object (Any asset type) will be destroyed after the callback is invoked
DestroyAssetObject = 9,
// A property of a loaded asset object has changed
ChangeAssetObjectProperties = 10,
// An instance of a prefab was updated
UpdatePrefabInstances = 11,
// Children order change
ChangeChildrenOrder = 12
}
public static class ObjectChangeEvents
{
public delegate void ObjectChangeEventsHandler(ref ObjectChangeEventStream stream);
public static event ObjectChangeEventsHandler changesPublished
{
add => m_ChangesPublishedEvent.Add(value);
remove => m_ChangesPublishedEvent.Remove(value);
}
private static EventWithPerformanceTracker<ObjectChangeEventsHandler> m_ChangesPublishedEvent = new EventWithPerformanceTracker<ObjectChangeEventsHandler>($"{nameof(ObjectChangeEvents)}.{nameof(changesPublished)}");
// TODO: Once Burst supports internal/external functions in static initializers, this can become
// static readonly int s_staticSafetyId = AtomicSafetyHandle.NewStaticSafetyId<ObjectChangeEventStream>();
// and InitStaticSafetyId() can be replaced with a call to AtomicSafetyHandle.SetStaticSafetyId();
static int s_staticSafetyId;
[BurstDiscard]
static void InitStaticSafetyId(ref AtomicSafetyHandle handle1, ref AtomicSafetyHandle handle2)
{
if (s_staticSafetyId == 0)
s_staticSafetyId = AtomicSafetyHandle.NewStaticSafetyId<ObjectChangeEventStream>();
AtomicSafetyHandle.SetStaticSafetyId(ref handle1, s_staticSafetyId);
AtomicSafetyHandle.SetStaticSafetyId(ref handle2, s_staticSafetyId);
}
[RequiredByNativeCode(GenerateProxy = true)]
static void InvokeChangeEvent(IntPtr events, int eventsCount, IntPtr payLoad, int payLoadLength)
{
if (!m_ChangesPublishedEvent.hasSubscribers || eventsCount == 0)
return;
var stream = new ObjectChangeEventStream(events, eventsCount, payLoad, payLoadLength);
var ash1 = AtomicSafetyHandle.Create();
var ash2 = AtomicSafetyHandle.Create();
InitStaticSafetyId(ref ash1, ref ash2);
stream.OverrideSafetyHandle(ash1, ash2);
foreach (var evt in m_ChangesPublishedEvent)
evt(ref stream);
var result1 = AtomicSafetyHandle.EnforceAllBufferJobsHaveCompletedAndRelease(ash1);
var result2 = AtomicSafetyHandle.EnforceAllBufferJobsHaveCompletedAndRelease(ash2);
if (result1 == EnforceJobResult.DidSyncRunningJobs || result2 == EnforceJobResult.DidSyncRunningJobs)
{
UnityEngine.Debug.LogError(
$"You cannot use the {nameof(ObjectChangeEventStream)} instance provided by {nameof(changesPublished)} in a job unless you complete the job before your callback finishes.");
}
}
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeGameObjectParentEventArgs
{
public int instanceId => m_InstanceId;
public int previousParentInstanceId => m_PreviousParentInstanceId;
public int newParentInstanceId => m_NewParentInstanceId;
public Scene previousScene => m_PreviousScene;
public Scene newScene => m_NewScene;
public ChangeGameObjectParentEventArgs(int instanceId, Scene previousScene, int previousParentInstanceId, Scene newScene, int newParentInstanceId)
{
m_InstanceId = instanceId;
m_PreviousParentInstanceId = previousParentInstanceId;
m_NewParentInstanceId = newParentInstanceId;
m_PreviousScene = previousScene;
m_NewScene = newScene;
}
private int m_InstanceId;
private int m_PreviousParentInstanceId;
private int m_NewParentInstanceId;
private Scene m_PreviousScene;
private Scene m_NewScene;
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeChildrenOrderEventArgs
{
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public ChangeChildrenOrderEventArgs(int instanceId, Scene scene)
{
m_InstanceId = instanceId;
m_Scene = scene;
}
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeSceneEventArgs
{
public Scene scene => m_Scene;
public ChangeSceneEventArgs(Scene scene)
{
m_Scene = scene;
}
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct CreateGameObjectHierarchyEventArgs
{
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public CreateGameObjectHierarchyEventArgs(int instanceId, Scene scene)
{
m_InstanceId = instanceId;
m_Scene = scene;
}
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeGameObjectStructureHierarchyEventArgs
{
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public ChangeGameObjectStructureHierarchyEventArgs(int instanceId, Scene scene)
{
m_InstanceId = instanceId;
m_Scene = scene;
}
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeGameObjectStructureEventArgs
{
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public ChangeGameObjectStructureEventArgs(int instanceId, Scene scene)
{
m_InstanceId = instanceId;
m_Scene = scene;
}
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeGameObjectOrComponentPropertiesEventArgs
{
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public ChangeGameObjectOrComponentPropertiesEventArgs(int instanceId, Scene scene)
{
m_InstanceId = instanceId;
m_Scene = scene;
}
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct DestroyGameObjectHierarchyEventArgs
{
public int instanceId => m_InstanceId;
public int parentInstanceId => m_ParentInstanceId;
public Scene scene => m_Scene;
public DestroyGameObjectHierarchyEventArgs(int instanceId, Scene scene)
{
m_InstanceId = instanceId;
m_ParentInstanceId = 0;
m_Scene = scene;
}
public DestroyGameObjectHierarchyEventArgs(int instanceId, int parentInstanceId, Scene scene)
{
m_InstanceId = instanceId;
m_ParentInstanceId = parentInstanceId;
m_Scene = scene;
}
private int m_InstanceId;
private int m_ParentInstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct CreateAssetObjectEventArgs
{
public GUID guid => m_Guid;
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public CreateAssetObjectEventArgs(GUID guid, int instanceId, Scene scene)
{
m_Guid = guid;
m_InstanceId = instanceId;
m_Scene = scene;
}
private GUID m_Guid;
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct DestroyAssetObjectEventArgs
{
public GUID guid => m_Guid;
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public DestroyAssetObjectEventArgs(GUID guid, int instanceId, Scene scene)
{
m_Guid = guid;
m_InstanceId = instanceId;
m_Scene = scene;
}
private GUID m_Guid;
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct ChangeAssetObjectPropertiesEventArgs
{
public GUID guid => m_Guid;
public int instanceId => m_InstanceId;
public Scene scene => m_Scene;
public ChangeAssetObjectPropertiesEventArgs(GUID guid, int instanceId, Scene scene)
{
m_Guid = guid;
m_InstanceId = instanceId;
m_Scene = scene;
}
private GUID m_Guid;
private int m_InstanceId;
private Scene m_Scene;
}
[StructLayout(LayoutKind.Sequential)]
public struct UpdatePrefabInstancesEventArgs
{
public Scene scene => m_Scene;
public NativeArray<int>.ReadOnly instanceIds => m_InstanceIds;
public UpdatePrefabInstancesEventArgs(Scene scene, NativeArray<int>.ReadOnly instanceIds)
{
m_Scene = scene;
m_InstanceIds = instanceIds;
}
private Scene m_Scene;
private NativeArray<int>.ReadOnly m_InstanceIds;
}
public struct ObjectChangeEventStream : IDisposable
{
[ReadOnly]
private NativeArray<byte> m_Payload;
[ReadOnly]
private NativeArray<Event> m_Events;
#pragma warning disable 0649
[StructLayout(LayoutKind.Sequential)]
struct Event
{
// size in bytes and offset into payload array
public int offset, size;
public ObjectChangeKind ChangeKind;
}
[StructLayout(LayoutKind.Sequential)]
struct UpdatePrefabInstancesHeader
{
public Scene scene;
}
#pragma warning restore 0649
internal unsafe ObjectChangeEventStream(IntPtr events, int eventsCount, IntPtr payload, int payloadLength)
{
m_Payload = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(payload.ToPointer(), payloadLength, Allocator.Invalid);
m_Events = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Event>(events.ToPointer(), eventsCount, Allocator.Invalid);
}
internal void OverrideSafetyHandle(AtomicSafetyHandle handle1, AtomicSafetyHandle handle2)
{
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref m_Payload, handle1);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref m_Events, handle2);
}
ObjectChangeEventStream(NativeArray<Event> events, NativeArray<byte> payload)
{
m_Payload = payload;
m_Events = events;
}
public int length => m_Events.Length;
public bool isCreated => m_Events.IsCreated;
public ObjectChangeKind GetEventType(int eventIdx) => m_Events[eventIdx].ChangeKind;
public void GetChangeSceneEvent(int eventIdx, out ChangeSceneEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeScene, out data);
public void GetCreateGameObjectHierarchyEvent(int eventIdx, out CreateGameObjectHierarchyEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.CreateGameObjectHierarchy, out data);
public void GetDestroyGameObjectHierarchyEvent(int eventIdx, out DestroyGameObjectHierarchyEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.DestroyGameObjectHierarchy, out data);
public void GetChangeGameObjectStructureHierarchyEvent(int eventIdx, out ChangeGameObjectStructureHierarchyEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeGameObjectStructureHierarchy, out data);
public void GetChangeGameObjectStructureEvent(int eventIdx, out ChangeGameObjectStructureEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeGameObjectStructure, out data);
public void GetChangeGameObjectParentEvent(int eventIdx, out ChangeGameObjectParentEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeGameObjectParent, out data);
public void GetChangeChildrenOrderEvent(int eventIdx, out ChangeChildrenOrderEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeChildrenOrder, out data);
public void GetChangeGameObjectOrComponentPropertiesEvent(int eventIdx, out ChangeGameObjectOrComponentPropertiesEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeGameObjectOrComponentProperties, out data);
public void GetCreateAssetObjectEvent(int eventIdx, out CreateAssetObjectEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.CreateAssetObject, out data);
public void GetDestroyAssetObjectEvent(int eventIdx, out DestroyAssetObjectEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.DestroyAssetObject, out data);
public void GetChangeAssetObjectPropertiesEvent(int eventIdx, out ChangeAssetObjectPropertiesEventArgs data) =>
ExtractEvent(eventIdx, ObjectChangeKind.ChangeAssetObjectProperties, out data);
public void GetUpdatePrefabInstancesEvent(int eventIdx, out UpdatePrefabInstancesEventArgs data)
{
data = default;
var evt = ExtractEvent(eventIdx, ObjectChangeKind.UpdatePrefabInstances, out UpdatePrefabInstancesHeader header);
unsafe
{
int s = sizeof(UpdatePrefabInstancesHeader);
void* offset = (byte*)m_Payload.m_Buffer + evt.offset + s;
int elements = (evt.size - s) / sizeof(int);
var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<int>(offset, elements, Allocator.Invalid);
var ash = NativeArrayUnsafeUtility.GetAtomicSafetyHandle(m_Payload);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, ash);
data = new UpdatePrefabInstancesEventArgs(header.scene, arr.AsReadOnly());
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
static void CheckEventType(ObjectChangeKind actual, ObjectChangeKind expected)
{
if (actual != expected)
throw new InvalidOperationException($"Asked for event kind {expected}, but found {actual} instead.");
}
unsafe Event ExtractEvent<T>(int eventIdx, ObjectChangeKind kind, out T data) where T : struct
{
var evt = m_Events[eventIdx];
CheckEventType(evt.ChangeKind, kind);
var ptr = (byte*)m_Payload.GetUnsafePtr() + evt.offset;
UnsafeUtility.CopyPtrToStructure(ptr, out data);
return evt;
}
public ObjectChangeEventStream Clone(Allocator allocator) =>
new ObjectChangeEventStream(new NativeArray<Event>(m_Events, allocator), new NativeArray<byte>(m_Payload, allocator));
public void Dispose()
{
m_Events.Dispose();
m_Payload.Dispose();
}
public struct Builder : IDisposable
{
private NativeArray<Event> m_Events;
private NativeArray<byte> m_Payload;
private int m_EventCount;
private int m_PayloadSize;
public int eventCount => m_EventCount;
public Builder(Allocator allocator)
{
m_Events = new NativeArray<Event>(16, allocator, NativeArrayOptions.UninitializedMemory);
m_EventCount = 0;
m_Payload = new NativeArray<byte>(256, allocator, NativeArrayOptions.UninitializedMemory);
m_PayloadSize = 0;
}
public ObjectChangeEventStream ToStream(Allocator allocator)
{
var events = new NativeArray<Event>(m_EventCount, allocator, NativeArrayOptions.UninitializedMemory);
var payload = new NativeArray<byte>(m_PayloadSize, allocator, NativeArrayOptions.UninitializedMemory);
try
{
NativeArray<Event>.Copy(m_Events, 0, events, 0, m_EventCount);
NativeArray<byte>.Copy(m_Payload, 0, payload, 0, m_PayloadSize);
}
catch
{
events.Dispose();
payload.Dispose();
throw;
}
return new ObjectChangeEventStream(events, payload);
}
public void Dispose()
{
m_Events.Dispose();
m_Payload.Dispose();
}
public void PushChangeSceneEvent(ref ChangeSceneEventArgs data) =>
PushEvent(ObjectChangeKind.ChangeScene, ref data);
public void PushCreateGameObjectHierarchyEvent(ref CreateGameObjectHierarchyEventArgs data) =>
PushEvent(ObjectChangeKind.CreateGameObjectHierarchy, ref data);
public void PushDestroyGameObjectHierarchyEvent(ref DestroyGameObjectHierarchyEventArgs data) =>
PushEvent(ObjectChangeKind.DestroyGameObjectHierarchy, ref data);
public void PushChangeGameObjectStructureHierarchyEvent(ref ChangeGameObjectStructureHierarchyEventArgs data) =>
PushEvent(ObjectChangeKind.ChangeGameObjectStructureHierarchy, ref data);
public void PushChangeGameObjectStructureEvent(ref ChangeGameObjectStructureEventArgs data) =>
PushEvent(ObjectChangeKind.ChangeGameObjectStructure, ref data);
public void PushChangeGameObjectParentEvent(ref ChangeGameObjectParentEventArgs data) =>
PushEvent(ObjectChangeKind.ChangeGameObjectParent, ref data);
public void PushChangeGameObjectOrComponentPropertiesEvent(ref ChangeGameObjectOrComponentPropertiesEventArgs data) =>
PushEvent(ObjectChangeKind.ChangeGameObjectOrComponentProperties, ref data);
public void PushCreateAssetObjectEvent(ref CreateAssetObjectEventArgs data) =>
PushEvent(ObjectChangeKind.CreateAssetObject, ref data);
public void PushDestroyAssetObjectEvent(ref DestroyAssetObjectEventArgs data) =>
PushEvent(ObjectChangeKind.DestroyAssetObject, ref data);
public void PushChangeAssetObjectPropertiesEvent(ref ChangeAssetObjectPropertiesEventArgs data) =>
PushEvent(ObjectChangeKind.ChangeAssetObjectProperties, ref data);
public void PushUpdatePrefabInstancesEvent(ref UpdatePrefabInstancesEventArgs data)
{
Scene scene = data.scene;
PushEvent(ObjectChangeKind.UpdatePrefabInstances, ref scene);
AtomicSafetyHandle.CheckReadAndThrow(data.instanceIds.m_Safety);
unsafe
{
AppendToLastEvent(data.instanceIds.m_Buffer, data.instanceIds.m_Length * sizeof(int));
}
}
unsafe void PushEvent<T>(ObjectChangeKind kind, ref T data) where T : unmanaged
{
PushEvent(kind, UnsafeUtility.AddressOf(ref data), sizeof(T));
}
unsafe void PushEvent(ObjectChangeKind kind, void* data , int size)
{
ReallocMaybe(ref m_Events, m_EventCount, 1);
m_Events[m_EventCount] = new Event
{
ChangeKind = kind,
offset = m_PayloadSize,
size = size
};
m_EventCount += 1;
AppendPayLoad(data, size);
}
unsafe void AppendToLastEvent(void* data, int size)
{
AppendPayLoad(data, size);
var evt = m_Events[m_EventCount - 1];
evt.size += size;
m_Events[m_EventCount - 1] = evt;
}
unsafe void AppendPayLoad(void* data, int size)
{
ReallocMaybe(ref m_Payload, m_PayloadSize, size);
var ptr = (byte*)m_Payload.GetUnsafePtr() + m_PayloadSize;
UnsafeUtility.MemCpy(ptr, data, size);
m_PayloadSize += size;
}
static void ReallocMaybe<T>(ref NativeArray<T> arr, int size, int additional) where T : unmanaged
{
if (size + additional < arr.Length)
return;
int capacity = size + additional;
if (capacity < 2 * arr.Length)
capacity = 2 * arr.Length;
var newArr = new NativeArray<T>(capacity, arr.m_AllocatorLabel, NativeArrayOptions.UninitializedMemory);
NativeArray<T>.Copy(arr, 0, newArr, 0, size);
arr.Dispose();
arr = newArr;
}
}
}
}
| UnityCsReference/Editor/Mono/Undo/EditorObjectChangeEvents.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Undo/EditorObjectChangeEvents.cs",
"repo_id": "UnityCsReference",
"token_count": 9275
} | 351 |
// Unity 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
{
static class EnumUtility
{
[RequiredByNativeCode]
private static string ConvertEnumToString(Type enumType, int enumValue)
{
return Enum.GetName(enumType, enumValue);
}
}
}
| UnityCsReference/Editor/Mono/Utils/EnumUtility.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Utils/EnumUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 169
} | 352 |
// Unity 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 : IDisposable
{
private readonly Func<bool> hostProcessExited;
private readonly StreamReader stream;
internal List<string> lines;
private Thread thread;
internal ProcessOutputStreamReader(Process p, StreamReader stream) : this(() => p.HasExited, stream)
{
}
internal ProcessOutputStreamReader(Func<bool> hostProcessExited, StreamReader stream)
{
this.hostProcessExited = hostProcessExited;
this.stream = stream;
lines = new List<string>();
thread = new Thread(ThreadFunc);
thread.Start();
}
public void Dispose()
{
lock (stream)
{
stream.Dispose();
}
}
private void ThreadFunc()
{
try
{
while (true)
{
string line;
lock (stream)
{
if (stream == null || stream.BaseStream == null)
return;
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();
}
}
}
}
| UnityCsReference/Editor/Mono/Utils/ProcessOutputStreamReader.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Utils/ProcessOutputStreamReader.cs",
"repo_id": "UnityCsReference",
"token_count": 1308
} | 353 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.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<Asset>
{
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;
}
internal AssetList NaturalSort()
{
Sort((a, b) => EditorUtility.NaturalCompare(a.name, b.name));
return this;
}
}
}
| UnityCsReference/Editor/Mono/VersionControl/Common/VCAssetList.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/Common/VCAssetList.cs",
"repo_id": "UnityCsReference",
"token_count": 1357
} | 354 |
// 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.ShortcutManagement;
using UnityEditor.VersionControl;
namespace UnityEditorInternal.VersionControl
{
// Top-level VCS menu; set up and invoked from native code when VCS integration is turned on
class ProjectContextMenu
{
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Get Latest" menu handler
static bool GetLatestTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
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 selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
Provider.GetLatest(selected).SetCompletionAction(CompletionAction.UpdatePendingWindow);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Submit..." menu handler
static bool SubmitTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
return Provider.enabled && Provider.SubmitIsValid(null, selected);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Submit..." menu handler
static void Submit(MenuCommand cmd)
{
InspectorWindow.ApplyChanges();
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
WindowChange.Open(selected, true);
}
[Shortcut("Version Control/Submit Changeset")]
static void Submit(ShortcutArguments args)
{
Submit(null);
}
// 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)
{
AssetList selected = Provider.GetAssetListFromSelection();
Provider.Checkout(selected, CheckoutMode.Both);
}
[Shortcut("Version Control/Check Out")]
static void CheckOut(ShortcutArguments args)
{
CheckOut(null);
}
// 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/Mark Add" menu handler
static bool MarkAddTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
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 selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
Provider.Add(selected, true).SetCompletionAction(CompletionAction.UpdatePendingWindow);
}
[Shortcut("Version Control/Mark Add")]
static void MarkAdd(ShortcutArguments args)
{
MarkAdd(null);
}
/// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert..." menu handler
static bool RevertTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
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)
{
InspectorWindow.ApplyChanges();
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
WindowRevert.Open(selected);
}
[Shortcut("Version Control/Revert...")]
static void Revert(ShortcutArguments args)
{
Revert(null);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert Unchanged" menu handler
static bool RevertUnchangedTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
return Provider.enabled && Provider.RevertIsValid(selected, RevertMode.Unchanged);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Revert Unchanged" menu handler
static void RevertUnchanged(MenuCommand cmd)
{
InspectorWindow.ApplyChanges();
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
Provider.Revert(selected, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow);
Provider.Status(selected);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Diff Against Head..." menu handler
static bool ResolveTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
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();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
WindowResolve.Open(selected);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Lock" menu handler
static bool LockTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
return Provider.enabled && Provider.hasLockingSupport && Provider.LockIsValid(selected);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Lock" menu handler
static void Lock(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
Provider.Lock(selected, true).SetCompletionAction(CompletionAction.UpdatePendingWindow);
}
[Shortcut("Version Control/Lock")]
static void Lock(ShortcutArguments args)
{
Lock(null);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Unlock" menu handler
static bool UnlockTest(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
return Provider.enabled && Provider.hasLockingSupport && Provider.UnlockIsValid(selected);
}
// Called from native class VCSAssetMenuHandler as "Assets/Version Control/Unlock" menu handler
static void Unlock(MenuCommand cmd)
{
AssetList selected = Provider.GetAssetListFromSelection();
selected = Provider.ConsolidateAssetList(selected, CheckoutMode.Both);
Provider.Lock(selected, false).SetCompletionAction(CompletionAction.UpdatePendingWindow);
}
[Shortcut("Version Control/Unlock")]
static void Unlock(ShortcutArguments args)
{
Unlock(null);
}
// 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);
}
[Shortcut("Version Control/Diff Against Head...")]
static void DiffHead(ShortcutArguments args)
{
DiffHead(null);
}
// 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);
}
}
}
| UnityCsReference/Editor/Mono/VersionControl/UI/VCMenuProject.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/UI/VCMenuProject.cs",
"repo_id": "UnityCsReference",
"token_count": 4413
} | 355 |
// Unity 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.Runtime.InteropServices;
using UnityEngine.Bindings;
using UnityEngine.Internal;
using Object = UnityEngine.Object;
namespace UnityEditor
{
// Must be a struct in order to have correct comparison behaviour
[StructLayout(LayoutKind.Sequential)]
[ExcludeFromDocs]
public struct ExternalVersionControl
{
private readonly string m_Value;
public static readonly string Disabled = "Hidden Meta Files";
public static readonly string AutoDetect = "Auto detect";
public static readonly string Generic = "Visible Meta Files";
[Obsolete("Asset Server VCS support has been removed.")]
public static readonly string AssetServer = "Asset Server";
public ExternalVersionControl(string value)
{
m_Value = value;
}
// User-defined conversion
public static implicit operator string(ExternalVersionControl d)
{
return d.ToString();
}
// User-defined conversion
public static implicit operator ExternalVersionControl(string d)
{
return new ExternalVersionControl(d);
}
public override string ToString()
{
return m_Value;
}
}
[NativeHeader("Editor/Src/VersionControlSettings.h")]
[NativeHeader("Editor/Src/EditorUserSettings.h")]
public sealed class VersionControlSettings : Object
{
private VersionControlSettings()
{
}
[StaticAccessor("GetVersionControlSettings()", StaticAccessorType.Dot)]
[ExcludeFromDocs]
public static extern string mode
{
[NativeMethod("GetMode")]
get;
[NativeMethod("SetMode")]
set;
}
[StaticAccessor("GetVersionControlSettings()", StaticAccessorType.Dot)]
[ExcludeFromDocs]
public static extern bool trackPackagesOutsideProject { get; set; }
[StaticAccessor("GetEditorUserSettings()", StaticAccessorType.Dot)]
private static extern string GetConfigValue(string name);
[StaticAccessor("GetEditorUserSettings()", StaticAccessorType.Dot)]
private static extern void SetConfigValue(string name, string value);
}
}
| UnityCsReference/Editor/Mono/VersionControlSettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControlSettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 917
} | 356 |
//
// File autogenerated from Include/C/Baselib_DynamicLibrary.h
//
using System;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using size_t = System.UIntPtr;
namespace Unity.Baselib.LowLevel
{
[NativeHeader("baselib/CSharp/BindingsUnity/Baselib_DynamicLibrary.gen.binding.h")]
internal static unsafe partial class Binding
{
[StructLayout(LayoutKind.Sequential)]
public struct Baselib_DynamicLibrary_Handle
{
public IntPtr handle;
}
/// <summary>Open a dynamic library.</summary>
/// <remarks>
/// Dynamic libraries are reference counted, so if the same library is loaded again
/// with Baselib_DynamicLibrary_OpenUtf8/Baselib_DynamicLibrary_OpenUtf16, the same file handle is returned.
/// It is also possible to load two different libraries containing two different functions that have the same name.
///
/// Please note that additional error information should be retrieved via error state explain and be presented to the end user.
/// This is needed to improve ergonomics of debugging library loading issues.
///
/// Possible error codes:
/// - Baselib_ErrorCode_FailedToOpenDynamicLibrary: Unable to open requested dynamic library.
/// - Baselib_ErrorCode_NotSupported: This feature is not supported on the current platform.
/// </remarks>
/// <param name="pathnameUtf8">
/// Library file to be opened.
/// If relative pathname is provided, platform library search rules are applied (if any).
/// If nullptr is passed, Baselib_ErrorCode_InvalidArgument will be risen.
/// </param>
[FreeFunction(IsThreadSafe = true)]
public static extern Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenUtf8(byte* pathnameUtf8, Baselib_ErrorState* errorState);
/// <summary>
/// Open a dynamic library.
/// Functionally identical to Baselib_DynamicLibrary_OpenUtf8, but accepts UTF-16 path instead.
/// </summary>
[FreeFunction(IsThreadSafe = true)]
public static extern Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenUtf16(char* pathnameUtf16, Baselib_ErrorState* errorState);
/// <summary>
/// Return a handle that can be used to query functions in the program's scope.
/// Must be closed via Baselib_DynamicLibrary_Close.
/// </summary>
/// <remarks>
/// Possible error codes:
/// - Baselib_ErrorCode_NotSupported: This feature is not supported on the current platform.
/// </remarks>
[FreeFunction(IsThreadSafe = true)]
public static extern Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenProgramHandle(Baselib_ErrorState* errorState);
/// <summary>Convert native handle into baselib handle without changing the dynamic library ref counter.</summary>
/// <remarks>
/// Provided handle should be closed either via Baselib_DynamicLibrary_Close or other means.
/// The caller is responsible for closing the handle once done with it.
/// Other corresponding resources should be closed by other means.
/// </remarks>
/// <param name="handle">Platform defined native handle.</param>
/// <param name="type">
/// Platform defined native handle type from Baselib_DynamicLibrary_NativeHandleType enum.
/// If unsupported type is passed, will return Baselib_DynamicLibrary_Handle_Invalid.
/// </param>
/// <returns>Baselib_DynamicLibrary_Handle handle.</returns>
[FreeFunction(IsThreadSafe = true)]
public static extern Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_FromNativeHandle(UInt64 handle, UInt32 type, Baselib_ErrorState* errorState);
/// <summary>Lookup a function in a dynamic library.</summary>
/// <remarks>
/// Possible error codes:
/// - Baselib_ErrorCode_FunctionNotFound: Requested function was not found.
/// </remarks>
/// <param name="handle">
/// Library handle.
/// If Baselib_DynamicLibrary_Handle_Invalid is passed, Baselib_ErrorCode_InvalidArgument will be risen.
/// </param>
/// <param name="functionName">
/// Function name to look for.
/// If nullptr is passed, Baselib_ErrorCode_InvalidArgument will be risen.
/// </param>
/// <returns>pointer to the function (can be NULL for symbols mapped to NULL).</returns>
[FreeFunction(IsThreadSafe = true)]
public static extern IntPtr Baselib_DynamicLibrary_GetFunction(Baselib_DynamicLibrary_Handle handle, byte* functionName, Baselib_ErrorState* errorState);
/// <summary>Close a dynamic library.</summary>
/// <remarks>
/// Decreases reference counter, if it becomes zero, closes the library.
/// If system api will return an error during this operation, the process will be aborted.
/// </remarks>
/// <param name="handle">
/// Library handle.
/// If Baselib_DynamicLibrary_Handle_Invalid is passed, function is no-op.
/// </param>
[FreeFunction(IsThreadSafe = true)]
public static extern void Baselib_DynamicLibrary_Close(Baselib_DynamicLibrary_Handle handle);
}
}
| UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_DynamicLibrary.gen.binding.cs/0 | {
"file_path": "UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_DynamicLibrary.gen.binding.cs",
"repo_id": "UnityCsReference",
"token_count": 1861
} | 357 |
using System;
namespace Unity.Baselib.LowLevel
{
internal static partial class Binding
{
public static readonly Baselib_Memory_PageAllocation Baselib_Memory_PageAllocation_Invalid = new Baselib_Memory_PageAllocation();
public static readonly Baselib_RegisteredNetwork_Socket_UDP Baselib_RegisteredNetwork_Socket_UDP_Invalid = new Baselib_RegisteredNetwork_Socket_UDP();
public static readonly Baselib_Socket_Handle Baselib_Socket_Handle_Invalid = new Baselib_Socket_Handle { handle = (IntPtr)(-1) };
public static readonly Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_Handle_Invalid = new Baselib_DynamicLibrary_Handle { handle = (IntPtr)(-1) };
public static readonly Baselib_FileIO_EventQueue Baselib_FileIO_EventQueue_Invalid = new Baselib_FileIO_EventQueue { handle = (IntPtr)0 };
public static readonly Baselib_FileIO_AsyncFile Baselib_FileIO_AsyncFile_Invalid = new Baselib_FileIO_AsyncFile { handle = (IntPtr)0 };
public static readonly Baselib_FileIO_SyncFile Baselib_FileIO_SyncFile_Invalid = new Baselib_FileIO_SyncFile { handle = (IntPtr)(-1) };
}
}
| UnityCsReference/External/baselib/baselib/CSharp/ManualBindings.cs/0 | {
"file_path": "UnityCsReference/External/baselib/baselib/CSharp/ManualBindings.cs",
"repo_id": "UnityCsReference",
"token_count": 390
} | 358 |
// Unity 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.AI
{
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
[Flags]
public enum NavMeshBuildDebugFlags
{
None = 0,
InputGeometry = 1 << 0,
Voxels = 1 << 1,
Regions = 1 << 2,
RawContours = 1 << 3,
SimplifiedContours = 1 << 4,
PolygonMeshes = 1 << 5,
PolygonMeshesDetail = 1 << 6,
All = unchecked((int)(~(~0U << 7)))
}
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
public enum NavMeshBuildSourceShape
{
Mesh = 0,
Terrain = 1,
Box = 2,
Sphere = 3,
Capsule = 4,
ModifierBox = 5
}
// Keep this enum in sync with the one defined in "NavMeshBindingTypes.h"
public enum NavMeshCollectGeometry
{
RenderMeshes = 0,
PhysicsColliders = 1
}
// Struct containing source geometry data and annotation for runtime navmesh building
[UsedByNativeCode]
[NativeHeader("Modules/AI/Public/NavMeshBindingTypes.h")]
public struct NavMeshBuildSource
{
public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } }
public Vector3 size { get { return m_Size; } set { m_Size = value; } }
public NavMeshBuildSourceShape shape { get { return m_Shape; } set { m_Shape = value; } }
public int area { get { return m_Area; } set { m_Area = value; } }
public bool generateLinks { get { return m_GenerateLinks != 0; } set { m_GenerateLinks = value ? 1 : 0; } }
public Object sourceObject { get { return InternalGetObject(m_InstanceID); } set { m_InstanceID = value != null ? value.GetInstanceID() : 0; } }
public Component component { get { return InternalGetComponent(m_ComponentID); } set { m_ComponentID = value != null ? value.GetInstanceID() : 0; } }
Matrix4x4 m_Transform;
Vector3 m_Size;
NavMeshBuildSourceShape m_Shape;
int m_Area;
int m_InstanceID;
int m_ComponentID;
int m_GenerateLinks;
[StaticAccessor("NavMeshBuildSource", StaticAccessorType.DoubleColon)]
static extern Component InternalGetComponent(int instanceID);
[StaticAccessor("NavMeshBuildSource", StaticAccessorType.DoubleColon)]
static extern Object InternalGetObject(int instanceID);
}
// Struct containing source geometry data and annotation for runtime navmesh building
[NativeHeader("Modules/AI/Public/NavMeshBindingTypes.h")]
public struct NavMeshBuildMarkup
{
public bool overrideArea { get { return m_OverrideArea != 0; } set { m_OverrideArea = value ? 1 : 0; } }
public int area { get { return m_Area; } set { m_Area = value; } }
public bool overrideIgnore { get { return m_InheritIgnoreFromBuild == 0; } set { m_InheritIgnoreFromBuild = value ? 0: 1; } }
public bool ignoreFromBuild { get { return m_IgnoreFromBuild != 0; } set { m_IgnoreFromBuild = value ? 1 : 0; } }
public bool overrideGenerateLinks { get { return m_OverrideGenerateLinks != 0; } set { m_OverrideGenerateLinks = value ? 1 : 0; } }
public bool generateLinks { get { return m_GenerateLinks != 0; } set { m_GenerateLinks = value ? 1 : 0; } }
public bool applyToChildren { get { return m_IgnoreChildren == 0; } set { m_IgnoreChildren = value ? 0 : 1; } }
public Transform root { get { return InternalGetRootGO(m_InstanceID); } set { m_InstanceID = value != null ? value.GetInstanceID() : 0; } }
int m_OverrideArea;
int m_Area;
int m_InheritIgnoreFromBuild; // backing field is reversed for the default value to align with the legacy default behaviour
int m_IgnoreFromBuild;
int m_OverrideGenerateLinks;
int m_GenerateLinks;
int m_InstanceID;
int m_IgnoreChildren; // backing field is reversed for the default value to align with the legacy default behaviour
[StaticAccessor("NavMeshBuildMarkup", StaticAccessorType.DoubleColon)]
static extern Transform InternalGetRootGO(int instanceID);
}
}
| UnityCsReference/Modules/AI/Public/NavMeshBindingTypes.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/AI/Public/NavMeshBindingTypes.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1610
} | 359 |
// Unity 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.Bindings;
namespace UnityEngine.Accessibility
{
/// <summary>
/// Represents the hierarchy data model that the screen reader uses for reading and navigating the UI.
/// </summary>
/// <remarks>
/// A hierarchy must be set to active through <see cref="AssistiveSupport.activeHierarchy"/> when the screen
/// reader is on for the screen reader to function. If a hierarchy is not set active, the screen reader cannot read and
/// navigate through the UI. Once an active hierarchy is set, if the hierarchy is modified, the screen reader must
/// be notified by calling <see cref="AssistiveSupport.NotificationDispatcher.SendLayoutChanged"/> or
/// <see cref="AssistiveSupport.NotificationDispatcher.SendScreenChanged"/> (depending if the changes are only at
/// the layout level, or a more considerable screen change). Modifications in the hierarchy consist of calls to:
///
///- <see cref="AccessibilityHierarchy.AddNode"/>
///- <see cref="AccessibilityHierarchy.Clear"/>
///- <see cref="AccessibilityHierarchy.InsertNode"/>
///- <see cref="AccessibilityHierarchy.MoveNode"/>
///- <see cref="AccessibilityHierarchy.RemoveNode"/>
///- Modifications to node <see cref="AccessibilityNode.frame"/> values.
///
/// </remarks>
public class AccessibilityHierarchy
{
internal List<AccessibilityNode> m_RootNodes;
/// <summary>
/// The root nodes of the hierarchy.
/// </summary>
public IReadOnlyList<AccessibilityNode> rootNodes => m_RootNodes;
/// <summary>
/// One of two reusable stacks for finding the lowest common ancestor in the hierarchy
/// </summary>
Stack<AccessibilityNode> m_FirstLowestCommonAncestorChain;
/// <summary>
/// One of two reusable stacks for finding the lowest common ancestor in the hierarchy
/// </summary>
Stack<AccessibilityNode> m_SecondLowestCommonAncestorChain;
/// <summary>
/// The next unique ID that can be assigned to a new node. This is a static value and
/// therefore shared among all instances of AccessibilityHierarchy, in order to guarantee ID uniqueness and
/// avoid confusion of looking for an ID in a hierarchy that does not contain the node that ID originally
/// belonged to.
/// </summary>
static int m_NextUniqueNodeId;
/// <summary>
/// The collection of nodes and associated data in the hierarchy that can be accessed by the node ID as a key.
/// </summary>
readonly IDictionary<int, AccessibilityNode> m_Nodes;
event Action<AccessibilityHierarchy> m_Changed;
/// <summary>
/// Event sent when the hierarchy changes.
/// </summary>
internal event Action<AccessibilityHierarchy> changed
{
[VisibleToOtherModules("UnityEditor.AccessibilityModule")]
add => m_Changed += value;
[VisibleToOtherModules("UnityEditor.AccessibilityModule")]
remove => m_Changed -= value;
}
/// <summary>
/// Initializes and returns an instance of an AccessibilityHierarchy.
/// </summary>
public AccessibilityHierarchy()
{
// Initialize the collections
m_FirstLowestCommonAncestorChain = new Stack<AccessibilityNode>();
m_SecondLowestCommonAncestorChain = new Stack<AccessibilityNode>();
m_Nodes = new Dictionary<int, AccessibilityNode>();
m_RootNodes = new List<AccessibilityNode>();
}
internal void NotifyHierarchyChanged()
{
m_Changed?.Invoke(this);
}
/// <summary>
/// Resets the hierarchy to an empty state, removing all the nodes and removing focus.
/// </summary>
public void Clear()
{
for (var i = m_RootNodes.Count - 1; i >= 0; i--)
{
RemoveNode(m_RootNodes[i], removeChildren: true);
}
}
/// <summary>
/// Tries to get the node in this hierarchy that has the given ID.
/// </summary>
/// <param name="id">The ID of the node to retrieve.</param>
/// <param name="node">The valid node with the associated ID, or @@null@@ if no such node exists in this hierarchy.</param>
/// <returns>Returns true if a node is found and false otherwise.</returns>
public bool TryGetNode(int id, out AccessibilityNode node)
{
return m_Nodes.TryGetValue(id, out node);
}
/// <summary>
/// Creates and adds a new node with the given label in this hierarchy under the given parent node. If no parent is
/// provided, the new node is added as a root in the hierarchy.
/// </summary>
/// <param name="label">A label that succinctly describes the accessibility node.</param>
/// <param name="parent">The parent of the node being added. When the value given is @@null@@, the created node
/// is placed at the root level.</param>
/// <returns>The node created and added.</returns>
public AccessibilityNode AddNode(string label = null, AccessibilityNode parent = null)
{
return InsertNode(-1, label, parent);
}
/// <summary>
/// Creates and inserts a new node with the given label at the given index in this hierarchy under the given parent node.
/// If no parent is provided, the new node is inserted at the given index as a root in the hierarchy.
/// </summary>
/// <param name="childIndex">A zero-based index for positioning the inserted node in the parent's children list,
/// or in the list of roots if the node is a root node. If the index is invalid, the inserted node will be the
/// last child of its parent (or the last root node).</param>
/// <param name="label">A label that succinctly describes the accessibility node.</param>
/// <param name="parent">The parent of the node being added. When the value given is @@null@@, the created node
/// is placed at the root level.</param>
/// <returns>The node created and inserted.</returns>
public AccessibilityNode InsertNode(int childIndex, string label = null, AccessibilityNode parent = null)
{
// Only nodes intended as roots may have an invalid parent.
if (parent != null)
ValidateNodeInHierarchy(parent);
// Generate a new node to return, then add it to the manager under it's parent
var node = GenerateNewNode();
m_Nodes[node.id] = node;
if (label != null)
{
node.label = label;
}
SetParent(node, parent, null, parent == null ? m_RootNodes : parent.childList, childIndex);
NotifyHierarchyChanged();
return node;
}
/// <summary>
/// Moves the node elsewhere in the hierarchy, which causes the given node to be parented by a different node
/// in the hierarchy. An optional index can be supplied for specifying the position within the list of children the
/// moved node should take (zero-based). If no index is supplied, the node is added as the last child of the new parent by default.
/// <para>Root nodes can be moved elsewhere in the hierarchy, therefore ceasing to be a root.
/// Non-root nodes can be moved to become a root node by providing @@null@@ as the new parent node.</para>
/// <para>__Warning:__ The moving operation is costly as many checks have to be executed to guarantee the integrity of
/// the hierarchy. Therefore this operation should not be done excessively as it may affect performance.</para>
/// </summary>
/// <param name="node">The node to move.</param>
/// <param name="newParent">The new parent of the moved node, or @@null@@ if the moved node should be made into a root node.</param>
/// <param name="newChildIndex">An optional zero-based index for positioning the moved node in the new parent's children list, or in the list of
/// roots if the node is becoming a root node. If the index is not provided or is invalid, the moved node will be the last child of its parent.</param>
/// <returns>Whether the node was successfully moved.</returns>
public bool MoveNode(AccessibilityNode node, AccessibilityNode newParent, int newChildIndex = -1)
{
ValidateNodeInHierarchy(node);
// Check if node is valid to move
if (node == newParent)
{
throw new ArgumentException($"Attempting to move the node {node} under itself.");
}
if (node.parent == newParent)
{
// If the node we are trying to move is already at the right location, we are done
var parentList = newParent == null ? m_RootNodes : newParent.childList;
if (newChildIndex == parentList.IndexOf(node))
{
return false;
}
// Keep parent, move index
CheckForLoopsAndSetParent(node, newParent, newChildIndex);
return true;
}
// Making node a root
if (newParent == null)
{
// If the node is already a root, there's nothing to do
if (node.parent == null)
{
return false;
}
CheckForLoopsAndSetParent(node, null, newChildIndex);
return true;
}
ValidateNodeInHierarchy(newParent);
// Update node relationships (SetParent checks for loops)
CheckForLoopsAndSetParent(node, newParent, newChildIndex);
NotifyHierarchyChanged();
return true;
}
/// <summary>
/// Removes the node from the hierarchy. Can also optionally remove nodes under the given node depending on the value of
/// the <see cref="removeChildren"/> parameter.
/// </summary>
/// <param name="node">The node to remove.</param>
/// <param name="removeChildren">Default value is @@true@@. If removeChildren is @@false@@, Unity grafts the child nodes to the parent.</param>
public void RemoveNode(AccessibilityNode node, bool removeChildren = true)
{
ValidateNodeInHierarchy(node);
if (removeChildren)
{
void removeFromNodes(AccessibilityNode child)
{
m_Nodes.Remove(child.id);
for (var i = 0; i < child.childList.Count; i++)
{
removeFromNodes(child.childList[i]);
}
};
removeFromNodes(node);
}
else
{
m_Nodes.Remove(node.id);
}
if (m_RootNodes.Contains(node))
{
m_RootNodes.Remove(node);
// If we aren't removing the children, add them as roots (AccessibilityNode.Destroy will handle updating the parent value).
if (!removeChildren)
{
m_RootNodes.AddRange(node.childList);
}
}
node.Destroy(removeChildren);
NotifyHierarchyChanged();
}
/// <summary>
/// Returns whether a given node exists in the hierarchy.
/// </summary>
/// <param name="node">The node to search for in the hierarchy.</param>
/// <returns>Whether the node exists in this hierarchy.</returns>
public bool ContainsNode(AccessibilityNode node)
{
return node != null && m_Nodes.ContainsKey(node.id) && m_Nodes[node.id] == node;
}
private void CheckForLoopsAndSetParent(AccessibilityNode node, AccessibilityNode parent, int newChildIndex = -1)
{
// We don't validate the nodes are in the hierarchy here as this is a private method and we guarantee this is
// only called when we're sure both given parameters are valid.
// Edge case: moving the node to be a root, so no need to check for loops
if (parent == null)
{
SetParent(node, null, node.parent?.childList ?? m_RootNodes, m_RootNodes, newChildIndex);
return;
}
// Edge case: potentially only moving the index of the child, keeping the same parent
if (node.parent == parent)
{
SetParent(node, parent, parent.childList, parent.childList, newChildIndex);
return;
}
// Edge case: both nodes are roots, so no need to check for loops
if (node.parent == null && parent.parent == null)
{
SetParent(node, parent, m_RootNodes, parent.childList, newChildIndex);
return;
}
var ancestor = parent.parent;
// If the node exists in any of the ancestral nodes of the parent, then we are creating a loop, which is invalid.
while (ancestor != null)
{
if (ancestor == node)
{
throw new ArgumentException($"Trying to set the node {node} to have parent {parent}, but this would create a loop.");
}
ancestor = ancestor.parent;
}
SetParent(node, parent, node.parent?.childList ?? m_RootNodes, parent.childList, newChildIndex);
}
private void SetParent(AccessibilityNode node, AccessibilityNode parent, IList<AccessibilityNode> previousParentChildren, IList<AccessibilityNode> newParentChildren, int newChildIndex = -1)
{
// Update references for both old and new parents and child
previousParentChildren?.Remove(node);
node.SetParent(parent, newChildIndex);
if (newChildIndex < 0 || newChildIndex > newParentChildren.Count)
{
newParentChildren.Add(node);
}
else
{
newParentChildren.Insert(newChildIndex, node);
}
}
internal void AllocateNative()
{
foreach (var rootNode in m_RootNodes)
{
rootNode.AllocateNative();
}
}
internal void FreeNative()
{
foreach (var rootNode in m_RootNodes)
{
// We're freeing the whole hierarchy, so children of roots also get freed.
rootNode.FreeNative(freeChildren: true);
}
}
/// <summary>
/// Refreshes all the node frames (i.e. the screen elements' positions) for the hierarchy.
/// </summary>
/// <remarks>
/// Calling this method sends a notification to the operating system that the layout has changed, by
/// calling <see cref="IAccessibilityNotificationDispatcher.SendLayoutChanged"/> (with a @@null@@ parameter).
/// </remarks>
/// <seealso cref="AccessibilityNode.frame"/>
/// <seealso cref="AccessibilityNode.frameGetter"/>
public void RefreshNodeFrames()
{
foreach (var node in m_Nodes.Values)
{
node.CalculateFrame();
}
AssistiveSupport.OnHierarchyNodeFramesRefreshed(this);
}
/// <summary>
/// Tries to retrieve the node at the given position on the screen.
/// </summary>
/// <param name="horizontalPosition">The horizontal position on the screen.</param>
/// <param name="verticalPosition">The vertical position on the screen.</param>
/// <param name="node">The node found at that screen position, or @@null@@ if there are no nodes at that position.</param>
/// <returns>Returns true if a node is found and false otherwise.</returns>
public bool TryGetNodeAt(float horizontalPosition, float verticalPosition, out AccessibilityNode node)
{
var position = new Vector2(horizontalPosition, verticalPosition);
AccessibilityNode FindNodeContainingPoint(IList<AccessibilityNode> nodes, Vector2 pos)
{
// Perform BFS (Breadth First Search) PostOrder Traversal in reverse order to find the last (at the top) node containing the specified point.
for (var i = nodes.Count - 1; i >= 0; --i)
{
var curNode = nodes[i];
// If the node is disabled then ignore it and its children as they are also considered disabled.
// Unlike the disabled state, a node can be inactive while its children are active. This is why we
// still seek for children of a node regardless of its active state.
if (curNode.state.HasFlag(AccessibilityState.Disabled))
continue;
var childNodeContainingPoint = FindNodeContainingPoint(curNode.childList, pos);
if (childNodeContainingPoint != null)
return childNodeContainingPoint;
// Ignore inactive node
if (curNode.isActive && curNode.frame.Contains(pos))
return curNode;
}
return null;
}
node = FindNodeContainingPoint(m_RootNodes, position);
return node != null;
}
/// <summary>
/// Retrieves the lowest common ancestor of two nodes in the hierarchy.<br/>
/// The lowest common ancestor is the node that is the common node that both nodes share in their path to the root node
/// of their branch in the hierarchy.
/// </summary>
/// <param name="firstNode">The first node to find the lowest common ancestor of.</param>
/// <param name="secondNode">The second node to find the lowest common ancestor of.</param>
/// <returns>The lowest common ancestor of the two given nodes, or @@null@@ if there is no common ancestor.</returns>
public AccessibilityNode GetLowestCommonAncestor(AccessibilityNode firstNode, AccessibilityNode secondNode)
{
// Edge case: one of the given parameters is null.
if (firstNode == null || secondNode == null)
{
return null;
}
// Edge case: both nodes are roots, so there is no common ancestor.
if (firstNode.parent == null && secondNode.parent == null)
{
return null;
}
// Edge case: one of the nodes is not in this hierarchy.
if (!ContainsNode(firstNode) || !ContainsNode(secondNode))
{
return null;
}
// Use local function to build the ID chains for both nodes
void buildNodeIdStack(AccessibilityNode node, ref Stack<AccessibilityNode> nodeStack)
{
// Traverse up the hierarchy until we reach the root of the current node
while (node != null)
{
nodeStack.Push(node);
node = m_Nodes[node.id].parent;
}
}
// Set up the ID stacks
m_FirstLowestCommonAncestorChain.Clear();
m_SecondLowestCommonAncestorChain.Clear();
buildNodeIdStack(firstNode, ref m_FirstLowestCommonAncestorChain);
buildNodeIdStack(secondNode, ref m_SecondLowestCommonAncestorChain);
// Start with no common ancestor, as nodes might not be in the same branch of the hierarchy
AccessibilityNode commonAncestor = null;
// Find the deepest level the lowest common ancestor can be on
var hierarchyLevelsToSearch = Mathf.Min(m_FirstLowestCommonAncestorChain.Count, m_SecondLowestCommonAncestorChain.Count);
// The first node that doesn't match or doesn't exist among the chains is the common ancestor
while (hierarchyLevelsToSearch > 0)
{
var firstChainNodeId = m_FirstLowestCommonAncestorChain.Pop();
var secondChainNodeId = m_SecondLowestCommonAncestorChain.Pop();
if (firstChainNodeId != secondChainNodeId)
{
// If the nodes no longer match, we have the lowest common ancestor
break;
}
// If the nodes do match, they share the same ancestor at this level
commonAncestor = firstChainNodeId;
hierarchyLevelsToSearch--;
}
return commonAncestor;
}
/// <summary>
/// Generates a new node that is unique for the hierarchy.
/// </summary>
/// <returns>The node created.</returns>
internal AccessibilityNode GenerateNewNode()
{
// Validate we can actually generate new nodes, meaning we still have a valid ID value to set to a node
if (m_NextUniqueNodeId >= int.MaxValue)
{
throw new Exception($"Could not generate unique node for hierarchy. A hierarchy may only have up to {int.MaxValue} nodes.");
}
// Create new instance of a node and increment the control for the ID so the next node created gets a new and valid value
var node = new AccessibilityNode(m_NextUniqueNodeId, this);
m_NextUniqueNodeId = node.id + 1;
return node;
}
/// <summary>
/// Validates the given node is not @@null@@ and part of this hierarchy.
/// </summary>
/// <param name="node">The AccessibilityNode instance to be validated as part of this hierarchy.</param>
/// <exception cref="ArgumentException">If the node is not part of this hierarchy.</exception>
private void ValidateNodeInHierarchy(AccessibilityNode node)
{
if (node != null)
{
if (ContainsNode(node))
{
return;
}
}
else
{
throw new ArgumentNullException(nameof(node));
}
throw new ArgumentException($"Trying to use an AccessibilityNode with ID {node.id} that is not part of this hierarchy.");
}
}
}
| UnityCsReference/Modules/Accessibility/Managed/Hierarchy/AccessibilityHierarchy.cs/0 | {
"file_path": "UnityCsReference/Modules/Accessibility/Managed/Hierarchy/AccessibilityHierarchy.cs",
"repo_id": "UnityCsReference",
"token_count": 9428
} | 360 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using Unity.Collections;
namespace UnityEngine.Android
{
public enum ProcessImportance
{
/// <summary>
/// <para>This process is running the foreground UI; that is, it is the thing currently at the top of the screen that the user is interacting with.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_FOREGROUND">developer.android.com</seealso>
/// </summary>
Foreground = 100,
/// <summary>
/// <para>This process is running a foreground service, for example to perform music playback even while the user is not immediately in the app. This generally indicates that the process is doing something the user actively cares about.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_FOREGROUND_SERVICE">developer.android.com</seealso>
/// </summary>
ForeGroundService = 125,
/// <summary>
/// <para>This process is running something that is actively visible to the user, though not in the immediate foreground. This may be running a window that is behind the current foreground (so paused and with its state saved, not interacting with the user, but visible to them to some degree); it may also be running other services under the system's control that it inconsiders important.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_VISIBLE">developer.android.com</seealso>
/// </summary>
Visible = 200,
/// <summary>
/// <para>This process is not something the user is directly aware of, but is otherwise perceptible to them to some degree.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_PERCEPTIBLE">developer.android.com</seealso>
/// </summary>
Perceptible = 230,
/// <summary>
/// <para>This process is running the foreground UI, but the device is asleep so it is not visible to the user. Though the system will try hard to keep its process from being killed, in all other ways we consider it a kind of cached process, with the limitations that go along with that state: network access, running background services, etc.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_TOP_SLEEPING">developer.android.com</seealso>
/// </summary>
TopSleeping = 325,
/// <summary>
/// <para>This process is running an application that can not save its state, and thus can't be killed while in the background. This will be used with apps that have R.attr.cantSaveState set on their application tag.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_CANT_SAVE_STATE">developer.android.com</seealso>
/// </summary>
CantSaveState = 350,
/// <summary>
/// <para>This process contains services that should remain running. These are background services apps have started, not something the user is aware of, so they may be killed by the system relatively freely (though it is generally desired that they stay running as long as they want to).</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_SERVICE">developer.android.com</seealso>
/// </summary>
Service = 300,
/// <summary>
/// <para>This process process contains cached code that is expendable, not actively running any app components we care about.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_CACHED">developer.android.com</seealso>
/// </summary>
Cached = 400,
/// <summary>
/// <para>This process does not exist.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ActivityManager.RunningAppProcessInfo#IMPORTANCE_GONE">developer.android.com</seealso>
/// </summary>
Gone = 1000
}
public enum ExitReason
{
/// <summary>
/// <para>Application process died due to unknown reason.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_UNKNOWN">developer.android.com</seealso>
/// </summary>
Unknown = 0,
/// <summary>
/// <para>Application process exit normally by itself, for example, via System.exit(int); getStatus() will specify the exit code.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_EXIT_SELF">developer.android.com</seealso>
/// </summary>
ExitSelf = 1,
/// <summary>
/// <para>Application process died due to the result of an OS signal; for example, OsConstants.SIGKILL; getStatus() will specify the signal number.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_SIGNALED">developer.android.com</seealso>
/// </summary>
Signaled = 2,
/// <summary>
/// <para>Application process was killed by the system low memory killer, meaning the system was under memory pressure at the time of kill.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_LOW_MEMORY">developer.android.com</seealso>
/// </summary>
LowMemory = 3,
/// <summary>
/// <para>Application process died because of an unhandled exception in Java code.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_CRASH">developer.android.com</seealso>
/// </summary>
Crash = 4,
/// <summary>
/// <para>Application process died because of a native code crash.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_CRASH_NATIVE">developer.android.com</seealso>
/// </summary>
CrashNative = 5,
/// <summary>
/// <para>Application process was killed due to being unresponsive (ANR).</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_ANR">developer.android.com</seealso>
/// </summary>
ANR = 6,
/// <summary>
/// <para>Application process was killed because of initialization failure, for example, it took too long to attach to the system during the start, or there was an error during initialization.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_INITIALIZATION_FAILURE">developer.android.com</seealso>
/// </summary>
InititalizationFailure = 7,
/// <summary>
/// <para>Application process was killed due to a runtime permission change.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_PERMISSION_CHANGE">developer.android.com</seealso>
/// </summary>
PermissionChange = 8,
/// <summary>
/// <para>Application process was killed by the system due to excessive resource usage.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_EXCESSIVE_RESOURCE_USAGE">developer.android.com</seealso>
/// </summary>
ExcessiveResourceUsage = 9,
/// <summary>
/// <para>Application process was killed because of the user request, for example, user clicked the "Force stop" button of the application in the Settings, or removed the application away from Recents.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_USER_REQUESTED">developer.android.com</seealso>
/// </summary>
UserRequested = 10,
/// <summary>
/// <para>Application process was killed, because the user it is running as on devices with mutlple users, was stopped.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_USER_STOPPED">developer.android.com</seealso>
/// </summary>
UserStopped = 11,
/// <summary>
/// <para>Application process was killed because its dependency was going away, for example, a stable content provider connection's client will be killed if the provider is killed.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_DEPENDENCY_DIED">developer.android.com</seealso>
/// </summary>
DependencyDied = 12,
/// <summary>
/// <para>Application process was killed by the system for various other reasons which are not by problems in apps and not actionable by apps, for example, the system just finished updates; getDescription() will specify the cause given by the system.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_OTHER">developer.android.com</seealso>
/// </summary>
Other = 13,
/// <summary>
/// <para>Application process was killed by App Freezer, for example, because it receives sync binder transactions while being frozen.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_FREEZER">developer.android.com</seealso>
/// </summary>
Freezer = 14,
/// <summary>
/// <para>Application process was killed because the app was disabled, or any of its component states have changed without PackageManager.DONT_KILL_APP</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_PACKAGE_STATE_CHANGE">developer.android.com</seealso>
/// </summary>
PackageStateChange = 15,
/// <summary>
/// <para>Application process was killed because it was updated.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#REASON_PACKAGE_UPDATED">developer.android.com</seealso>
/// </summary>
PackageUpdated = 16
}
public interface IApplicationExitInfo
{
/// <summary>
/// <para>The human readable description of the process's death, given by the system; could be null.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getDescription()">developer.android.com</seealso>
/// </summary>
/// <returns>string</returns>
string description { get; }
/// <summary>
/// <para>Describe the kinds of special objects contained in this Parcelable instance's marshaled representation.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#describeContents()">developer.android.com</seealso>
/// </summary>
/// <returns>a bitmask indicating the set of special object types marshaled by this Parcelable object instance. Value is either 0 or CONTENTS_FILE_DESCRIPTOR</returns>
int describeContents { get; }
/// <summary>
/// <para>Return the defining kernel user identifier, maybe different from getRealUid() and getPackageUid(), if an external service has the android:useAppZygote set to true and was bound with the flag Context.BIND_EXTERNAL_SERVICE - in this case, this field here will be the kernel user identifier of the external service provider.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getDefiningUid()">developer.android.com</seealso>
/// </summary>
/// <returns>int</returns>
int definingUid { get; }
/// <summary>
/// <para>The importance of the process that it used to have before the death.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getImportance()">developer.android.com</seealso>
/// </summary>
/// <returns>ProcessImportance</returns>
ProcessImportance importance { get; }
/// <summary>
/// <para>Similar to getRealUid(), it's the kernel user identifier that is assigned at the package installation time.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getPackageUid()">developer.android.com</seealso>
/// </summary>
/// <returns>int</returns>
int packageUid { get; }
/// <summary>
/// <para>The process id of the process that died.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getPid()">developer.android.com</seealso>
/// </summary>
/// <returns>int</returns>
int pid { get; }
/// <summary>
/// <para>The actual process name it was running with.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getProcessName()">developer.android.com</seealso>
/// </summary>
/// <returns>String</returns>
String processName { get; }
/// <summary>
/// <para>Return the state data set by calling ApplicationExitInfoProvider.setProcessStateSummary(byte[]) from the process before its death.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getProcessStateSummary()">developer.android.com</seealso>
/// </summary>
/// <returns>byte[] containing the process-customized data. This value may be null.</returns>
sbyte[] processStateSummary { get; }
/// <summary>
/// <para>Last proportional set size of the memory that the process had used in kB.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getPss()">developer.android.com</seealso>
/// </summary>
/// <returns>long</returns>
long pss { get; }
/// <summary>
/// <para>The kernel user identifier of the process, most of the time the system uses this to do access control checks.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getRealUid()">developer.android.com</seealso>
/// </summary>
/// <returns>int</returns>
int realUid { get; }
/// <summary>
/// <para>The reason code of the process's death.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getReason()">developer.android.com</seealso>
/// </summary>
/// <returns>ExitReason</returns>
ExitReason reason { get; }
/// <summary>
/// <para>Last resident set size of the memory that the process had used in kB.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getRss()">developer.android.com</seealso>
/// </summary>
/// <returns>long</returns>
long rss { get; }
/// <summary>
/// <para>The exit status argument of exit() if the application calls it, or the signal number if the application is signaled.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getStatus()">developer.android.com</seealso>
/// </summary>
/// <returns>int</returns>
int status { get; }
/// <summary>
/// <para>The timestamp of the process's death, in milliseconds since the epoch, as returned by System.currentTimeMillis(). Value is a non-negative timestamp measured as the number of milliseconds since 1970-01-01T00:00:00Z.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getTimestamp()">developer.android.com</seealso>
/// </summary>
/// <returns>long Value is a non-negative timestamp measured as the number of milliseconds since 1970-01-01T00:00:00Z.</returns>
long timestamp { get; }
/// <summary>
/// <para>Return the traces that was taken by the system prior to the death of the process; typically it'll be available when the reason is REASON_ANR, though if the process gets an ANR but recovers, and dies for another reason later, this trace will be included in the record of ApplicationExitInfo still.</para>
/// <seealso href="https://developer.android.com/reference/android/app/ApplicationExitInfo#getTraceInputStream()">developer.android.com</seealso>
/// </summary>
/// <returns>byte[]</returns>
byte[] trace { get; }
/// <summary>
/// <para>Return the trace data in string format</para>
/// </summary>
/// <returns>string</returns>
public String traceAsString { get; }
}
public static class ApplicationExitInfoProvider
{
/// <summary>
/// <para>Return a list of ApplicationExitInfo records containing the reasons for the most recent app deaths.</para>
/// <seealso href="https://developer.android.com/reference/kotlin/android/app/ActivityManager#gethistoricalprocessexitreasons">developer.android.com</seealso>
/// </summary>
/// <param name="packageName">Optional, a null value means match all packages belonging to the caller's UID. If this package belongs to another UID, you must hold android.Manifest.permission.DUMP in order to retrieve it.</param>
/// <param name="pid">A process ID that used to belong to this package but died later; a value of 0 means to ignore this parameter and return all matching records. Value is 0 or greater</param>
/// <param name="maxNum">The maximum number of results to be returned; a value of 0 means to ignore this parameter and return all matching records Value is 0 or greater.</param>
/// <returns>IApplicationExitInfo[] a list of ApplicationExitInfo records matching the criteria, sorted in the order from most recent to least recent. This value cannot be null.</returns>
public static IApplicationExitInfo[] GetHistoricalProcessExitInfo(string packageName = null, int pid = 0, int maxNum = 0)
{
IApplicationExitInfo[] result = null;
if (result == null)
result = new IApplicationExitInfo[0];
return result;
}
///<summary>
///<para>Set custom state data for this process.It will be included in the record of ApplicationExitInfo on the death of the current calling process; the new process of the app can retrieve this state data by calling processStateSummary on the IApplicationExitInfo record returned by ApplicationExitInfoProvider.getHistoricalProcessExitReasons(String, int, int).</para>
///<seealso href="https://developer.android.com/reference/kotlin/android/app/ActivityManager#setprocessstatesummary">developer.android.com</seealso>
///</summary>
///<param name = "buffer" > The state data.To be advised, DO NOT include sensitive information/data (PII, SPII, or other sensitive user data) here.Maximum length is 128 bytes.</param>
public static void SetProcessStateSummary(SByte[] buffer)
{
}
}
}
| UnityCsReference/Modules/AndroidJNI/AndroidApplicationExitInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/AndroidJNI/AndroidApplicationExitInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 6840
} | 361 |
// Unity 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 System.Collections.Generic;
namespace UnityEngine
{
public interface IAnimationClipSource
{
void GetAnimationClips(List<AnimationClip> results);
}
}
| UnityCsReference/Modules/Animation/Managed/IAnimationClipSource.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/Managed/IAnimationClipSource.cs",
"repo_id": "UnityCsReference",
"token_count": 124
} | 362 |
// Unity 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 UnityObject = UnityEngine.Object;
namespace UnityEngine.Animations
{
[NativeHeader("Modules/Animation/ScriptBindings/AnimationOffsetPlayable.bindings.h")]
[NativeHeader("Modules/Animation/Director/AnimationOffsetPlayable.h")]
[NativeHeader("Runtime/Director/Core/HPlayable.h")]
[StaticAccessor("AnimationOffsetPlayableBindings", StaticAccessorType.DoubleColon)]
[RequiredByNativeCode]
internal struct AnimationOffsetPlayable : IPlayable, IEquatable<AnimationOffsetPlayable>
{
PlayableHandle m_Handle;
static readonly AnimationOffsetPlayable m_NullPlayable = new AnimationOffsetPlayable(PlayableHandle.Null);
public static AnimationOffsetPlayable Null { get { return m_NullPlayable; } }
public static AnimationOffsetPlayable Create(PlayableGraph graph, Vector3 position, Quaternion rotation, int inputCount)
{
var handle = CreateHandle(graph, position, rotation, inputCount);
return new AnimationOffsetPlayable(handle);
}
private static PlayableHandle CreateHandle(PlayableGraph graph, Vector3 position, Quaternion rotation, int inputCount)
{
PlayableHandle handle = PlayableHandle.Null;
if (!CreateHandleInternal(graph, position, rotation, ref handle))
return PlayableHandle.Null;
handle.SetInputCount(inputCount);
return handle;
}
internal AnimationOffsetPlayable(PlayableHandle handle)
{
if (handle.IsValid())
{
if (!handle.IsPlayableOfType<AnimationOffsetPlayable>())
throw new InvalidCastException("Can't set handle: the playable is not an AnimationOffsetPlayable.");
}
m_Handle = handle;
}
public PlayableHandle GetHandle()
{
return m_Handle;
}
public static implicit operator Playable(AnimationOffsetPlayable playable)
{
return new Playable(playable.GetHandle());
}
public static explicit operator AnimationOffsetPlayable(Playable playable)
{
return new AnimationOffsetPlayable(playable.GetHandle());
}
public bool Equals(AnimationOffsetPlayable other)
{
return Equals(other.GetHandle());
}
public Vector3 GetPosition()
{
return GetPositionInternal(ref m_Handle);
}
public void SetPosition(Vector3 value)
{
SetPositionInternal(ref m_Handle, value);
}
public Quaternion GetRotation()
{
return GetRotationInternal(ref m_Handle);
}
public void SetRotation(Quaternion value)
{
SetRotationInternal(ref m_Handle, value);
}
[NativeThrows]
extern private static bool CreateHandleInternal(PlayableGraph graph, Vector3 position, Quaternion rotation, ref PlayableHandle handle);
[NativeThrows]
extern static private Vector3 GetPositionInternal(ref PlayableHandle handle);
[NativeThrows]
extern static private void SetPositionInternal(ref PlayableHandle handle, Vector3 value);
[NativeThrows]
extern static private Quaternion GetRotationInternal(ref PlayableHandle handle);
[NativeThrows]
extern static private void SetRotationInternal(ref PlayableHandle handle, Quaternion value);
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/AnimationOffsetPlayable.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationOffsetPlayable.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1420
} | 363 |
// Unity 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;
namespace UnityEngine
{
public enum BodyDof
{
SpineFrontBack = 0,
SpineLeftRight,
SpineRollLeftRight,
ChestFrontBack,
ChestLeftRight,
ChestRollLeftRight,
UpperChestFrontBack,
UpperChestLeftRight,
UpperChestRollLeftRight,
LastBodyDof
}
public enum HeadDof
{
NeckFrontBack = 0,
NeckLeftRight,
NeckRollLeftRight,
HeadFrontBack,
HeadLeftRight,
HeadRollLeftRight,
LeftEyeDownUp,
LeftEyeInOut,
RightEyeDownUp,
RightEyeInOut,
JawDownUp,
JawLeftRight,
LastHeadDof
}
public enum LegDof
{
UpperLegFrontBack = 0,
UpperLegInOut,
UpperLegRollInOut,
LegCloseOpen,
LegRollInOut,
FootCloseOpen,
FootInOut,
ToesUpDown,
LastLegDof
}
public enum ArmDof
{
ShoulderDownUp = 0,
ShoulderFrontBack,
ArmDownUp,
ArmFrontBack,
ArmRollInOut,
ForeArmCloseOpen,
ForeArmRollInOut,
HandDownUp,
HandInOut,
LastArmDof
}
public enum FingerDof
{
ProximalDownUp = 0,
ProximalInOut,
IntermediateCloseOpen,
DistalCloseOpen,
LastFingerDof
}
public enum HumanPartDof
{
Body = 0,
Head,
LeftLeg,
RightLeg,
LeftArm,
RightArm,
LeftThumb,
LeftIndex,
LeftMiddle,
LeftRing,
LeftLittle,
RightThumb,
RightIndex,
RightMiddle,
RightRing,
RightLittle,
LastHumanPartDof
}
internal enum Dof
{
BodyDofStart = 0,
HeadDofStart = (int)BodyDofStart + (int)BodyDof.LastBodyDof,
LeftLegDofStart = (int)HeadDofStart + (int)HeadDof.LastHeadDof,
RightLegDofStart = (int)LeftLegDofStart + (int)LegDof.LastLegDof,
LeftArmDofStart = (int)RightLegDofStart + (int)LegDof.LastLegDof,
RightArmDofStart = (int)LeftArmDofStart + (int)ArmDof.LastArmDof,
LeftThumbDofStart = (int)RightArmDofStart + (int)ArmDof.LastArmDof,
LeftIndexDofStart = (int)LeftThumbDofStart + (int)FingerDof.LastFingerDof,
LeftMiddleDofStart = (int)LeftIndexDofStart + (int)FingerDof.LastFingerDof,
LeftRingDofStart = (int)LeftMiddleDofStart + (int)FingerDof.LastFingerDof,
LeftLittleDofStart = (int)LeftRingDofStart + (int)FingerDof.LastFingerDof,
RightThumbDofStart = (int)LeftLittleDofStart + (int)FingerDof.LastFingerDof,
RightIndexDofStart = (int)RightThumbDofStart + (int)FingerDof.LastFingerDof,
RightMiddleDofStart = (int)RightIndexDofStart + (int)FingerDof.LastFingerDof,
RightRingDofStart = (int)RightMiddleDofStart + (int)FingerDof.LastFingerDof,
RightLittleDofStart = (int)RightRingDofStart + (int)FingerDof.LastFingerDof,
LastDof = (int)RightLittleDofStart + (int)FingerDof.LastFingerDof
}
// Human Body Bones
public enum HumanBodyBones
{
// This is the Hips bone
Hips = 0,
// This is the Left Upper Leg bone
LeftUpperLeg = 1,
// This is the Right Upper Leg bone
RightUpperLeg = 2,
// This is the Left Knee bone
LeftLowerLeg = 3,
// This is the Right Knee bone
RightLowerLeg = 4,
// This is the Left Ankle bone
LeftFoot = 5,
// This is the Right Ankle bone
RightFoot = 6,
// This is the first Spine bone
Spine = 7,
// This is the Chest bone
Chest = 8,
// This is the UpperChest bone
UpperChest = 54,
// This is the Neck bone
Neck = 9,
// This is the Head bone
Head = 10,
// This is the Left Shoulder bone
LeftShoulder = 11,
// This is the Right Shoulder bone
RightShoulder = 12,
// This is the Left Upper Arm bone
LeftUpperArm = 13,
// This is the Right Upper Arm bone
RightUpperArm = 14,
// This is the Left Elbow bone
LeftLowerArm = 15,
// This is the Right Elbow bone
RightLowerArm = 16,
// This is the Left Wrist bone
LeftHand = 17,
// This is the Right Wrist bone
RightHand = 18,
// This is the Left Toes bone
LeftToes = 19,
// This is the Right Toes bone
RightToes = 20,
// This is the Left Eye bone
LeftEye = 21,
// This is the Right Eye bone
RightEye = 22,
// This is the Jaw bone
Jaw = 23,
LeftThumbProximal = 24,
LeftThumbIntermediate = 25,
LeftThumbDistal = 26,
LeftIndexProximal = 27,
LeftIndexIntermediate = 28,
LeftIndexDistal = 29,
LeftMiddleProximal = 30,
LeftMiddleIntermediate = 31,
LeftMiddleDistal = 32,
LeftRingProximal = 33,
LeftRingIntermediate = 34,
LeftRingDistal = 35,
LeftLittleProximal = 36,
LeftLittleIntermediate = 37,
LeftLittleDistal = 38,
RightThumbProximal = 39,
RightThumbIntermediate = 40,
RightThumbDistal = 41,
RightIndexProximal = 42,
RightIndexIntermediate = 43,
RightIndexDistal = 44,
RightMiddleProximal = 45,
RightMiddleIntermediate = 46,
RightMiddleDistal = 47,
RightRingProximal = 48,
RightRingIntermediate = 49,
RightRingDistal = 50,
RightLittleProximal = 51,
RightLittleIntermediate = 52,
RightLittleDistal = 53,
// UpperChest = 54
// This is the Last bone index delimiter
LastBone = 55
}
internal enum HumanParameter
{
UpperArmTwist = 0,
LowerArmTwist,
UpperLegTwist,
LowerLegTwist,
ArmStretch,
LegStretch,
FeetSpacing
}
[NativeHeader("Modules/Animation/Avatar.h")]
[UsedByNativeCode]
public class Avatar : Object
{
private Avatar()
{
}
// Return true if this avatar is a valid mecanim avatar. It can be a generic avatar or a human avatar.
extern public bool isValid
{
[NativeMethod("IsValid")]
get;
}
// Return true if this avatar is a valid human avatar.
extern public bool isHuman
{
[NativeMethod("IsHuman")]
get;
}
extern public HumanDescription humanDescription
{
get;
}
extern internal void SetMuscleMinMax(int muscleId, float min, float max);
extern internal void SetParameter(int parameterId, float value);
internal float GetAxisLength(int humanId)
{
return Internal_GetAxisLength(HumanTrait.GetBoneIndexFromMono(humanId));
}
internal Quaternion GetPreRotation(int humanId)
{
return Internal_GetPreRotation(HumanTrait.GetBoneIndexFromMono(humanId));
}
internal Quaternion GetPostRotation(int humanId)
{
return Internal_GetPostRotation(HumanTrait.GetBoneIndexFromMono(humanId));
}
internal Quaternion GetZYPostQ(int humanId, Quaternion parentQ, Quaternion q)
{
return Internal_GetZYPostQ(HumanTrait.GetBoneIndexFromMono(humanId), parentQ, q);
}
internal Quaternion GetZYRoll(int humanId, Vector3 uvw)
{
return Internal_GetZYRoll(HumanTrait.GetBoneIndexFromMono(humanId), uvw);
}
internal Vector3 GetLimitSign(int humanId)
{
return Internal_GetLimitSign(HumanTrait.GetBoneIndexFromMono(humanId));
}
[NativeMethod("GetAxisLength")]
extern internal float Internal_GetAxisLength(int humanId);
[NativeMethod("GetPreRotation")]
extern internal Quaternion Internal_GetPreRotation(int humanId);
[NativeMethod("GetPostRotation")]
extern internal Quaternion Internal_GetPostRotation(int humanId);
[NativeMethod("GetZYPostQ")]
extern internal Quaternion Internal_GetZYPostQ(int humanId, Quaternion parentQ, Quaternion q);
[NativeMethod("GetZYRoll")]
extern internal Quaternion Internal_GetZYRoll(int humanId, Vector3 uvw);
[NativeMethod("GetLimitSign")]
extern internal Vector3 Internal_GetLimitSign(int humanId);
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/Avatar.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/Avatar.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 4085
} | 364 |
// Unity 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.Runtime.InteropServices;
using System.Text;
using UnityEngine.Bindings;
using UnityEngine.Rendering;
using UnityEngine.Scripting;
using UnityEngineInternal;
namespace UnityEngine
{
// Asynchronous create request for an [[AssetBundle]].
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
[NativeHeader("Modules/AssetBundle/Public/AssetBundleLoadFromAsyncOperation.h")]
public class AssetBundleCreateRequest : AsyncOperation
{
public extern UnityEngine.AssetBundle assetBundle
{
[NativeMethod("GetAssetBundleBlocking")]
get;
}
[NativeMethod("SetEnableCompatibilityChecks")]
private extern void SetEnableCompatibilityChecks(bool set);
internal void DisableCompatibilityChecks()
{
SetEnableCompatibilityChecks(false);
}
public AssetBundleCreateRequest() { }
private AssetBundleCreateRequest(IntPtr ptr) : base(ptr)
{ }
new internal static class BindingsMarshaller
{
public static AssetBundleCreateRequest ConvertToManaged(IntPtr ptr) => new AssetBundleCreateRequest(ptr);
public static IntPtr ConvertToNative(AssetBundleCreateRequest assetBundleCreateRequest) => assetBundleCreateRequest.m_Ptr;
}
}
}
| UnityCsReference/Modules/AssetBundle/Managed/AssetBundleCreateRequest.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetBundle/Managed/AssetBundleCreateRequest.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 555
} | 365 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor
{
[System.AttributeUsage(System.AttributeTargets.Field)]
public class AssetPostprocessorStaticVariableIgnoreAttribute : System.Attribute { }
}
| UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/AssetPostprocessorStaticVariableIgnoreAttribute.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/AssetPostprocessorStaticVariableIgnoreAttribute.cs",
"repo_id": "UnityCsReference",
"token_count": 93
} | 366 |
// Unity 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.IO;
using Object = UnityEngine.Object;
using UnityEditor.AssetImporters;
using System.Linq;
namespace UnityEditor
{
internal class ModelImporterRigEditor : BaseAssetImporterTabUI
{
ModelImporter singleImporter { get { return targets[0] as ModelImporter; } }
public int m_SelectedClipIndex = -1;
Avatar m_Avatar;
#pragma warning disable 0649
[CacheProperty]
SerializedProperty m_AnimationType;
[CacheProperty]
SerializedProperty m_AvatarSetup;
[CacheProperty("m_LastHumanDescriptionAvatarSource")]
SerializedProperty m_AvatarSource;
[CacheProperty]
SerializedProperty m_LegacyGenerateAnimations;
[CacheProperty]
SerializedProperty m_AnimationCompression;
[CacheProperty("skinWeightsMode")]
SerializedProperty m_SkinWeightsMode;
[CacheProperty("maxBonesPerVertex")]
SerializedProperty m_MaxBonesPerVertex;
[CacheProperty("minBoneWeight")]
SerializedProperty m_MinBoneWeight;
[CacheProperty("optimizeBones")]
SerializedProperty m_OptimizeBones;
[CacheProperty]
SerializedProperty m_OptimizeGameObjects;
[CacheProperty("m_HumanDescription.m_RootMotionBoneName")]
SerializedProperty m_RootMotionBoneName;
[CacheProperty("m_HasExtraRoot")]
SerializedProperty m_SrcHasExtraRoot;
[CacheProperty("m_HumanDescription.m_HasExtraRoot")]
SerializedProperty m_DstHasExtraRoot;
[CacheProperty("m_HumanDescription.m_Human")]
SerializedProperty m_HumanBoneArray;
[CacheProperty("m_HumanDescription.m_Skeleton")]
SerializedProperty m_Skeleton;
[CacheProperty]
SerializedProperty m_AutoGenerateAvatarMappingIfUnspecified;
#pragma warning restore 0649
private static bool importMessageFoldout = false;
GUIContent[] m_RootMotionBoneList;
private ExposeTransformEditor m_ExposeTransformEditor;
private SerializedObject m_AvatarSourceSerializedObject;
string[] m_ReferencedClips;
SerializedObject avatarSourceSerializedObject
{
get
{
// to keep the serialized object in sync with the current source avatar
Object currentAvatar = m_AvatarSource?.objectReferenceValue;
if (currentAvatar == null || currentAvatar != m_AvatarSourceSerializedObject?.targetObject)
{
m_AvatarSourceSerializedObject?.Dispose();
m_AvatarSourceSerializedObject = null;
if (currentAvatar != null)
m_AvatarSourceSerializedObject = new SerializedObject(currentAvatar);
}
m_AvatarSourceSerializedObject?.Update();
return m_AvatarSourceSerializedObject;
}
}
private ModelImporterAnimationType animationType
{
get { return (ModelImporterAnimationType)m_AnimationType.intValue; }
set { m_AnimationType.intValue = (int)value; }
}
private bool m_CanMultiEditTransformList;
private const string k_RigErrorPrefix = "Rig Error: ";
bool m_IsBiped = false;
List<string> m_BipedMappingReport = null;
bool m_ExtraExposedTransformFoldout = false;
static class Styles
{
public static GUIContent AnimationType = EditorGUIUtility.TrTextContent("Animation Type", "The type of animation to support / import.");
public static GUIContent[] AnimationTypeOpt =
{
EditorGUIUtility.TrTextContent("None", "No animation present."),
EditorGUIUtility.TrTextContent("Legacy", "Legacy animation system."),
EditorGUIUtility.TrTextContent("Generic", "Generic Mecanim animation."),
EditorGUIUtility.TrTextContent("Humanoid", "Humanoid Mecanim animation system.")
};
public static GUIContent SaveAvatar = EditorGUIUtility.TrTextContent("Save Avatar", "Saves the generated Avatar as a sub-asset.");
public static GUIContent AnimLabel = EditorGUIUtility.TrTextContent("Generation", "Controls how animations are imported.");
public static GUIContent[] AnimationsOpt =
{
EditorGUIUtility.TrTextContent("Don't Import", "No animation or skinning is imported."),
EditorGUIUtility.TrTextContent("Store in Original Roots (Deprecated)", "Animations are stored in the root objects of your animation package (these might be different from the root objects in Unity)."),
EditorGUIUtility.TrTextContent("Store in Nodes (Deprecated)", "Animations are stored together with the objects they animate. Use this when you have a complex animation setup and want full scripting control."),
EditorGUIUtility.TrTextContent("Store in Root (Deprecated)", "Animations are stored in the scene's transform root objects. Use this when animating anything that has a hierarchy."),
EditorGUIUtility.TrTextContent("Store in Root (New)")
};
public static GUIContent avatar = EditorGUIUtility.TrTextContent("Animator");
public static GUIContent configureAvatar = EditorGUIUtility.TrTextContent("Configure...");
public static GUIContent avatarValid = EditorGUIUtility.TrTextContent("\u2713");
public static GUIContent avatarInvalid = EditorGUIUtility.TrTextContent("\u2715");
public static GUIContent avatarPending = EditorGUIUtility.TrTextContent("...");
public static GUIContent UpdateMuscleDefinitionFromSource = EditorGUIUtility.TrTextContent("Update", "Update the copy of the muscle definition from the source.");
public static GUIContent RootNode = EditorGUIUtility.TrTextContent("Root node", "Specify the root node used to extract the animation translation.");
public static GUIContent AvatarDefinition = EditorGUIUtility.TrTextContent("Avatar Definition", "Choose between Create From This Model or Copy From Other Avatar. The first one creates an Avatar for this file and the second one uses an Avatar from another file to import animation.");
public static GUIContent SkinWeightsMode = EditorGUIUtility.TrTextContent("Skin Weights", "Control how many bone weights are imported.");
public static GUIContent[] SkinWeightsModeOpt =
{
EditorGUIUtility.TrTextContent("Standard (4 Bones)", "Import a maximum of 4 bones per vertex."),
EditorGUIUtility.TrTextContent("Custom", "Import a custom number of bones per vertex.")
};
public static GUIContent MaxBonesPerVertex = EditorGUIUtility.TrTextContent("Max Bones/Vertex", "Number of bones that can affect each vertex.");
public static GUIContent MinBoneWeight = EditorGUIUtility.TrTextContent("Min Bone Weight", "Bone weights smaller than this value are rejected. The remaining weights are scaled to add up to 1.0.");
public static GUIContent OptimizeBones = EditorGUIUtility.TrTextContent("Strip Bones", "Only adds bones to SkinnedMeshRenderers that have skin weights assigned to them.");
public static GUIContent UpdateReferenceClips = EditorGUIUtility.TrTextContent("Update referenced clips", "Click on this button to update all the referenced clips matching this model. This will set all these clips to Copy From Other Avatar, set the source Avatar to this one and reimport all these files. See the documentation for EditorSettings.referenceClipsExactNaming for more details about how models are matched to referenced clips.");
public static GUIContent ImportMessages = EditorGUIUtility.TrTextContent("Import Messages");
public static GUIContent ExtraExposedTransform = EditorGUIUtility.TrTextContent("Extra Transforms to Expose", "Select the list of transforms to expose in the optimized GameObject hierarchy.");
}
public ModelImporterRigEditor(AssetImporterEditor panelContainer)
: base(panelContainer)
{}
internal override void OnEnable()
{
Editor.AssignCachedProperties(this, serializedObject.GetIterator());
m_ExposeTransformEditor = new ExposeTransformEditor();
string[] transformPaths = singleImporter.transformPaths;
m_RootMotionBoneList = new GUIContent[transformPaths.Length];
for (int i = 0; i < transformPaths.Length; i++)
m_RootMotionBoneList[i] = new GUIContent(transformPaths[i]);
if (m_RootMotionBoneList.Length > 0)
m_RootMotionBoneList[0] = EditorGUIUtility.TrTextContent("None");
m_ExposeTransformEditor.OnEnable(singleImporter.transformPaths, serializedObject);
m_CanMultiEditTransformList = CanMultiEditTransformList();
m_IsBiped = false;
m_BipedMappingReport = new List<string>();
UpdateBipedMappingReport();
if (m_AnimationType.intValue == (int)ModelImporterAnimationType.Human)
{
if (m_Avatar == null)
{
ResetAvatar();
}
UpdateReferencedClips();
ReferencedClipsPostProcessor.ReferencedClipsChanged += ReferencedClipsChanged;
}
}
void ReferencedClipsChanged(List<string> referencedClips)
{
if (referencedClips.Count == 0)
return;
// If any of the passed referenced clip is located in the same folder as this model,
// then refresh our list of referenced clips
var modelImporter = target as ModelImporter;
if (modelImporter)
{
var modelDirectory = Path.GetDirectoryName(modelImporter.assetPath);
foreach (var referencedClip in referencedClips)
{
if (modelDirectory == Path.GetDirectoryName(referencedClip))
{
UpdateReferencedClips();
return;
}
}
}
}
internal override void OnDisable()
{
ReferencedClipsPostProcessor.ReferencedClipsChanged -= ReferencedClipsChanged;
if (m_AvatarSourceSerializedObject != null)
m_AvatarSourceSerializedObject.Dispose();
}
private void UpdateBipedMappingReport()
{
if (m_AnimationType.intValue == (int)ModelImporterAnimationType.Human)
{
GameObject go = assetTarget as GameObject;
if (go != null)
{
m_IsBiped = AvatarBipedMapper.IsBiped(go.transform, m_BipedMappingReport);
}
}
}
private bool CanMultiEditTransformList()
{
string[] transformPaths = singleImporter.transformPaths;
for (int i = 1; i < targets.Length; ++i)
{
ModelImporter modelImporter = targets[i] as ModelImporter;
if (!ArrayUtility.ArrayEquals(transformPaths, modelImporter.transformPaths))
return false;
}
return true;
}
bool AvatarCopyIsUpToDate()
{
if (!(animationType == ModelImporterAnimationType.Human || animationType == ModelImporterAnimationType.Generic) || m_AvatarSource.objectReferenceValue == null)
return true;
SerializedProperty humanDescription = serializedObject.FindProperty("m_HumanDescription");
//Because of the constraint that Editors must share an Animation Source, if we have a mix of different human descriptions, then *at least* one is out of date
if (humanDescription.hasMultipleDifferentValues)
return false;
//Does the HumanDescription in the Importer match the one in the referenced Avatar?
return SerializedProperty.DataEquals(humanDescription, avatarSourceSerializedObject.FindProperty("m_HumanDescription"));
}
internal override void OnDestroy()
{
m_Avatar = null;
}
internal override void ResetValues()
{
base.ResetValues();
ResetAvatar();
m_ExposeTransformEditor.ResetExposedTransformList();
}
internal override void PostApply()
{
base.PostApply();
//The import process may generate a new avatar, find it.
ResetAvatar();
}
void ResetAvatar()
{
if (assetTarget != null)
{
var path = singleImporter.assetPath;
m_Avatar = AssetDatabase.LoadAssetAtPath<Avatar>(path);
}
}
void LegacyGUI()
{
EditorGUILayout.Popup(m_LegacyGenerateAnimations, Styles.AnimationsOpt, Styles.AnimLabel);
// Show warning and fix button for deprecated import formats
if (m_LegacyGenerateAnimations.intValue == 1 || m_LegacyGenerateAnimations.intValue == 2 || m_LegacyGenerateAnimations.intValue == 3)
EditorGUILayout.HelpBox("The animation import setting \"" + Styles.AnimationsOpt[m_LegacyGenerateAnimations.intValue].text + "\" is deprecated.", MessageType.Warning);
}
void GenericGUI()
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyField = new EditorGUI.PropertyScope(horizontal.rect, Styles.AvatarDefinition, m_AvatarSetup))
{
EditorGUI.showMixedValue = m_AvatarSetup.hasMultipleDifferentValues;
using (var change = new EditorGUI.ChangeCheckScope())
{
var value = (ModelImporterAvatarSetup)EditorGUILayout.EnumPopup(propertyField.content, (ModelImporterAvatarSetup)m_AvatarSetup.intValue);
if (change.changed)
m_AvatarSetup.intValue = (int)value;
}
EditorGUI.showMixedValue = false;
}
}
if (!m_AvatarSetup.hasMultipleDifferentValues)
{
if (m_AvatarSetup.intValue == (int)ModelImporterAvatarSetup.CreateFromThisModel)
{
// Do not allow multi edit of root node if all rigs doesn't match
using (new EditorGUI.DisabledScope(!m_CanMultiEditTransformList))
{
if (assetTarget == null)
{
m_RootMotionBoneName.stringValue =
EditorGUILayout.TextField(Styles.RootNode, m_RootMotionBoneName.stringValue);
}
else
{
EditorGUI.BeginChangeCheck();
var currentIndex = ArrayUtility.FindIndex(m_RootMotionBoneList, content => FileUtil.GetLastPathNameComponent(content.text) == m_RootMotionBoneName.stringValue);
currentIndex = currentIndex < 1 ? 0 : currentIndex;
currentIndex = EditorGUILayout.Popup(Styles.RootNode, currentIndex, m_RootMotionBoneList);
if (EditorGUI.EndChangeCheck())
{
if (currentIndex > 0 && currentIndex < m_RootMotionBoneList.Length)
{
m_RootMotionBoneName.stringValue =
FileUtil.GetLastPathNameComponent(m_RootMotionBoneList[currentIndex].text);
}
else
{
m_RootMotionBoneName.stringValue = "";
}
}
}
}
}
else if (m_AvatarSetup.intValue == (int)ModelImporterAvatarSetup.CopyFromOther)
CopyAvatarGUI();
}
}
void HumanoidGUI()
{
using (var horizontal = new EditorGUILayout.HorizontalScope())
{
using (var propertyField = new EditorGUI.PropertyScope(horizontal.rect, Styles.AvatarDefinition, m_AvatarSetup))
{
EditorGUI.showMixedValue = m_AvatarSetup.hasMultipleDifferentValues;
using (var change = new EditorGUI.ChangeCheckScope())
{
Rect r = EditorGUILayout.GetControlRect(true, EditorGUI.kSingleLineHeight, EditorStyles.popup);
var value = (ModelImporterAvatarSetup)EditorGUI.EnumPopup(r, propertyField.content, (ModelImporterAvatarSetup)m_AvatarSetup.intValue, e => (ModelImporterAvatarSetup)e != ModelImporterAvatarSetup.NoAvatar);
if (change.changed)
{
m_AvatarSetup.intValue = (int)value;
//Case 1213138 - When changing avatar setup value, we must reset the human, skeleton & auto-mapping to their default values.
//NB: This fix will be defunct once we have a reference-based solution for copying avatars.
AvatarSetupTool.ClearAll(m_HumanBoneArray, m_Skeleton);
m_AutoGenerateAvatarMappingIfUnspecified.boolValue = true;
}
}
EditorGUI.showMixedValue = false;
}
}
if (!m_AvatarSetup.hasMultipleDifferentValues)
{
if (m_AvatarSetup.intValue == (int)ModelImporterAvatarSetup.CreateFromThisModel)
ConfigureAvatarGUI();
else
CopyAvatarGUI();
}
if (m_IsBiped)
{
if (m_BipedMappingReport.Count > 0)
{
string report = "A Biped was detected, but cannot be configured properly because of an unsupported hierarchy. Adjust Biped settings in 3DS Max before exporting to correct this problem.\n";
for (int reportIter = 0; reportIter < m_BipedMappingReport.Count; reportIter++)
{
report += m_BipedMappingReport[reportIter];
}
EditorGUILayout.HelpBox(report, MessageType.Warning);
}
else
{
EditorGUILayout.HelpBox("A Biped was detected. Default Biped mapping and T-Pose have been configured for this avatar. Translation DoFs have been activated. Use Configure to modify default Biped setup.", MessageType.Info);
}
}
EditorGUILayout.Space();
}
void ConfigureAvatarGUI()
{
if (targets.Length > 1)
{
GUILayout.Label("Can't configure avatar in multi-editing mode", EditorStyles.helpBox);
return;
}
if (singleImporter.transformPaths.Length <= HumanTrait.RequiredBoneCount)
{
GUILayout.Label(string.Format("Not enough bones to create human avatar (requires {0})", HumanTrait.RequiredBoneCount), EditorStyles.helpBox);
}
// Validation text
GUIContent validationContent;
if (m_Avatar && !HasModified())
{
if (m_Avatar.isHuman)
validationContent = Styles.avatarValid;
else
validationContent = Styles.avatarInvalid;
}
else
{
validationContent = Styles.avatarPending;
GUILayout.Label("The avatar can be configured after settings have been applied.", EditorStyles.helpBox);
}
Rect r = EditorGUILayout.GetControlRect();
const int buttonWidth = 80;
GUI.Label(new Rect(r.xMax - buttonWidth - 18, r.y, 18, r.height), validationContent, EditorStyles.label);
// Configure button
using (new EditorGUI.DisabledScope(m_Avatar == null))
{
if (GUI.Button(new Rect(r.xMax - buttonWidth, r.y + 1, buttonWidth, r.height - 1), Styles.configureAvatar, EditorStyles.miniButton))
{
if (!isLocked)
{
Selection.activeObject = m_Avatar;
AvatarEditor.s_EditImmediatelyOnNextOpen = true;
GUIUtility.ExitGUI();
}
else
Debug.Log("Cannot configure avatar, inspector is locked");
}
}
}
bool IsAvatarValid(Avatar newAvatar)
{
if (newAvatar != null)
{
if (newAvatar.isHuman && (animationType != ModelImporterAnimationType.Human))
{
if (EditorUtility.DisplayDialog("Assigning a Humanoid Avatar on a Generic Rig",
"Do you want to change Animation Type to Humanoid ?", "Yes", "No"))
{
animationType = ModelImporterAnimationType.Human;
return true;
}
else
{
//New Avatar is invalid
return false;
}
}
else if (!newAvatar.isHuman && (animationType != ModelImporterAnimationType.Generic))
{
if (EditorUtility.DisplayDialog("Assigning a Generic Avatar on a Humanoid Rig",
"Do you want to change Animation Type to Generic ?", "Yes", "No"))
{
animationType = ModelImporterAnimationType.Generic;
return true;
}
else
{
//New Avatar is invalid
return false;
}
}
}
return true;
}
void CopyAvatarGUI()
{
GUILayout.Label(
@"If you have already created an Avatar for another model with a rig identical to this one, you can copy its Avatar definition.
With this option, this model will not create any avatar but only import animations.", EditorStyles.helpBox);
EditorGUILayout.BeginHorizontal();
Avatar previousAvatar = (Avatar)m_AvatarSource.objectReferenceValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.ObjectField(m_AvatarSource, typeof(Avatar), GUIContent.Temp("Source"), ValidateAvatarSource);
var sourceAvatar = m_AvatarSource.objectReferenceValue as Avatar;
if (EditorGUI.EndChangeCheck())
{
if (IsAvatarValid(sourceAvatar))
{
AvatarSetupTool.ClearAll(m_HumanBoneArray, m_Skeleton);
if (sourceAvatar != null)
CopyHumanDescriptionFromOtherModel(sourceAvatar);
}
else
//Avatar is invalid so revert to the previous Avatar
m_AvatarSource.objectReferenceValue = previousAvatar;
}
if (sourceAvatar != null && !m_AvatarSource.hasMultipleDifferentValues && !AvatarCopyIsUpToDate())
{
if (GUILayout.Button(Styles.UpdateMuscleDefinitionFromSource, EditorStyles.miniButton))
{
if (IsAvatarValid(sourceAvatar))
{
AvatarSetupTool.ClearAll(m_HumanBoneArray, m_Skeleton);
CopyHumanDescriptionFromOtherModel(sourceAvatar);
}
}
}
EditorGUILayout.EndHorizontal();
}
Object ValidateAvatarSource(Object[] references, Type objType, SerializedProperty property, EditorGUI.ObjectFieldValidatorOptions options)
{
if (references.Length == 0)
return null;
string avatarPath = AssetDatabase.GetAssetPath(references[0]);
foreach (AssetImporter importer in targets)
{
if (avatarPath == importer.assetPath)
{
return null;
}
}
return references[0];
}
// We only populate the model's referenced clips for models using the Legacy animation type.
// Models using the Human animation type still need to be able to fetch their matching referenced clips
// and the editor needs to react when referenced clips are imported. This is done through this asset
// post-processor
class ReferencedClipsPostProcessor : AssetPostprocessor
{
public static event Action<List<string>> ReferencedClipsChanged;
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths, bool didDomainReload)
{
if (ReferencedClipsChanged == null)
return;
List<string> referencedClips = new();
foreach (var asset in importedAssets)
if (asset.Contains('@'))
referencedClips.Add(asset);
foreach (var asset in deletedAssets)
if (asset.Contains('@'))
referencedClips.Add(asset);
foreach (var asset in movedAssets)
if (asset.Contains('@'))
referencedClips.Add(asset);
foreach (var asset in movedFromAssetPaths)
if (asset.Contains('@'))
referencedClips.Add(asset);
ReferencedClipsChanged(referencedClips);
}
}
void UpdateReferencedClips()
{
ModelImporter importer = target as ModelImporter;
if (importer != null)
m_ReferencedClips = ModelImporter.GetReferencedClipsForModelPath(importer.assetPath);
}
void ShowUpdateReferenceClip()
{
if (targets.Length > 1
|| m_AvatarSetup.intValue == (int)ModelImporterAvatarSetup.CopyFromOther
|| !m_Avatar
|| !m_Avatar.isValid
|| animationType != ModelImporterAnimationType.Human
)
{
return;
}
string[] paths = new string[m_ReferencedClips.Length];
for (var i = 0; i < m_ReferencedClips.Length; i++)
paths[i] = AssetDatabase.GUIDToAssetPath(m_ReferencedClips[i]);
// Show only button if some clip reference this avatar.
if (paths.Length > 0 && GUILayout.Button(Styles.UpdateReferenceClips, GUILayout.Width(150)))
{
foreach (string path in paths)
SetupReferencedClip(path);
try
{
AssetDatabase.StartAssetEditing();
foreach (string path in paths)
AssetDatabase.ImportAsset(path);
}
finally
{
AssetDatabase.StopAssetEditing();
}
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
ImportLog importLog = AssetImporter.GetImportLog(singleImporter.assetPath);
ImportLog.ImportLogEntry[] importRigErrors = importLog ? importLog.logEntries.Where(x => x.flags == ImportLogFlags.Error && x.message.StartsWith(k_RigErrorPrefix)).ToArray() : new ImportLog.ImportLogEntry[0];
ImportLog.ImportLogEntry[] importRigWarnings = importLog ? importLog.logEntries.Where(x => x.flags == ImportLogFlags.Warning && x.message.StartsWith(k_RigErrorPrefix)).ToArray() : new ImportLog.ImportLogEntry[0];
if (importRigErrors.Length > 0)
{
EditorGUILayout.Space();
EditorGUILayout.HelpBox("Error(s) found while importing rig in this animation file. Open \"Import Messages\" foldout below for more details", MessageType.Error);
}
else if (importRigWarnings.Length > 0)
{
EditorGUILayout.Space();
EditorGUILayout.HelpBox("Warning(s) found while importing rig in this animation file. Open \"Import Messages\" foldout below for more details", MessageType.Warning);
}
// Animation type
EditorGUI.BeginChangeCheck();
EditorGUILayout.Popup(m_AnimationType, Styles.AnimationTypeOpt, Styles.AnimationType);
if (EditorGUI.EndChangeCheck())
{
m_AvatarSource.objectReferenceValue = null;
if (m_AvatarSourceSerializedObject != null)
m_AvatarSourceSerializedObject.Dispose();
m_AvatarSourceSerializedObject = null;
if (animationType == ModelImporterAnimationType.Legacy)
m_AnimationCompression.intValue = (int)ModelImporterAnimationCompression.KeyframeReduction;
else if (animationType == ModelImporterAnimationType.Generic || animationType == ModelImporterAnimationType.Human)
m_AnimationCompression.intValue = (int)ModelImporterAnimationCompression.Optimal;
m_DstHasExtraRoot.boolValue = m_SrcHasExtraRoot.boolValue;
}
EditorGUILayout.Space();
if (!m_AnimationType.hasMultipleDifferentValues)
{
// Show GUI depending on animation type
if (animationType == ModelImporterAnimationType.Human)
HumanoidGUI();
else if (animationType == ModelImporterAnimationType.Generic)
GenericGUI();
else if (animationType == ModelImporterAnimationType.Legacy)
LegacyGUI();
}
if (animationType != ModelImporterAnimationType.None || m_AnimationType.hasMultipleDifferentValues)
{
EditorGUILayout.Popup(m_SkinWeightsMode, Styles.SkinWeightsModeOpt, Styles.SkinWeightsMode);
if (m_SkinWeightsMode.intValue == (int)ModelImporterSkinWeights.Custom)
{
EditorGUILayout.IntSlider(m_MaxBonesPerVertex, 1, 255, Styles.MaxBonesPerVertex);
EditorGUILayout.Slider(m_MinBoneWeight, 0.001f, 0.5f, Styles.MinBoneWeight);
}
int currentSkinWeights = m_SkinWeightsMode.intValue == (int)ModelImporterSkinWeights.Standard ? 4 : m_MaxBonesPerVertex.intValue;
if ((int)QualitySettings.skinWeights < currentSkinWeights)
{
var msg =
$"Skin Weights is set to {(int)QualitySettings.skinWeights} bones per vertex in Quality Settings. Some bone influences may not be rendered.";
EditorGUILayout.HelpBox(msg, MessageType.Info);
}
}
if (animationType != ModelImporterAnimationType.None)
{
EditorGUILayout.PropertyField(m_OptimizeBones, Styles.OptimizeBones);
ShowUpdateReferenceClip();
}
// OptimizeGameObject is only supported on our own avatar when animation type is not Legacy.
if (m_AvatarSetup.intValue == (int)ModelImporterAvatarSetup.CreateFromThisModel && animationType != ModelImporterAnimationType.Legacy)
{
EditorGUILayout.PropertyField(m_OptimizeGameObjects);
if (m_OptimizeGameObjects.boolValue &&
serializedObject.targetObjectsCount == 1) // SerializedProperty can't handle multiple string arrays properly.
{
bool wasChanged = GUI.changed;
m_ExtraExposedTransformFoldout = EditorGUILayout.Foldout(m_ExtraExposedTransformFoldout, Styles.ExtraExposedTransform, true);
GUI.changed = wasChanged;
if (m_ExtraExposedTransformFoldout)
{
// Do not allow multi edit of exposed transform list if all rigs doesn't match
using (new EditorGUI.DisabledScope(!m_CanMultiEditTransformList))
using (new EditorGUI.IndentLevelScope())
m_ExposeTransformEditor.OnGUI();
}
}
}
if (importRigErrors.Length > 0 || importRigWarnings.Length > 0)
{
EditorGUILayout.Space();
importMessageFoldout = EditorGUILayout.Foldout(importMessageFoldout, Styles.ImportMessages, true);
if (importMessageFoldout)
{
foreach (var importRigError in importRigErrors)
EditorGUILayout.HelpBox(importRigError.message, MessageType.Error);
foreach (var importRigWarning in importRigWarnings)
EditorGUILayout.HelpBox(importRigWarning.message, MessageType.Warning);
}
}
}
static SerializedObject GetModelImporterSerializedObject(string assetPath)
{
ModelImporter importer = AssetImporter.GetAtPath(assetPath) as ModelImporter;
if (importer == null)
return null;
return new SerializedObject(importer);
}
static void CopyHumanDescriptionToDestination(SerializedObject sourceObject, SerializedObject targetObject)
{
targetObject.CopyFromSerializedProperty(sourceObject.FindProperty("m_HumanDescription"));
}
private void CopyHumanDescriptionFromOtherModel(Avatar sourceAvatar)
{
//This could be an Avatar sub-asset, or a distinct avatar asset
using (SerializedObject avatarSerializedObject = new SerializedObject(sourceAvatar))
{
CopyHumanDescriptionToDestination(avatarSerializedObject, serializedObject);
}
}
private void SetupReferencedClip(string otherModelImporterPath)
{
SerializedObject targetImporter = GetModelImporterSerializedObject(otherModelImporterPath);
// We may receive a path that doesn't have a importer.
if (targetImporter != null)
{
targetImporter.CopyFromSerializedProperty(serializedObject.FindProperty("m_AnimationType"));
SerializedProperty copyAvatar = targetImporter.FindProperty("m_CopyAvatar");
if (copyAvatar != null)
copyAvatar.boolValue = true;
SerializedProperty avatar = targetImporter.FindProperty("m_LastHumanDescriptionAvatarSource");
if (avatar != null)
avatar.objectReferenceValue = m_Avatar;
CopyHumanDescriptionToDestination(serializedObject, targetImporter);
targetImporter.ApplyModifiedProperties();
targetImporter.Dispose();
}
}
public bool isLocked
{
get
{
foreach (InspectorWindow i in InspectorWindow.GetAllInspectorWindows())
{
ActiveEditorTracker activeEditor = i.tracker;
foreach (Editor e in activeEditor.activeEditors)
{
// the tab is no longer an editor, so we must always refer to the panel container
if (e is ModelImporterEditor && ((ModelImporterEditor)e).activeTab == this)
{
return i.isLocked;
}
}
}
return false;
}
}
}
}
| UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterRigEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterRigEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 17157
} | 367 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.AssetImporters;
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeHeader("Modules/AssetPipelineEditor/Public/TextScriptImporter.h")]
internal class TextScriptImporter : AssetImporter
{
}
[CustomEditor(typeof(TextScriptImporter))]
internal class TextScriptImporterEditor : AssetImporterEditor
{
protected override bool needsApplyRevert => false;
public override void OnInspectorGUI()
{
}
}
}
| UnityCsReference/Modules/AssetPipelineEditor/Public/TextScriptImporter.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/TextScriptImporter.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 221
} | 368 |
// Unity 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.Audio;
using UnityEngine.Bindings;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEngine
{
[NativeType(Header = "Modules/Audio/Public/ScriptBindings/AudioRenderer.bindings.h")]
public class AudioRenderer
{
public static bool Start()
{
return Internal_AudioRenderer_Start();
}
public static bool Stop()
{
return Internal_AudioRenderer_Stop();
}
public static int GetSampleCountForCaptureFrame()
{
return Internal_AudioRenderer_GetSampleCountForCaptureFrame();
}
// We should consider making this delegate-based in order to provide information like channel count and format. Also the term "sink" is quite audio-domain specific.
unsafe internal static bool AddMixerGroupSink(AudioMixerGroup mixerGroup, NativeArray<float> buffer, bool excludeFromMix)
{
return Internal_AudioRenderer_AddMixerGroupSink(mixerGroup, buffer.GetUnsafePtr(), buffer.Length, excludeFromMix);
}
unsafe public static bool Render(NativeArray<float> buffer)
{
return Internal_AudioRenderer_Render(buffer.GetUnsafePtr(), buffer.Length);
}
internal static extern bool Internal_AudioRenderer_Start();
internal static extern bool Internal_AudioRenderer_Stop();
internal static extern int Internal_AudioRenderer_GetSampleCountForCaptureFrame();
unsafe internal static extern bool Internal_AudioRenderer_AddMixerGroupSink(AudioMixerGroup mixerGroup, void* ptr, int length, bool excludeFromMix);
unsafe internal static extern bool Internal_AudioRenderer_Render(void* ptr, int length);
}
}
| UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioRenderer.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioRenderer.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 686
} | 369 |
// 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.Build.Content
{
[ExcludeFromPreset]
internal sealed partial class BuildInstructionImporter : AssetImporter
{
}
}
| UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildInstructionImporter.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildInstructionImporter.cs",
"repo_id": "UnityCsReference",
"token_count": 107
} | 370 |
// Unity 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;
namespace UnityEditor.Build.Content
{
[Serializable]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public struct ResourceFile
{
[SerializeField]
[NativeName("fileName")]
internal string m_FileName;
public string fileName { get { return m_FileName; } set { m_FileName = value; } }
[SerializeField]
[NativeName("fileAlias")]
internal string m_FileAlias;
public string fileAlias { get { return m_FileAlias; } set { m_FileAlias = value; } }
[SerializeField]
[NativeName("serializedFile")]
internal bool m_SerializedFile;
public bool serializedFile { get { return m_SerializedFile; } set { m_SerializedFile = value; } }
}
}
| UnityCsReference/Modules/BuildPipeline/Editor/Managed/ResourceFile.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/ResourceFile.cs",
"repo_id": "UnityCsReference",
"token_count": 382
} | 371 |
// Unity 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.Build.Profile.Elements;
using UnityEngine.UIElements;
namespace UnityEditor.Build.Profile.Handlers
{
internal class BuildProfileContextMenu
{
static readonly string k_Duplicate = L10n.Tr("Duplicate");
static readonly string k_CopyToNewProfile = L10n.Tr("Copy To New Profile");
static readonly string k_Rename = L10n.Tr("Rename");
static readonly string k_Delete = L10n.Tr("Delete");
static readonly string k_DeleteContinue = L10n.Tr("Continue");
static readonly string k_DeleteCancel = L10n.Tr("Cancel");
static readonly string k_DeleteTitle = L10n.Tr("Delete Active Build Profile");
static readonly string k_DeleteMessage = L10n.Tr("This will delete your active build profile and activate the respective platform build profile. This cannot be undone.");
readonly BuildProfileWindowSelection m_ProfileSelection;
readonly BuildProfileDataSource m_ProfileDataSource;
readonly BuildProfileWindow m_ProfileWindow;
internal BuildProfileContextMenu(BuildProfileWindow window, BuildProfileWindowSelection profileSelection, BuildProfileDataSource profileDataSource)
{
m_ProfileWindow = window;
m_ProfileSelection = profileSelection;
m_ProfileDataSource = profileDataSource;
}
internal ContextualMenuManipulator AddBuildProfileContextMenu()
{
return new ContextualMenuManipulator((evt) =>
{
BuildProfileListEditableLabel label = evt.target as BuildProfileListEditableLabel;
BuildProfile targetProfile = label.dataSource as BuildProfile;
if (targetProfile == null)
{
return;
}
bool isMultipleSelection = m_ProfileSelection.IsMultipleSelection();
bool isClassic = BuildProfileContext.IsClassicPlatformProfile(targetProfile);
if (!isMultipleSelection)
{
SelectBuildProfileInView(targetProfile, isClassic, shouldAppend: false);
}
evt.menu.ClearItems();
if (isClassic)
{
evt.menu.AppendAction(
k_CopyToNewProfile,
action =>
{
HandleDuplicateSelectedProfiles(duplicateClassic: true);
});
}
else
{
evt.menu.AppendAction(
k_Duplicate,
action =>
{
HandleDuplicateSelectedProfiles(duplicateClassic: false);
});
evt.menu.AppendAction(
k_Rename,
action =>
{
label.EditName();
}, isMultipleSelection ? DropdownMenuAction.Status.Disabled : DropdownMenuAction.Status.Normal);
evt.menu.AppendAction(
k_Delete,
action =>
{
HandleDeleteSelectedProfiles();
});
}
});
}
internal bool UpdateBuildProfileLabelName(object buildProfileObject, string buildProfileLabelName)
{
var buildProfile = buildProfileObject as BuildProfile;
if (buildProfile == null || string.IsNullOrEmpty(buildProfileLabelName))
return false;
string newName = buildProfileLabelName;
m_ProfileDataSource.RenameAsset(buildProfile, newName);
m_ProfileSelection.ClearListViewSelection(BuildProfileWindowSelection.ListViewSelectionType.ClassicAndCustom);
SelectBuildProfileInView(buildProfile, isClassic: false, shouldAppend: false);
return true;
}
internal void HandleDuplicateSelectedProfiles(bool duplicateClassic)
{
var selectedProfiles = m_ProfileSelection.GetAll();
var duplicatedProfiles = m_ProfileDataSource.DuplicateProfiles(selectedProfiles, duplicateClassic);
m_ProfileWindow.RepaintAndClearSelection();
for (int i = 0; i < duplicatedProfiles.Count; ++i)
{
var duplicated = duplicatedProfiles[i];
bool shouldAppend = i > 0;
SelectBuildProfileInView(duplicated, isClassic: false, shouldAppend);
}
}
internal void SelectClassicBuildProfileInViewForModule(string moduleName)
{
var targetIndex = -1;
for (int i = 0; i < m_ProfileDataSource.classicPlatforms.Count; ++i)
{
var platform = m_ProfileDataSource.classicPlatforms[i];
if (platform.moduleName == moduleName)
{
targetIndex = i;
break;
}
}
if (targetIndex >= 0)
m_ProfileSelection.SelectBuildProfileInViewByIndex(targetIndex, isClassic: true, shouldAppend: false);
}
void SelectBuildProfileInView(BuildProfile buildProfile, bool isClassic, bool shouldAppend)
{
var targetProfiles = isClassic ? m_ProfileDataSource.classicPlatforms : m_ProfileDataSource.customBuildProfiles;
var index = targetProfiles.IndexOf(buildProfile);
if (index >= 0)
m_ProfileSelection.SelectBuildProfileInViewByIndex(index, isClassic, shouldAppend);
}
void HandleDeleteSelectedProfiles()
{
var selectedProfiles = m_ProfileSelection.GetAll();
for (int i = selectedProfiles.Count - 1; i >= 0; --i)
{
var profile = selectedProfiles[i];
if (BuildProfileContext.instance.activeProfile == profile)
{
string path = AssetDatabase.GetAssetPath(profile);
string finalMessage = $"{path}\n\n{k_DeleteMessage}";
if (!EditorUtility.DisplayDialog(k_DeleteTitle, finalMessage, k_DeleteContinue, k_DeleteCancel))
{
continue;
}
}
m_ProfileDataSource.DeleteAsset(profile);
}
// No need to select a profile after deletion, since the method below
// selects the active profile after repaint
m_ProfileWindow.RepaintAndClearSelection();
}
}
}
| UnityCsReference/Modules/BuildProfileEditor/Handlers/BuildProfileContextMenu.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildProfileEditor/Handlers/BuildProfileContextMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 3267
} | 372 |
// Unity 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/PackedAssets.h")]
public struct PackedAssetInfo
{
[NativeName("fileID")]
public long id { get; }
public Type type { get; }
public ulong packedSize { get; }
public ulong offset { get; }
public GUID sourceAssetGUID { get; }
[NativeName("buildTimeAssetPath")]
public string sourceAssetPath { get; }
}
}
| UnityCsReference/Modules/BuildReportingEditor/Managed/PackedAssetInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/PackedAssetInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 252
} | 373 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Bindings;
namespace UnityEngine
{
[Internal.ExcludeFromDocs]
[NativeHeader("Modules/ClusterRenderer/ClusterSerialization.h")]
public static class ClusterSerialization
{
public static int SaveTimeManagerState(NativeArray<byte> buffer)
{
unsafe
{
return SaveTimeManagerStateInternal((byte*)buffer.GetUnsafePtr(), buffer.Length);
}
}
public static bool RestoreTimeManagerState(NativeArray<byte> buffer)
{
unsafe
{
return RestoreTimeManagerStateInternal((byte*)buffer.GetUnsafePtr(), buffer.Length);
}
}
public static int SaveInputManagerState(NativeArray<byte> buffer)
{
unsafe
{
return SaveInputManagerStateInternal((byte*)buffer.GetUnsafePtr(), buffer.Length);
}
}
public static bool RestoreInputManagerState(NativeArray<byte> buffer)
{
unsafe
{
return RestoreInputManagerStateInternal((byte*)buffer.GetUnsafePtr(), buffer.Length);
}
}
public static int SaveClusterInputState(NativeArray<byte> buffer)
{
unsafe
{
return SaveClusterInputStateInternal((byte*)buffer.GetUnsafePtr(), buffer.Length);
}
}
public static bool RestoreClusterInputState(NativeArray<byte> buffer)
{
unsafe
{
return RestoreClusterInputStateInternal((byte*)buffer.GetUnsafePtr(), buffer.Length);
}
}
[FreeFunction("ClusterSerialization::SaveTimeManagerState")]
private static extern unsafe int SaveTimeManagerStateInternal(void* intBuffer, int bufferSize);
[FreeFunction("ClusterSerialization::RestoreTimeManagerState")]
private static extern unsafe bool RestoreTimeManagerStateInternal(void* buffer, int bufferSize);
[FreeFunction("ClusterSerialization::SaveInputManagerState")]
private static extern unsafe int SaveInputManagerStateInternal(void* intBuffer, int bufferSize);
[FreeFunction("ClusterSerialization::RestoreInputManagerState")]
private static extern unsafe bool RestoreInputManagerStateInternal(void* buffer, int bufferSize);
[FreeFunction("ClusterSerialization::SaveClusterInputState")]
private static extern unsafe int SaveClusterInputStateInternal(void* intBuffer, int bufferSize);
[FreeFunction("ClusterSerialization::RestoreClusterInputState")]
private static extern unsafe bool RestoreClusterInputStateInternal(void* buffer, int bufferSize);
}
}
| UnityCsReference/Modules/ClusterRenderer/ClusterSerialization.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ClusterRenderer/ClusterSerialization.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1157
} | 374 |
// 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.AssetImporters;
namespace UnityEditor.DeviceSimulation
{
[CustomEditor(typeof(DeviceInfoImporter))]
class DeviceInfoImporterEditor : ScriptedImporterEditor
{
}
}
| UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfoImporterEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfoImporterEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 117
} | 375 |
// Unity 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.DeviceSimulation
{
internal enum ResolutionScalingMode
{
Disabled = 0,
FixedDpi = 1,
Letterboxed = 2
}
internal enum SimulationState{ Enabled, Disabled }
internal static class SimulatorUtilities
{
public static ScreenOrientation ToScreenOrientation(UIOrientation original)
{
switch (original)
{
case UIOrientation.Portrait:
return ScreenOrientation.Portrait;
case UIOrientation.PortraitUpsideDown:
return ScreenOrientation.PortraitUpsideDown;
case UIOrientation.LandscapeLeft:
return ScreenOrientation.LandscapeLeft;
case UIOrientation.LandscapeRight:
return ScreenOrientation.LandscapeRight;
case UIOrientation.AutoRotation:
return ScreenOrientation.AutoRotation;
}
throw new ArgumentException($"Unexpected value of UIOrientation {original}");
}
public static ScreenOrientation RotationToScreenOrientation(int angle)
{
ScreenOrientation orientation = ScreenOrientation.Portrait;
if (angle > 315 || angle <= 45)
{
orientation = ScreenOrientation.Portrait;
}
else if (angle > 45 && angle <= 135)
{
orientation = ScreenOrientation.LandscapeRight;
}
else if (angle > 135 && angle <= 225)
{
orientation = ScreenOrientation.PortraitUpsideDown;
}
else if (angle > 225 && angle <= 315)
{
orientation = ScreenOrientation.LandscapeLeft;
}
return orientation;
}
public static bool IsLandscape(this ScreenOrientation orientation)
{
if (orientation == ScreenOrientation.LandscapeLeft || orientation == ScreenOrientation.LandscapeRight)
return true;
return false;
}
}
}
| UnityCsReference/Modules/DeviceSimulatorEditor/SimulatorUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/SimulatorUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 1060
} | 376 |
// Unity 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.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Toolbars
{
public class EditorToolbarButton : ToolbarButton
{
internal const string textClassName = EditorToolbar.elementLabelClassName;
internal const string iconClassName = EditorToolbar.elementIconClassName;
readonly Image m_IconElement;
TextElement m_TextElement;
public new string text
{
get => m_TextElement?.text;
set
{
if (string.IsNullOrEmpty(value))
{
m_TextElement?.RemoveFromHierarchy();
m_TextElement = null;
return;
}
if (m_TextElement == null)
{
Insert(IndexOf(m_IconElement)+1, m_TextElement = new TextElement());
m_TextElement.AddToClassList(textClassName);
}
m_TextElement.text = value;
}
}
public Texture2D icon
{
get => m_IconElement.image as Texture2D;
set
{
m_IconElement.image = value;
m_IconElement.style.display = value != null ? DisplayStyle.Flex : DisplayStyle.None;
}
}
public EditorToolbarButton() : this(string.Empty, null, null) {}
public EditorToolbarButton(Action clickEvent) : this(string.Empty, null, clickEvent) {}
public EditorToolbarButton(string text, Action clickEvent) : this(text, null, clickEvent) {}
public EditorToolbarButton(Texture2D icon, Action clickEvent) : this(string.Empty, icon, clickEvent) {}
public EditorToolbarButton(string text, Texture2D icon, Action clickEvent) : base(clickEvent)
{
m_IconElement = new Image { scaleMode = ScaleMode.ScaleToFit };
m_IconElement.AddToClassList(iconClassName);
this.icon = icon;
Add(m_IconElement);
this.text = text;
}
}
}
| UnityCsReference/Modules/EditorToolbar/Controls/EditorToolbarButton.cs/0 | {
"file_path": "UnityCsReference/Modules/EditorToolbar/Controls/EditorToolbarButton.cs",
"repo_id": "UnityCsReference",
"token_count": 1026
} | 377 |
// Unity 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.ShortcutManagement;
using UnityEditor.Toolbars;
using UnityEngine;
using UnityEngine.UIElements;
using static UnityEditor.EditorWindow;
namespace UnityEditor.Overlays
{
sealed class OverlayPresetDropdown : BasePopupField<string, string>
{
readonly EditorWindow m_TargetWindow;
public OverlayPresetDropdown(EditorWindow targetWindow)
{
m_TargetWindow = targetWindow;
createMenuCallback = DropdownUtility.CreateDropdown;
SetValueWithoutNotify(m_TargetWindow.overlayCanvas.lastAppliedPresetName);
}
internal override void AddMenuItems(IGenericMenu menu)
{
OverlayPresetManager.GenerateMenu(menu, "", m_TargetWindow);
}
internal override string GetValueToDisplay()
{
if (m_TargetWindow == null)
return string.Empty;
return m_TargetWindow.overlayCanvas.lastAppliedPresetName;
}
//We don't actually use this but we are required to implement it
internal override string GetListItemToDisplay(string item) => item;
}
[Overlay(typeof(EditorWindow), "Overlays/OverlayMenu", "Overlay Menu", "overlay-menu", defaultDockZone = DockZone.LeftColumn, defaultLayout = Layout.HorizontalToolbar, defaultDisplay = true)]
sealed class OverlayMenu : Overlay, ICreateHorizontalToolbar, ICreateVerticalToolbar
{
class Toolbar : OverlayToolbar
{
OverlayMenu m_Menu;
VisualElement m_GlobalToolbar;
VisualElement m_TransientToolbar;
VisualElement m_Separator;
List<(Overlay overlay, int priority)> m_Overlays;
public Toolbar(OverlayMenu menu, bool horizontal)
{
m_Menu = menu;
Add(m_GlobalToolbar = new VisualElement());
m_GlobalToolbar.style.flexDirection = horizontal ? FlexDirection.Row : FlexDirection.Column;
m_Separator = new VisualElement() { name = "Separator" };
m_Separator.AddToClassList("unity-separator");
Add(m_Separator);
Add(m_TransientToolbar = new VisualElement());
m_TransientToolbar.style.flexDirection = horizontal ? FlexDirection.Row : FlexDirection.Column;
m_Overlays = new List<(Overlay, int)>();
RebuildContent();
}
static EditorToolbarToggle CreateToggle(Overlay overlay)
{
var iconContent = overlay.GetCollapsedIconContent();
var image = iconContent.image as Texture2D;
var toggle = image != null ? new EditorToolbarToggle(image) : new EditorToolbarToggle(iconContent.text);
toggle.tooltip = overlay.displayName;
toggle.SetValueWithoutNotify(overlay.displayed);
toggle.RegisterValueChangedCallback((evt) => overlay.displayed = evt.newValue);
Action<bool> displayedChanged = (value) => toggle.SetValueWithoutNotify(value);
toggle.RegisterCallback<AttachToPanelEvent>((evt) => overlay.displayedChanged += displayedChanged);
toggle.RegisterCallback<DetachFromPanelEvent>((evt) => overlay.displayedChanged -= displayedChanged);
return toggle;
}
public void RebuildContent()
{
m_GlobalToolbar.Clear();
m_Overlays.Clear();
foreach (var overlay in m_Menu.canvas.overlays)
{
if (!m_Menu.ShouldShowOverlay(overlay) || overlay is OverlayMenu)
continue;
var attrib = OverlayUtilities.GetAttribute(m_Menu.containerWindow.GetType(), overlay.GetType());
m_Overlays.Add((overlay, attrib.priority));
}
m_Overlays.Sort((a, b) => a.priority.CompareTo(b.priority));
foreach(var tuple in m_Overlays)
m_GlobalToolbar.Add(CreateToggle(tuple.overlay));
EditorToolbarUtility.SetupChildrenAsButtonStrip(m_GlobalToolbar);
m_Separator.style.display = m_Menu.canvas.HasTransientOverlays() ? DisplayStyle.Flex : DisplayStyle.None;
m_TransientToolbar.Clear();
foreach (var overlay in m_Menu.canvas.transientOverlays)
m_TransientToolbar.Add(CreateToggle(overlay));
EditorToolbarUtility.SetupChildrenAsButtonStrip(m_TransientToolbar);
}
}
ScrollView m_ListRoot;
Toggle m_Toggle;
OverlayPresetDropdown m_Dropdown;
Toolbar m_Toolbar;
const string k_ShowOverlayMenuShortcut = "Overlays/Show Overlay Menu";
[InitializeOnLoadMethod]
static void AddOverlayToWindowMenu()
{
HostView.populateDefaultMenuItems += PopulateDefaultMenuItems;
}
static void PopulateDefaultMenuItems(GenericMenu menu, EditorWindow targetWindow)
{
if (targetWindow is ISupportsOverlays)
{
var binding = ShortcutManager.instance.GetShortcutBinding(k_ShowOverlayMenuShortcut);
menu.AddItem(EditorGUIUtility.TrTextContent($"Overlay Menu _{binding}"), false,
() =>
{
targetWindow.overlayCanvas.ShowPopup<OverlayMenu>();
});
}
}
[Shortcut(k_ShowOverlayMenuShortcut, typeof(OverlayShortcutContext), KeyCode.BackQuote)]
static void ShowOverlayMenu(ShortcutArguments args)
{
if (args.context is OverlayShortcutContext context)
context.editorWindow.overlayCanvas.ShowPopupAtMouse<OverlayMenu>();
}
public override void OnCreated()
{
canvas.overlaysEnabledChanged += OnOverlayEnabledChanged;
canvas.overlayListChanged += OnOverlayListChanged;
displayedChanged += OnDisplayedChanged;
}
public override void OnWillBeDestroyed()
{
canvas.overlaysEnabledChanged -= OnOverlayEnabledChanged;
canvas.overlayListChanged -= OnOverlayListChanged;
displayedChanged -= OnDisplayedChanged;
}
void OnDisplayedChanged(bool displayed)
{
if (!displayed)
SetHighlightEnabled(false);
}
void OnOverlayEnabledChanged(bool visibility)
{
m_Toggle?.SetValueWithoutNotify(visibility);
m_Dropdown?.SetEnabled(visibility);
}
void OnOverlayListChanged()
{
if (m_Toolbar != null)
m_Toolbar.RebuildContent();
else
RebuildList();
}
bool ShouldShowOverlay(Overlay overlay)
{
return overlay.userControlledVisibility && overlay.hasMenuEntry && !canvas.IsTransient(overlay) && (overlay != this || isPopup);
}
public OverlayToolbar CreateHorizontalToolbarContent()
{
return m_Toolbar = new Toolbar(this, true);
}
public OverlayToolbar CreateVerticalToolbarContent()
{
return m_Toolbar = new Toolbar(this, false);
}
public override VisualElement CreatePanelContent()
{
VisualElement content = new VisualElement();
content.style.minWidth = 160;
m_Toolbar = null;
if (isPopup)
{
content.Add(m_Toggle = new Toggle(L10n.Tr("Enable Overlays")) { name = "overlay-toggle" });
m_Toggle.RegisterCallback<ChangeEvent<bool>>((evt) =>
{
canvas.overlaysEnabled = evt.newValue;
});
m_Toggle.SetValueWithoutNotify(canvas.overlaysEnabled);
}
content.Add(m_Dropdown = new OverlayPresetDropdown(canvas.containerWindow));
content.Add(m_ListRoot = new ScrollView() { name = "OverlayList" });
m_ListRoot.horizontalScrollerVisibility = ScrollerVisibility.Auto;
m_ListRoot.verticalScrollerVisibility = ScrollerVisibility.Auto;
RebuildList();
return content;
}
void RebuildList()
{
if (m_ListRoot == null)
return;
m_ListRoot.Clear();
var overlays = new List<(Overlay overlay, int priority)>();
foreach (var overlay in canvas.overlays)
{
if (!ShouldShowOverlay(overlay))
continue;
var attrib = OverlayUtilities.GetAttribute(containerWindow.GetType(), overlay.GetType());
overlays.Add((overlay, attrib.priority));
}
overlays.Sort((a, b) => a.priority.CompareTo(b.priority));
foreach(var sortedOverlay in overlays)
m_ListRoot.Add(new OverlayMenuItem() { overlay = sortedOverlay.overlay });
if (canvas.HasTransientOverlays())
{
var separator = new VisualElement() { name = "Separator" };
separator.AddToClassList("unity-separator");
m_ListRoot.Add(separator);
}
foreach (var overlay in canvas.transientOverlays)
{
m_ListRoot.Add(new OverlayMenuItem() { overlay = overlay });
}
}
}
}
| UnityCsReference/Modules/EditorToolbar/ToolbarElements/OverlayMenu.cs/0 | {
"file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/OverlayMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 4485
} | 378 |
// Unity 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.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public class Blackboard : GraphElement, ISelection
{
private VisualElement m_MainContainer;
private VisualElement m_Root;
private Label m_TitleLabel;
private Label m_SubTitleLabel;
private ScrollView m_ScrollView;
private VisualElement m_ContentContainer;
private VisualElement m_HeaderItem;
private Button m_AddButton;
private bool m_Scrollable = true;
private Dragger m_Dragger;
private GraphView m_GraphView;
public GraphView graphView
{
get
{
if (!windowed && m_GraphView == null)
m_GraphView = GetFirstAncestorOfType<GraphView>();
return m_GraphView;
}
set
{
if (!windowed)
return;
m_GraphView = value;
}
}
internal static readonly string StyleSheetPath = "StyleSheets/GraphView/Blackboard.uss";
public Action<Blackboard> addItemRequested { get; set; }
public Action<Blackboard, int, VisualElement> moveItemRequested { get; set; }
public Action<Blackboard, VisualElement, string> editTextRequested { get; set; }
// ISelection implementation
public List<ISelectable> selection
{
get
{
return graphView?.selection;
}
}
public override string title
{
get { return m_TitleLabel.text; }
set { m_TitleLabel.text = value; }
}
public string subTitle
{
get { return m_SubTitleLabel.text; }
set { m_SubTitleLabel.text = value; }
}
bool m_Windowed;
public bool windowed
{
get { return m_Windowed; }
set
{
if (m_Windowed == value) return;
if (value)
{
capabilities &= ~Capabilities.Movable;
AddToClassList("windowed");
this.RemoveManipulator(m_Dragger);
}
else
{
capabilities |= Capabilities.Movable;
RemoveFromClassList("windowed");
this.AddManipulator(m_Dragger);
}
m_Windowed = value;
}
}
public override VisualElement contentContainer { get { return m_ContentContainer; } }
public bool scrollable
{
get
{
return m_Scrollable;
}
set
{
if (m_Scrollable == value)
return;
m_Scrollable = value;
if (m_Scrollable)
{
if (m_ScrollView == null)
{
m_ScrollView = new ScrollView(ScrollViewMode.VerticalAndHorizontal);
}
// Remove the sections container from the content item and add it to the scrollview
m_ContentContainer.RemoveFromHierarchy();
m_Root.Add(m_ScrollView);
m_ScrollView.Add(m_ContentContainer);
resizeRestriction = ResizeRestriction.None; // As both the width and height can be changed by the user using a resizer
AddToClassList("scrollable");
}
else
{
if (m_ScrollView != null)
{
// Remove the sections container from the scrollview and add it to the content item
resizeRestriction = ResizeRestriction.FlexDirection; // As the height is automatically computed from the content but the width can be changed by the user using a resizer
m_ScrollView.RemoveFromHierarchy();
m_ContentContainer.RemoveFromHierarchy();
m_Root.Add(m_ContentContainer);
}
RemoveFromClassList("scrollable");
}
}
}
public Blackboard(GraphView associatedGraphView = null)
{
var tpl = EditorGUIUtility.Load("UXML/GraphView/Blackboard.uxml") as VisualTreeAsset;
AddStyleSheetPath(StyleSheetPath);
m_MainContainer = tpl.Instantiate();
m_MainContainer.AddToClassList("mainContainer");
m_Root = m_MainContainer.Q("content");
m_HeaderItem = m_MainContainer.Q("header");
m_HeaderItem.AddToClassList("blackboardHeader");
m_AddButton = m_MainContainer.Q(name: "addButton") as Button;
m_AddButton.clickable.clicked += () => {
if (addItemRequested != null)
{
addItemRequested(this);
}
};
m_TitleLabel = m_MainContainer.Q<Label>(name: "titleLabel");
m_SubTitleLabel = m_MainContainer.Q<Label>(name: "subTitleLabel");
m_ContentContainer = m_MainContainer.Q(name: "contentContainer");
hierarchy.Add(m_MainContainer);
capabilities |= Capabilities.Movable | Capabilities.Resizable;
style.overflow = Overflow.Hidden;
ClearClassList();
AddToClassList("blackboard");
m_Dragger = new Dragger { clampToParentEdges = true };
this.AddManipulator(m_Dragger);
scrollable = false;
hierarchy.Add(new Resizer());
RegisterCallback<DragUpdatedEvent>(e =>
{
e.StopPropagation();
});
// event interception to prevent GraphView manipulators from being triggered
// when working with the blackboard
// prevent Zoomer manipulator
RegisterCallback<WheelEvent>(e =>
{
e.StopPropagation();
});
RegisterCallback<MouseDownEvent>(e =>
{
if (e.button == (int)MouseButton.LeftMouse)
ClearSelection();
// prevent ContentDragger manipulator
e.StopPropagation();
});
RegisterCallback<ValidateCommandEvent>(OnValidateCommand);
RegisterCallback<ExecuteCommandEvent>(OnExecuteCommand);
m_GraphView = associatedGraphView;
focusable = true;
}
public virtual void AddToSelection(ISelectable selectable)
{
graphView?.AddToSelection(selectable);
}
public virtual void RemoveFromSelection(ISelectable selectable)
{
graphView?.RemoveFromSelection(selectable);
}
public virtual void ClearSelection()
{
graphView?.ClearSelection();
}
private void OnValidateCommand(ValidateCommandEvent evt)
{
graphView?.OnValidateCommand(evt);
}
private void OnExecuteCommand(ExecuteCommandEvent evt)
{
graphView?.OnExecuteCommand(evt);
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Elements/Blackboard/Blackboard.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/Blackboard/Blackboard.cs",
"repo_id": "UnityCsReference",
"token_count": 3742
} | 379 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public class PlacematContainer : GraphView.Layer
{
public enum CycleDirection
{
Up,
Down
}
LinkedList<Placemat> m_Placemats;
public IEnumerable<Placemat> Placemats => m_Placemats;
GraphView m_GraphView;
public PlacematContainer(GraphView graphView)
{
m_Placemats = new LinkedList<Placemat>();
m_GraphView = graphView;
AddStyleSheetPath("PlacematContainer");
AddToClassList("placematContainer");
pickingMode = PickingMode.Ignore;
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
m_GraphView.graphViewChanged += OnGraphViewChange;
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
// ReSharper disable once DelegateSubtraction
m_GraphView.graphViewChanged -= OnGraphViewChange;
}
GraphViewChange OnGraphViewChange(GraphViewChange graphViewChange)
{
if (graphViewChange.elementsToRemove != null)
foreach (Placemat placemat in graphViewChange.elementsToRemove.OfType<Placemat>())
RemovePlacemat(placemat);
return graphViewChange;
}
public static int PlacematsLayer => Int32.MinValue;
void AddPlacemat(Placemat placemat)
{
m_Placemats.AddLast(placemat);
Add(placemat);
}
void RemovePlacemat(Placemat placemat)
{
placemat.RemoveFromHierarchy();
m_Placemats.Remove(placemat);
}
public bool GetPortCenterOverride(Port port, out Vector2 overriddenPosition)
{
Node rootNode = port.node;
if (rootNode != null)
{
Node currNode;
while ((currNode = rootNode.GetFirstAncestorOfType<Node>()) != null)
rootNode = currNode;
//Find the furthest placemat containing the rootNode and that is collapsed (if any)
Placemat placemat = m_Placemats.FirstOrDefault(p => p.Collapsed && p.WillDragNode(rootNode));
if (placemat != null)
return placemat.GetPortCenterOverride(port, out overriddenPosition);
}
overriddenPosition = Vector3.zero;
return false;
}
public T CreatePlacemat<T>(Rect placematPosition, int zOrder, string placematTitle) where T : Placemat, new()
{
return InitAndAddPlacemat(new T(), placematPosition, zOrder, placematTitle);
}
public T CreatePlacemat<T>(Func<T> creator, Rect placematPosition, int zOrder, string placematTitle) where T : Placemat
{
return InitAndAddPlacemat(creator(), placematPosition, zOrder, placematTitle);
}
T InitAndAddPlacemat<T>(T placemat, Rect placematPosition, int zOrder, string placematTitle) where T : Placemat
{
placemat.Init(m_GraphView);
placemat.title = placematTitle;
placemat.SetPosition(placematPosition);
placemat.ZOrder = zOrder;
AddPlacemat(placemat);
return placemat;
}
public void RemoveAllPlacemats()
{
Clear();
m_Placemats.Clear();
}
public int GetTopZOrder()
{
return m_Placemats.Last?.Value.ZOrder + 1 ?? 1;
}
internal void CyclePlacemat(Placemat placemat, CycleDirection direction)
{
var node = m_Placemats.Find(placemat);
if (node == null)
return;
var next = direction == CycleDirection.Up ? node.Next : node.Previous;
if (next != null)
{
m_Placemats.Remove(placemat);
if (direction == CycleDirection.Down)
m_Placemats.AddBefore(next, node);
else
m_Placemats.AddAfter(next, node);
}
UpdateElementsOrder();
}
protected virtual void UpdateElementsOrder()
{
// Reset ZOrder from placemat order in array
int idx = 1;
foreach (var placemat in m_Placemats)
placemat.ZOrder = idx++;
Sort((a, b) => ((Placemat)a).ZOrder.CompareTo(((Placemat)b).ZOrder));
}
internal void SendToBack(Placemat placemat)
{
m_Placemats.Remove(placemat);
m_Placemats.AddFirst(placemat);
UpdateElementsOrder();
}
internal void BringToFront(Placemat placemat)
{
m_Placemats.Remove(placemat);
m_Placemats.AddLast(placemat);
UpdateElementsOrder();
}
public void HideCollapsedEdges()
{
// We need to hide edges in the reverse zOrder (topmost mats are collapsed first)
foreach (var p in Placemats.OrderByDescending(p => p.ZOrder))
{
p.HideCollapsedEdges();
}
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Elements/Placemat/PlacematContainer.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/Placemat/PlacematContainer.cs",
"repo_id": "UnityCsReference",
"token_count": 2771
} | 380 |
// Unity 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.UIElements;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEditor.Experimental.GraphView
{
public class IconBadge : VisualElement
{
static CustomStyleProperty<int> s_DistanceProperty = new CustomStyleProperty<int>("--distance");
private VisualElement m_TipElement;
private VisualElement m_IconElement;
private Label m_TextElement;
protected SpriteAlignment alignment { get; set; }
protected VisualElement target { get; set; }
public string badgeText
{
get
{
return (m_TextElement != null) ? m_TextElement.text : string.Empty;
}
set
{
if (m_TextElement != null)
{
m_TextElement.text = value;
}
}
}
public string visualStyle
{
get
{
return m_BadgeType;
}
set
{
if (m_BadgeType != value)
{
string modifier = "--" + m_BadgeType;
RemoveFromClassList(ussClassName + modifier);
m_TipElement?.RemoveFromClassList(tipUssClassName + modifier);
m_IconElement?.RemoveFromClassList(iconUssClassName + modifier);
m_TextElement?.RemoveFromClassList(textUssClassName + modifier);
m_BadgeType = value;
modifier = "--" + m_BadgeType;
AddToClassList(ussClassName + modifier);
m_TipElement?.AddToClassList(tipUssClassName + modifier);
m_IconElement?.AddToClassList(iconUssClassName + modifier);
m_TextElement?.AddToClassList(textUssClassName + modifier);
}
}
}
private const int kDefaultDistanceValue = 6;
private int m_Distance;
private bool m_DistanceIsInline;
public int distance
{
get { return m_Distance; }
set
{
m_DistanceIsInline = true;
if (value != m_Distance)
{
m_Distance = value;
if (m_Attacher != null)
m_Attacher.distance = m_Distance;
}
}
}
private int m_CurrentTipAngle = 0;
private Attacher m_Attacher = null;
private bool m_IsAttached;
private VisualElement m_originalParent;
private Attacher m_TextAttacher = null;
private string m_BadgeType;
public IconBadge()
{
m_IsAttached = false;
m_Distance = kDefaultDistanceValue;
var tpl = EditorGUIUtility.Load("GraphView/Badge/IconBadge.uxml") as VisualTreeAsset;
LoadTemplate(tpl);
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
visualStyle = "error";
}
public IconBadge(VisualTreeAsset template)
{
m_IsAttached = false;
m_Distance = kDefaultDistanceValue;
LoadTemplate(template);
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
visualStyle = "error";
}
internal static readonly string ussClassName = "icon-badge";
internal static readonly string iconUssClassName = ussClassName + "__icon";
internal static readonly string tipUssClassName = ussClassName + "__tip";
internal static readonly string textUssClassName = ussClassName + "__text";
private static readonly string defaultStylePath = "GraphView/Badge/IconBadge.uss";
private void LoadTemplate(VisualTreeAsset tpl)
{
tpl.CloneTree(this);
InitBadgeComponent("tip", tipUssClassName, ref m_TipElement);
InitBadgeComponent("icon", iconUssClassName, ref m_IconElement);
InitBadgeComponent("text", textUssClassName, ref m_TextElement);
if (m_TipElement != null)
{
////we make sure the tip is in the back
m_TipElement.SendToBack();
}
name = "IconBadge";
AddToClassList(ussClassName);
AddStyleSheetPath(defaultStylePath);
if (m_TextElement != null)
{
m_TextElement.RemoveFromHierarchy();
//we need to add the style sheet to the Text element as well since it will be parented elsewhere
m_TextElement.AddStyleSheetPath(defaultStylePath);
m_TextElement.style.whiteSpace = WhiteSpace.Normal;
m_TextElement.RegisterCallback<GeometryChangedEvent>((evt) => ComputeTextSize());
m_TextElement.pickingMode = PickingMode.Ignore;
}
}
private void InitBadgeComponent<ElementType>(string name, string ussClassName, ref ElementType outElement) where ElementType : VisualElement
{
outElement = this.Q<ElementType>(name);
if (outElement == null)
{
Debug.Log($"IconBadge: Couldn't load {name} element from template");
}
else
{
outElement.AddToClassList(ussClassName);
}
}
public static IconBadge CreateError(string message)
{
var result = new IconBadge();
result.visualStyle = "error";
result.badgeText = message;
return result;
}
public static IconBadge CreateComment(string message)
{
var result = new IconBadge();
result.visualStyle = "comment";
result.badgeText = message;
return result;
}
public void AttachTo(VisualElement target, SpriteAlignment align)
{
Detach();
this.alignment = align;
this.target = target;
m_IsAttached = true;
target.RegisterCallback<DetachFromPanelEvent>(OnTargetDetachedFromPanel);
CreateAttacher();
}
public void Detach()
{
if (m_IsAttached)
{
target.UnregisterCallback<DetachFromPanelEvent>(OnTargetDetachedFromPanel);
m_IsAttached = false;
}
ReleaseAttacher();
m_originalParent = null;
}
private void OnTargetDetachedFromPanel(DetachFromPanelEvent evt)
{
ReleaseAttacher();
if (m_IsAttached)
{
m_originalParent = hierarchy.parent;
RemoveFromHierarchy();
target.UnregisterCallback<DetachFromPanelEvent>(OnTargetDetachedFromPanel);
target.RegisterCallback<AttachToPanelEvent>(OnTargetAttachedToPanel);
}
}
private void OnTargetAttachedToPanel(AttachToPanelEvent evt)
{
if (m_IsAttached)
{
target.RegisterCallback<DetachFromPanelEvent>(OnTargetDetachedFromPanel);
//we re-add ourselves to the hierarchy
if (m_originalParent != null)
{
m_originalParent.hierarchy.Add(this);
}
if (m_Attacher != null)
{
ReleaseAttacher();
}
CreateAttacher();
}
}
private void ReleaseAttacher()
{
if (m_Attacher != null)
{
m_Attacher.Detach();
m_Attacher = null;
}
}
private void CreateAttacher()
{
m_Attacher = new Attacher(this, target, alignment);
m_Attacher.distance = distance;
}
private void ComputeTextSize()
{
if (m_TextElement != null)
{
float maxWidth = m_TextElement.resolvedStyle.maxWidth == StyleKeyword.None ? float.NaN : m_TextElement.resolvedStyle.maxWidth.value;
Vector2 newSize = m_TextElement.DoMeasure(maxWidth, MeasureMode.AtMost,
0, MeasureMode.Undefined);
m_TextElement.style.width = newSize.x +
m_TextElement.resolvedStyle.marginLeft +
m_TextElement.resolvedStyle.marginRight +
m_TextElement.resolvedStyle.borderLeftWidth +
m_TextElement.resolvedStyle.borderRightWidth +
m_TextElement.resolvedStyle.paddingLeft +
m_TextElement.resolvedStyle.paddingRight;
float height = newSize.y +
m_TextElement.resolvedStyle.marginTop +
m_TextElement.resolvedStyle.marginBottom +
m_TextElement.resolvedStyle.borderTopWidth +
m_TextElement.resolvedStyle.borderBottomWidth +
m_TextElement.resolvedStyle.paddingTop +
m_TextElement.resolvedStyle.paddingBottom;
m_TextElement.style.height = height;
if (m_TextAttacher != null)
{
m_TextAttacher.offset = new Vector2(0, height);
}
PerformTipLayout();
}
}
private void ShowText()
{
if (m_TextElement != null && m_TextElement.hierarchy.parent == null)
{
VisualElement textParent = this;
GraphView gv = GetFirstAncestorOfType<GraphView>();
if (gv != null)
{
textParent = gv;
}
textParent.Add(m_TextElement);
if (textParent != this)
{
if (m_TextAttacher == null)
{
m_TextAttacher = new Attacher(m_TextElement, m_IconElement, SpriteAlignment.TopRight);
}
else
{
m_TextAttacher.Reattach();
}
}
m_TextAttacher.distance = 0;
m_TextElement.ResetPositionProperties();
ComputeTextSize();
}
}
private void HideText()
{
if (m_TextElement != null && m_TextElement.hierarchy.parent != null)
{
m_TextAttacher?.Detach();
m_TextElement.RemoveFromHierarchy();
}
}
[EventInterest(typeof(GeometryChangedEvent), typeof(DetachFromPanelEvent), typeof(MouseEnterEvent),
typeof(MouseLeaveEvent))]
protected override void HandleEventBubbleUp(EventBase evt)
{
base.HandleEventBubbleUp(evt);
if (evt.eventTypeId == GeometryChangedEvent.TypeId())
{
if (m_Attacher != null)
PerformTipLayout();
}
else if (evt.eventTypeId == DetachFromPanelEvent.TypeId())
{
if (m_Attacher != null)
{
m_Attacher.Detach();
m_Attacher = null;
}
HideText();
}
else if (evt.eventTypeId == MouseEnterEvent.TypeId())
{
//we make sure we sit on top of whatever siblings we have
BringToFront();
ShowText();
}
else if (evt.eventTypeId == MouseLeaveEvent.TypeId())
{
HideText();
}
}
[EventInterest(EventInterestOptions.Inherit)]
[Obsolete("ExecuteDefaultAction override has been removed because default event handling was migrated to HandleEventBubbleUp. Please use HandleEventBubbleUp.", false)]
protected override void ExecuteDefaultAction(EventBase evt)
{
}
private void PerformTipLayout()
{
float contentWidth = resolvedStyle.width;
float arrowWidth = 0;
float arrowLength = 0;
if (m_TipElement != null)
{
arrowWidth = m_TipElement.resolvedStyle.width;
arrowLength = m_TipElement.resolvedStyle.height;
}
float iconSize = 0f;
if (m_IconElement != null)
{
iconSize = m_IconElement.computedStyle.width.IsAuto() ? contentWidth - arrowLength : m_IconElement.computedStyle.width.value;
}
float arrowOffset = Mathf.Floor((iconSize - arrowWidth) * 0.5f);
Rect iconRect = new Rect(0, 0, iconSize, iconSize);
float iconOffset = Mathf.Floor((contentWidth - iconSize) * 0.5f);
Rect tipRect = new Rect(0, 0, arrowWidth, arrowLength);
int tipAngle = 0;
Vector2 tipTranslate = Vector2.zero;
bool tipVisible = true;
switch (alignment)
{
case SpriteAlignment.TopCenter:
iconRect.x = iconOffset;
iconRect.y = 0;
tipRect.x = iconOffset + arrowOffset;
tipRect.y = iconRect.height;
tipTranslate = new Vector2(arrowWidth, arrowLength);
tipAngle = 180;
break;
case SpriteAlignment.LeftCenter:
iconRect.y = iconOffset;
tipRect.x = iconRect.width;
tipRect.y = iconOffset + arrowOffset;
tipTranslate = new Vector2(arrowLength, 0);
tipAngle = 90;
break;
case SpriteAlignment.RightCenter:
iconRect.y = iconOffset;
iconRect.x += arrowLength;
tipRect.y = iconOffset + arrowOffset;
tipTranslate = new Vector2(0, arrowWidth);
tipAngle = 270;
break;
case SpriteAlignment.BottomCenter:
iconRect.x = iconOffset;
iconRect.y = arrowLength;
tipRect.x = iconOffset + arrowOffset;
tipTranslate = new Vector2(0, 0);
tipAngle = 0;
break;
default:
tipVisible = false;
break;
}
if (tipAngle != m_CurrentTipAngle)
{
if (m_TipElement != null)
{
m_TipElement.transform.rotation = Quaternion.Euler(new Vector3(0, 0, tipAngle));
m_TipElement.transform.position = new Vector3(tipTranslate.x, tipTranslate.y, 0);
m_TipElement.style.transformOrigin = new TransformOrigin(0, 0, 0);
}
m_CurrentTipAngle = tipAngle;
}
if (m_IconElement != null)
m_IconElement.layout = iconRect;
if (m_TipElement != null)
{
m_TipElement.layout = tipRect;
if (m_TipElement.visible != tipVisible)
{
m_TipElement.visible = tipVisible;
}
}
if (m_TextElement != null)
{
if (m_TextElement.parent == this)
{
m_TextElement.style.position = Position.Absolute;
m_TextElement.style.left = iconRect.xMax;
m_TextElement.style.top = iconRect.y;
}
}
}
private void OnCustomStyleResolved(CustomStyleResolvedEvent e)
{
int dist = 0;
if (!m_DistanceIsInline && e.customStyle.TryGetValue(s_DistanceProperty, out dist))
m_Distance = dist;
}
}
}
| UnityCsReference/Modules/GraphViewEditor/IconBadge.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/IconBadge.cs",
"repo_id": "UnityCsReference",
"token_count": 8505
} | 381 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements.GraphView;
namespace UnityEditor.Experimental.GraphView
{
internal class Snapper
{
SnapService m_Service;
LineView m_LineView;
GraphView m_GraphView;
bool active { get { return m_Service != null ? m_Service.active : false; } }
public Snapper()
{
}
internal void BeginSnap(GraphView graphView)
{
if (m_Service == null)
{
m_Service = new SnapService();
}
if (m_LineView == null)
{
m_LineView = new LineView();
}
m_GraphView = graphView;
m_GraphView.Add(m_LineView);
m_LineView.layout = new Rect(0, 0, m_GraphView.layout.width, m_GraphView.layout.height);
var notSelectedElementRects = GetNotSelectedElementRectsInView();
m_Service.BeginSnap(notSelectedElementRects);
}
internal List<Rect> GetNotSelectedElementRectsInView()
{
List<Rect> notSelectedElementRects = new List<Rect>();
List<GraphElement> ignoreElements = new List<GraphElement>();
// If dragging a group we need to find all elements inside and disregard them
// For Groups they derive from Scope in which have containedElements.
// If we are dragging around a node that are inside a Group,
// the groups border might adjust and we don't want to snap to that.
// We also check if there are any GraphElement children of the selected graphelement
// And add them to the ignore list.
foreach (GraphElement ge in m_GraphView.selection.OfType<GraphElement>())
{
if (ge is Group)
{
Group group = ge as Group;
var grpElements = group.containedElements;
foreach (GraphElement element in grpElements)
{
ignoreElements.AddRange(element.Query<GraphElement>("", "graphElement").ToList());
}
}
else if (ge.GetContainingScope() != null)
{
ignoreElements.Add(ge.GetContainingScope());
}
else
{
ignoreElements.Add(ge);
}
ignoreElements.AddRange(ge.Query<GraphElement>("", "graphElement").ToList());
}
// Consider only the visible nodes.
Rect rectToFit = m_GraphView.layout;
// a copy is necessary because Add To selection might cause a SendElementToFront which will change the order.
List<ISelectable> checkOnlyInViewElements = new List<ISelectable>();
foreach (GraphElement element in m_GraphView.graphElements.ToList())
{
var localSelRect = m_GraphView.ChangeCoordinatesTo(element, rectToFit);
if (element.Overlaps(localSelRect))
{
checkOnlyInViewElements.Add(element);
}
}
foreach (GraphElement element in checkOnlyInViewElements)
{
if (!element.IsSelected(m_GraphView) && (element.capabilities & Capabilities.Snappable) != 0 && !(ignoreElements.Contains(element)))
{
Rect geomtryInContentViewContainerSpace = element.parent.ChangeCoordinatesTo(m_GraphView.contentViewContainer, element.GetPosition());
notSelectedElementRects.Add(geomtryInContentViewContainerSpace);
}
}
return notSelectedElementRects;
}
internal Rect GetSnappedRect(Rect sourceRect, float scale = 1.0f)
{
m_Service.UpdateSnapRects(GetNotSelectedElementRectsInView());
List<SnapResult> results;
Rect snappedRect = m_Service.GetSnappedRect(sourceRect, out results, scale);
m_LineView.lines.Clear();
foreach (SnapResult result in results)
{
m_LineView.lines.Add(result.indicatorLine);
}
m_LineView.MarkDirtyRepaint();
return snappedRect;
}
internal void EndSnap(GraphView graphView)
{
m_LineView.lines.Clear();
m_LineView.Clear();
m_LineView.RemoveFromHierarchy();
m_Service.EndSnap();
}
internal void ClearSnapLines()
{
m_LineView.lines.Clear();
m_LineView.MarkDirtyRepaint();
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Manipulators/Snapper.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/Snapper.cs",
"repo_id": "UnityCsReference",
"token_count": 2329
} | 382 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.Overlays;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Snap
{
sealed class GridSettingsWindow : OverlayPopupWindow
{
readonly SceneViewGrid.GridRenderAxis[] m_Axes =
{
SceneViewGrid.GridRenderAxis.X,
SceneViewGrid.GridRenderAxis.Y,
SceneViewGrid.GridRenderAxis.Z,
};
const string k_GridSettingsWindowUxmlPath = "UXML/GridAndSnap/GridSettings.uxml";
SceneView m_SceneView;
ButtonStripField m_GridPlane;
Slider m_GridOpacity;
protected override void OnEnable()
{
base.OnEnable();
var mainTemplate = EditorGUIUtility.Load(k_GridSettingsWindowUxmlPath) as VisualTreeAsset;
mainTemplate.CloneTree(rootVisualElement);
rootVisualElement.Q<TextElement>("PaneTitle").text = L10n.Tr("Grid Visual");
rootVisualElement.Q<Button>("PaneOption").clicked += PaneOptionMenu;
m_GridPlane = rootVisualElement.Q<ButtonStripField>("GridPlane");
foreach (var axis in m_Axes)
m_GridPlane.AddButton(axis.ToString());
m_GridPlane.label = L10n.Tr("Grid Plane");
m_GridPlane.RegisterValueChangedCallback((evt) =>
{
m_SceneView.sceneViewGrids.gridAxis = m_Axes[evt.newValue];
SceneView.RepaintAll();
});
m_GridOpacity = rootVisualElement.Q<Slider>("Opacity");
m_GridOpacity.label = L10n.Tr("Opacity");
m_GridOpacity.RegisterValueChangedCallback(evt =>
{
m_SceneView.sceneViewGrids.gridOpacity = evt.newValue;
SceneView.RepaintAll();
});
var toHandle = rootVisualElement.Q<Button>("ToHandle");
toHandle.text = L10n.Tr("To Handle");
toHandle.clicked += () =>
{
foreach (var view in SceneView.sceneViews)
((SceneView)view).sceneViewGrids.SetAllGridsPivot(Snapping.Snap(Tools.handlePosition, GridSettings.size));
SceneView.RepaintAll();
};
var toOrigin = rootVisualElement.Q<Button>("ToOrigin");
toOrigin.text = L10n.Tr("To Origin");
toOrigin.clicked += () =>
{
foreach (var view in SceneView.sceneViews)
((SceneView)view).sceneViewGrids.ResetPivot(SceneViewGrid.GridRenderAxis.All);
SceneView.RepaintAll();
};
}
void PaneOptionMenu()
{
GenericMenu menu = new GenericMenu();
menu.AddItem(EditorGUIUtility.TrTextContent("Reset"), false, ResetValues);
menu.ShowAsContext();
}
void ResetValues()
{
m_SceneView.sceneViewGrids.gridAxis = SceneViewGrid.defaultRenderAxis;
m_SceneView.sceneViewGrids.gridOpacity = SceneViewGrid.defaultGridOpacity;
Init(m_SceneView);
}
public void Init(SceneView sceneView)
{
m_SceneView = sceneView;
m_GridOpacity.SetValueWithoutNotify(m_SceneView.sceneViewGrids.gridOpacity);
SceneViewGrid grid = m_SceneView.sceneViewGrids;
grid.gridRenderAxisChanged += axis => { m_GridPlane.SetValueWithoutNotify((int)axis); };
m_GridPlane.SetValueWithoutNotify((int)grid.gridAxis);
}
}
}
| UnityCsReference/Modules/GridAndSnap/GridSettingsWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/GridAndSnap/GridSettingsWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 1700
} | 383 |
// Unity 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.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Hierarchy
{
enum NativeSparseArrayResizePolicy
{
ExactSize,
DoubleSize,
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct NativeSparseArray<TKey, TValue> : IDisposable
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
[StructLayout(LayoutKind.Sequential)]
readonly struct Pair
{
public readonly TKey Key;
public readonly TValue Value;
public Pair(in TKey key, in TValue value)
{
Key = key;
Value = value;
}
}
public delegate int KeyIndex(in TKey key);
public delegate bool KeyEqual(in TKey lhs, in TKey rhs);
Pair* m_Ptr;
int m_Capacity;
int m_Count;
readonly Allocator m_Allocator;
readonly Pair m_InitValue;
readonly KeyIndex m_KeyIndex;
readonly KeyEqual m_KeyEqual;
public bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Ptr != null;
}
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Capacity;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set => Allocate(value);
}
public int Count => m_Count;
public TValue this[in TKey key]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var index = m_KeyIndex(in key);
ThrowIfIndexOutOfRange(index);
ref var current = ref m_Ptr[index];
if (!m_KeyEqual(in current.Key, in key))
throw new KeyNotFoundException(key.ToString());
return current.Value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
var index = m_KeyIndex(in key);
ThrowIfIndexIsNegative(index);
EnsureCapacity(index + 1, NativeSparseArrayResizePolicy.ExactSize);
ref var current = ref m_Ptr[index];
if (m_KeyEqual(in current.Key, default))
m_Count++;
m_Ptr[index] = new Pair(in key, in value);
}
}
public NativeSparseArray(KeyIndex keyIndex, Allocator allocator)
{
m_Ptr = null;
m_Capacity = 0;
m_Count = 0;
m_Allocator = allocator;
m_InitValue = default;
m_KeyIndex = keyIndex;
m_KeyEqual = (in TKey lhs, in TKey rhs) => { return lhs.Equals(rhs); };
}
public NativeSparseArray(KeyIndex keyIndex, KeyEqual keyEqual, Allocator allocator)
{
m_Ptr = null;
m_Capacity = 0;
m_Count = 0;
m_Allocator = allocator;
m_InitValue = default;
m_KeyIndex = keyIndex;
m_KeyEqual = keyEqual;
}
public NativeSparseArray(in TValue initValue, KeyIndex keyIndex, Allocator allocator)
{
m_Ptr = null;
m_Capacity = 0;
m_Count = 0;
m_Allocator = allocator;
m_InitValue = new Pair(default, in initValue);
m_KeyIndex = keyIndex;
m_KeyEqual = (in TKey lhs, in TKey rhs) => { return lhs.Equals(rhs); };
}
public NativeSparseArray(in TValue initValue, KeyIndex keyIndex, KeyEqual keyEqual, Allocator allocator)
{
m_Ptr = null;
m_Capacity = 0;
m_Count = 0;
m_Allocator = allocator;
m_InitValue = new Pair(default, in initValue);
m_KeyIndex = keyIndex;
m_KeyEqual = keyEqual;
}
public void Dispose()
{
Deallocate();
}
public void Reserve(int capacity)
{
EnsureCapacity(capacity, NativeSparseArrayResizePolicy.ExactSize);
}
public bool ContainsKey(in TKey key)
{
var index = m_KeyIndex(in key);
ThrowIfIndexOutOfRange(index);
ref var current = ref m_Ptr[index];
return m_KeyEqual(in current.Key, in key);
}
public void Add(in TKey key, in TValue value, NativeSparseArrayResizePolicy policy = NativeSparseArrayResizePolicy.ExactSize)
{
var index = m_KeyIndex(in key);
ThrowIfIndexIsNegative(index);
EnsureCapacity(index + 1, policy);
ref var current = ref m_Ptr[index];
if (m_KeyEqual(in current.Key, in key))
throw new ArgumentException($"an element with the same key [{key}] already exists");
if (m_KeyEqual(in current.Key, default))
m_Count++;
m_Ptr[index] = new Pair(in key, in value);
}
public void AddNoResize(in TKey key, in TValue value)
{
var index = m_KeyIndex(in key);
ThrowIfIndexOutOfRange(index);
ref var current = ref m_Ptr[index];
if (m_KeyEqual(in current.Key, in key))
throw new ArgumentException($"an element with the same key [{key}] already exists");
if (m_KeyEqual(in current.Key, default))
m_Count++;
m_Ptr[index] = new Pair(in key, in value);
}
public bool TryAdd(in TKey key, in TValue value, NativeSparseArrayResizePolicy policy = NativeSparseArrayResizePolicy.ExactSize)
{
var index = m_KeyIndex(in key);
ThrowIfIndexIsNegative(index);
EnsureCapacity(index + 1, policy);
ref var current = ref m_Ptr[index];
if (m_KeyEqual(in current.Key, in key))
return false;
if (m_KeyEqual(in current.Key, default))
m_Count++;
m_Ptr[index] = new Pair(in key, in value);
return true;
}
public bool TryAddNoResize(in TKey key, in TValue value)
{
var index = m_KeyIndex(in key);
ThrowIfIndexOutOfRange(index);
ref var current = ref m_Ptr[index];
if (m_KeyEqual(in current.Key, in key))
return false;
if (m_KeyEqual(in current.Key, default))
m_Count++;
m_Ptr[index] = new Pair(in key, in value);
return true;
}
public bool TryGetValue(in TKey key, out TValue value)
{
var index = m_KeyIndex(in key);
ThrowIfIndexOutOfRange(index);
ref var current = ref m_Ptr[index];
if (m_KeyEqual(in current.Key, in key))
{
value = current.Value;
return true;
}
value = default;
return false;
}
public bool Remove(in TKey key)
{
var index = m_KeyIndex(in key);
ThrowIfIndexOutOfRange(index);
ref var current = ref m_Ptr[index];
if (!m_KeyEqual(in current.Key, in key))
return false;
m_Ptr[index] = m_InitValue;
m_Count--;
return true;
}
public void Clear()
{
if (m_Ptr != null)
{
fixed (void* initValuePtr = &m_InitValue)
{
UnsafeUtility.MemCpyReplicate(m_Ptr, initValuePtr, UnsafeUtility.SizeOf<Pair>(), m_Capacity);
}
}
m_Count = 0;
}
void Allocate(int capacity)
{
if (capacity < 0)
throw new ArgumentException($"capacity [{capacity}] cannot be negative");
var sizeOf = UnsafeUtility.SizeOf<Pair>();
var alignOf = UnsafeUtility.AlignOf<Pair>();
if (m_Ptr == null)
{
m_Ptr = (Pair*)UnsafeUtility.Malloc(capacity * sizeOf, alignOf, m_Allocator);
fixed (Pair* initValuePtr = &m_InitValue)
{
UnsafeUtility.MemCpyReplicate(m_Ptr, initValuePtr, sizeOf, capacity);
}
}
else
{
m_Ptr = (Pair*)Realloc(m_Ptr, capacity * sizeOf, alignOf, m_Allocator);
if (capacity > m_Capacity)
{
fixed (Pair* initValuePtr = &m_InitValue)
{
UnsafeUtility.MemCpyReplicate(m_Ptr + m_Capacity, initValuePtr, sizeOf, capacity - m_Capacity);
}
}
}
m_Capacity = capacity;
}
void Deallocate()
{
if (m_Ptr != null)
{
UnsafeUtility.Free(m_Ptr, m_Allocator);
m_Ptr = null;
}
m_Capacity = 0;
m_Count = 0;
}
void EnsureCapacity(int capacity, NativeSparseArrayResizePolicy policy)
{
if (capacity <= m_Capacity)
return;
switch (policy)
{
case NativeSparseArrayResizePolicy.ExactSize:
Allocate(capacity);
break;
case NativeSparseArrayResizePolicy.DoubleSize:
Allocate(Math.Max(capacity, m_Capacity * 2));
break;
default:
throw new NotImplementedException(policy.ToString());
}
}
void ThrowIfIndexIsNegative(int index)
{
if (index < 0)
throw new InvalidOperationException($"key index [{index}] cannot be negative");
}
void ThrowIfIndexOutOfRange(int index)
{
ThrowIfIndexIsNegative(index);
if (index >= m_Capacity)
throw new InvalidOperationException($"key index [{index}] is out of range [0, {m_Capacity}]");
}
static void* Realloc(void* ptr, long size, int alignment, Allocator allocator)
{
if (ptr == null)
return UnsafeUtility.Malloc(size, alignment, allocator);
var newPtr = UnsafeUtility.Malloc(size, alignment, allocator);
UnsafeUtility.MemCpy(newPtr, ptr, size);
UnsafeUtility.Free(ptr, allocator);
return newPtr;
}
}
}
| UnityCsReference/Modules/HierarchyCore/Managed/NativeSparseArray.cs/0 | {
"file_path": "UnityCsReference/Modules/HierarchyCore/Managed/NativeSparseArray.cs",
"repo_id": "UnityCsReference",
"token_count": 5649
} | 384 |
// Unity 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("Modules/IMGUI/Event.bindings.h"),
StaticAccessor("GUIEvent", StaticAccessorType.DoubleColon)]
partial class Event
{
[NativeProperty("type", false, TargetType.Field)] public extern EventType rawType { get; }
[NativeProperty("mousePosition", false, TargetType.Field)] public extern Vector2 mousePosition { get; set; }
[NativeProperty("delta", false, TargetType.Field)] public extern Vector2 delta { get; set; }
[NativeProperty("pointerType", false, TargetType.Field)] public extern PointerType pointerType { get; set; }
[NativeProperty("button", false, TargetType.Field)] public extern int button { get; set; }
[NativeProperty("modifiers", false, TargetType.Field)] public extern EventModifiers modifiers { get; set; }
[NativeProperty("pressure", false, TargetType.Field)] public extern float pressure { get; set; }
[NativeProperty("twist", false, TargetType.Field)] public extern float twist { get; set; }
[NativeProperty("tilt", false, TargetType.Field)] public extern Vector2 tilt { get; set; }
[NativeProperty("penStatus", false, TargetType.Field)] public extern PenStatus penStatus { get; set; }
[NativeProperty("clickCount", false, TargetType.Field)] public extern int clickCount { get; set; }
[NativeProperty("character", false, TargetType.Field)] public extern char character { get; set; }
[NativeProperty("keycode", false, TargetType.Field)] extern KeyCode Internal_keyCode { get; set; }
public KeyCode keyCode
{
get
{
var key = isMouse ? KeyCode.Mouse0 + button : Internal_keyCode;
if(isScrollWheel)
key = delta.y < 0 ? KeyCode.WheelUp : KeyCode.WheelDown;
return key;
}
set => Internal_keyCode = value;
}
[NativeProperty("displayIndex", false, TargetType.Field)] public extern int displayIndex { get; set; }
public extern EventType type
{
[FreeFunction("GUIEvent::GetType", HasExplicitThis = true)] get;
[FreeFunction("GUIEvent::SetType", HasExplicitThis = true)] set;
}
public extern string commandName
{
[FreeFunction("GUIEvent::GetCommandName", HasExplicitThis = true)] get;
[FreeFunction("GUIEvent::SetCommandName", HasExplicitThis = true)] set;
}
[NativeMethod("Use")]
private extern void Internal_Use();
[FreeFunction("GUIEvent::Internal_Create", IsThreadSafe = true)]
private static extern IntPtr Internal_Create(int displayIndex);
[FreeFunction("GUIEvent::Internal_Destroy", IsThreadSafe = true)]
private static extern void Internal_Destroy(IntPtr ptr);
[FreeFunction("GUIEvent::Internal_Copy", IsThreadSafe = true)]
private static extern IntPtr Internal_Copy(IntPtr otherPtr);
[FreeFunction("GUIEvent::GetTypeForControl", HasExplicitThis = true)]
public extern EventType GetTypeForControl(int controlID);
[VisibleToOtherModules("UnityEngine.UIElementsModule"),
FreeFunction("GUIEvent::CopyFromPtr", IsThreadSafe = true, HasExplicitThis = true)]
internal extern void CopyFromPtr(IntPtr ptr);
public static extern bool PopEvent([NotNull] Event outEvent);
internal static extern void QueueEvent([NotNull] Event outEvent);
[VisibleToOtherModules("UnityEngine.InputForUIModule")]
internal static extern void GetEventAtIndex(int index, [NotNull] Event outEvent);
public static extern int GetEventCount();
internal static extern void ClearEvents();
private static extern void Internal_SetNativeEvent(IntPtr ptr);
[RequiredByNativeCode]
internal static void Internal_MakeMasterEventCurrent(int displayIndex)
{
if (s_MasterEvent == null)
s_MasterEvent = new Event(displayIndex);
s_MasterEvent.displayIndex = displayIndex;
s_Current = s_MasterEvent;
Internal_SetNativeEvent(s_MasterEvent.m_Ptr);
}
[VisibleToOtherModules("UnityEngine.UIElementsModule", "UnityEngine.InputForUIModule")]
internal static extern int GetDoubleClickTime();
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(Event e) => e.m_Ptr;
}
}
}
| UnityCsReference/Modules/IMGUI/Event.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/IMGUI/Event.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1752
} | 385 |
// 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
{
// Utility functions for implementing and extending the GUILayout class.
[NativeHeader("Modules/IMGUI/GUILayoutUtility.bindings.h")]
partial class GUILayoutUtility
{
private static extern Rect Internal_GetWindowRect(int windowID);
private static extern void Internal_MoveWindow(int windowID, Rect r);
internal static extern Rect GetWindowsBounds();
}
}
| UnityCsReference/Modules/IMGUI/GUILayoutUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/IMGUI/GUILayoutUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 196
} | 386 |
// 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;
public bool isDuringTouchScroll;
public Vector2 touchScrollStartMousePosition;
public Vector2 touchScrollStartPosition;
public Vector2 velocity;
public float previousTimeSinceStartup;
[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;
}
}
}
| UnityCsReference/Modules/IMGUI/ScrollViewState.cs/0 | {
"file_path": "UnityCsReference/Modules/IMGUI/ScrollViewState.cs",
"repo_id": "UnityCsReference",
"token_count": 1587
} | 387 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.IntegerTime;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEngine.InputForUI
{
[VisibleToOtherModules("UnityEngine.UIElementsModule")]
internal struct NavigationEvent : IEventProperties
{
public enum Type
{
Move = 1,
Submit = 2,
Cancel = 3
}
/// <summary>
/// Move event direction.
/// </summary>
public enum Direction
{
/// <summary>
/// No specific direction.
/// </summary>
None = 0,
/// <summary>
/// Left.
/// </summary>
Left = 1,
/// <summary>
/// Up.
/// </summary>
Up = 2,
/// <summary>
/// Right.
/// </summary>
Right = 3,
/// <summary>
/// Down.
/// </summary>
Down = 4,
/// <summary>
/// Forwards, toward next element.
/// </summary>
Next = 5,
/// <summary>
/// Backwards, toward previous element.
/// </summary>
Previous = 6,
}
public Type type;
public Direction direction;
public bool shouldBeUsed;
public DiscreteTime timestamp { get; set; }
public EventSource eventSource { get; set; }
public uint playerId { get; set; }
public EventModifiers eventModifiers { get; set; }
public override string ToString()
{
return $"Navigation {type}" +
(type == Type.Move ? $" {direction}" : "") +
(eventSource != EventSource.Keyboard ? $" {eventSource}" : "");
}
/// <summary>
/// Given an input movement, determine the best Direction.
/// </summary>
/// <param name="vec">Input movement as a vector.</param>
/// <param name="deadZone">Dead zone.</param>
internal static Direction DetermineMoveDirection(Vector2 vec, float deadZone = 0.6f)
{
// if vector is too small... just return
if (vec.sqrMagnitude < deadZone * deadZone)
return Direction.None;
if (Mathf.Abs(vec.x) > Mathf.Abs(vec.y))
return vec.x > 0 ? Direction.Right : Direction.Left;
return vec.y > 0 ? Direction.Up : Direction.Down;
}
}
}
| UnityCsReference/Modules/InputForUI/Events/NavigationEvent.cs/0 | {
"file_path": "UnityCsReference/Modules/InputForUI/Events/NavigationEvent.cs",
"repo_id": "UnityCsReference",
"token_count": 1254
} | 388 |
// Unity 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.CodeAnalysis;
namespace UnityEditor.Licensing.UI.Data.Events.Base;
[Serializable]
class Notification
{
public NotificationType NotificationTypeAsEnum => Enum.TryParse<NotificationType>(
notificationType, true, out var targetType)
? targetType
: Events.NotificationType.Unknown;
public string message;
public string messageType;
public string notificationType;
public string sentDate;
public string title;
public override string ToString()
{
return $"[{notificationType}] {title}: {message}. Sent at: {sentDate}";
}
}
| UnityCsReference/Modules/Licensing/UI/Data/Events/Base/Notification.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/Data/Events/Base/Notification.cs",
"repo_id": "UnityCsReference",
"token_count": 255
} | 389 |
// Unity 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.UIElements;
namespace UnityEditor.Licensing.UI.Events.Buttons;
abstract class TemplateEventsButton : Button
{
Action m_AdditionalClickAction;
protected TemplateEventsButton(string labelText, Action additionalClickAction)
{
m_AdditionalClickAction = additionalClickAction;
text = labelText;
name = string.Empty;
foreach (var c in text)
{
if (!char.IsWhiteSpace(c))
{
name += c;
}
}
// For guidelines refer to:
// https://www.figma.com/file/GdibV2c1v5vP8kgBEraDgj/%E2%9D%96-Editor-Foundations-%E2%80%93%E2%80%93-Figma-Toolkit-(Community)?node-id=4159-111248&t=Uuszom0SMChZTRHQ-0
style.marginRight = 0;
style.marginLeft = 3;
clicked += OnClicked;
}
void OnClicked()
{
m_AdditionalClickAction?.Invoke();
Click();
}
protected abstract void Click();
}
| UnityCsReference/Modules/Licensing/UI/Events/Buttons/TemplateEventsButton.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/Events/Buttons/TemplateEventsButton.cs",
"repo_id": "UnityCsReference",
"token_count": 489
} | 390 |
// Unity 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.Licensing.UI.Data.Events;
using UnityEditor.Licensing.UI.Events.Buttons;
using UnityEditor.Licensing.UI.Events.Handlers;
using UnityEditor.Licensing.UI.Events.Text;
using UnityEditor.Licensing.UI.Helper;
using UnityEngine;
namespace UnityEditor.Licensing.UI.Events.Windows;
class LicenseOfflineValidityEndedWindowContents : TemplateLicenseEventWindowContents
{
LicenseExpiredNotification m_Notification;
public LicenseOfflineValidityEndedWindowContents(LicenseExpiredNotification notification, IEventsButtonFactory eventsButtonFactory, ILicenseLogger licenseLogger)
: base(eventsButtonFactory, licenseLogger)
{
m_Notification = notification;
OnEnable();
}
void OnEnable()
{
m_Description = LicenseExpiredHandler.BuildLicenseOfflineValidityEndedText(m_Notification);
m_LogTag = LicenseTrStrings.OfflineValidityEndedWindowTitle;
m_LogType = LogType.Error;
m_LogMessage = m_Description;
m_Buttons.Add(EventsButtonType.SaveAndQuit);
m_Buttons.Add(EventsButtonType.UpdateLicense);
CreateContents();
}
}
| UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseOfflineValidityEndedWindowContents.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseOfflineValidityEndedWindowContents.cs",
"repo_id": "UnityCsReference",
"token_count": 435
} | 391 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.Licensing.UI.Events;
using UnityEditor.Licensing.UI.Helper;
using UnityEngine.Internal;
using UnityEngine.Scripting;
namespace UnityEditor.Licensing.UI;
class LicenseManagedWrapper
{
static readonly ILicenseLogger k_LicenseLogger = new LicenseLogger();
static readonly INativeApiWrapper k_NativeApiWrapper = new NativeApiWrapper(k_LicenseLogger);
static readonly IModalWrapper k_ModalWrapper = new ModalWrapper();
// made it public for testing purposes
public static INotificationDispatcher notificationDispatcher =
new LicenseNotificationDispatcher(
new LicenseNotificationHandlerFactory(k_LicenseLogger, k_NativeApiWrapper, k_ModalWrapper),
k_LicenseLogger,
k_NativeApiWrapper);
[ExcludeFromDocs]
[RequiredByNativeCode]
public static void HandleNotification(string jsonNotification)
{
notificationDispatcher.Dispatch(jsonNotification);
}
}
| UnityCsReference/Modules/Licensing/UI/LicenseManagedWrapper.cs/0 | {
"file_path": "UnityCsReference/Modules/Licensing/UI/LicenseManagedWrapper.cs",
"repo_id": "UnityCsReference",
"token_count": 378
} | 392 |
// 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.Multiplayer.Internal;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using UnityEditor;
using System.Collections.Generic;
namespace UnityEditor.Multiplayer.Internal
{
[CustomEditor(typeof(MultiplayerRolesData), true)]
internal class MultiplayerRolesDataEditor : Editor
{
private SerializedProperty m_GameObjectRoleProperty;
private SerializedProperty m_ComponentsRoleProperty;
private readonly Dictionary<Component, SerializedProperty> m_ComponentRoleProperties = new();
public void OnEnable()
{
m_GameObjectRoleProperty = serializedObject.FindProperty("m_GameObjectRolesMask");
m_ComponentsRoleProperty = serializedObject.FindProperty("m_ComponentsRolesMasks");
var componentsCount = m_ComponentsRoleProperty.arraySize;
for (int i = 0; i < componentsCount; i++)
{
var componentRole = m_ComponentsRoleProperty.GetArrayElementAtIndex(i);
var componentProperty = componentRole.FindPropertyRelative("m_Object");
var roleProperty = componentRole.FindPropertyRelative("m_RolesMask");
if (componentProperty.objectReferenceValue is Component component)
{
m_ComponentRoleProperties.Add(component, roleProperty);
}
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
var gameObjectRole = (MultiplayerRoleFlags)m_GameObjectRoleProperty.intValue;
var newGameObjectRole = (MultiplayerRoleFlags)EditorGUILayout.EnumPopup("Game Object:", gameObjectRole);
if (gameObjectRole != newGameObjectRole)
{
m_GameObjectRoleProperty.intValue = (int)newGameObjectRole;
}
foreach (var kvp in m_ComponentRoleProperties)
{
var component = kvp.Key;
var role = (MultiplayerRoleFlags)kvp.Value.intValue;
var newRole = (MultiplayerRoleFlags)EditorGUILayout.EnumPopup($"{component.name}:", role);
if (role != newRole)
{
kvp.Value.intValue = (int)newRole;
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
| UnityCsReference/Modules/MultiplayerEditor/Managed/MultiplayerRolesDataEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/MultiplayerEditor/Managed/MultiplayerRolesDataEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1070
} | 393 |
// Unity 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 RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
namespace UnityEditor.PackageManager
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
[NativeAsStruct]
public class RepositoryInfo
{
[SerializeField]
[NativeName("type")]
private string m_Type;
[SerializeField]
[NativeName("url")]
private string m_Url;
[SerializeField]
[NativeName("revision")]
private string m_Revision;
[SerializeField]
[NativeName("path")]
private string m_Path;
internal RepositoryInfo() : this("", "", "", "") {}
internal RepositoryInfo(string type, string url, string revision, string path)
{
m_Type = type;
m_Url = url;
m_Revision = revision;
m_Path = path;
}
public string type => m_Type;
public string url => m_Url;
public string revision => m_Revision;
public string path => m_Path;
}
}
| UnityCsReference/Modules/PackageManager/Editor/Managed/RepositoryInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/RepositoryInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 540
} | 394 |
// Unity 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.PackageManager.Requests
{
/// <summary>
/// Tracks the state of an asynchronous Upm server operation
/// </summary>
public abstract partial class Request : ISerializationCallbackReceiver
{
internal const string ShimPackageType = "shim";
[NonSerialized]
private bool m_Serializing;
/// <summary>
/// Note: This field is there to workaround the serializer
/// that does not know how to handle null values
/// </summary>
[SerializeField]
private bool m_ErrorFetched;
[SerializeField]
private Error m_Error;
[SerializeField]
private NativeStatusCode m_Status = NativeStatusCode.NotFound;
[SerializeField]
private long m_Id;
internal NativeStatusCode NativeStatus
{
get
{
if (!m_Status.IsCompleted())
{
m_Status = GetOperationStatus(Id);
}
return m_Status;
}
}
internal long Id
{
get
{
return m_Id;
}
}
/// <summary>
/// Gets the status of the operation
/// </summary>
public StatusCode Status
{
get
{
FetchNativeData();
return NativeStatus.ConvertToManaged();
}
}
/// <summary>
/// Gets whether the operation is completed or not
/// </summary>
public bool IsCompleted
{
get
{
FetchNativeData();
return NativeStatus.IsCompleted();
}
}
/// <summary>
/// Gets the error associated to this operation
/// </summary>
public Error Error
{
get
{
FetchNativeData();
return m_ErrorFetched ? m_Error : null;
}
}
private void FetchError()
{
// We assume the request is empty when the Id is 0 and skip error fetching.
// This happens during the serialization process as empty instances are created
// in place of null references.
if (Id == 0 || m_ErrorFetched || NativeStatus.ConvertToManaged() != StatusCode.Failure)
{
return;
}
m_ErrorFetched = true;
m_Error = GetOperationError(Id);
if (m_Error == null)
{
if (NativeStatus == NativeStatusCode.NotFound)
{
m_Error = new Error(NativeErrorCode.NotFound, "Operation not found");
}
else
{
m_Error = new Error(NativeErrorCode.Unknown, "Unknown error");
}
}
}
protected virtual void FetchNativeData()
{
FetchError();
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
m_Serializing = true;
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
m_Serializing = false;
}
~Request()
{
if (!m_Serializing)
{
// This can be called when the request is not longer referenced (garbage-collected)
// or during Domain Reload. In the latter case, don't destroy the native request.
ReleaseCompletedOperation(Id);
}
}
/// <summary>
/// Constructor to support serialization. Internal to prevent
/// API consumers to extend the class.
/// </summary>
internal Request()
{
}
internal Request(long operationId, NativeStatusCode initialStatus)
{
m_Id = operationId;
m_Status = initialStatus;
Debug.AssertFormat(m_Status == NativeStatusCode.Error ? m_Id == 0 : m_Id > 0, "Invalid operation id [status: {0}, id: {1}]", m_Status, m_Id);
}
}
/// <summary>
/// Tracks the state of an asynchronous Upm server operation that returns a non-empty response
/// </summary>
public abstract class Request<T> : Request
{
/// <summary>
/// Note: This field is there to workaround the serializer
/// that does not know how to handle null values
/// </summary>
[SerializeField]
private bool m_ResultFetched = false;
[SerializeField]
private T m_Result = default(T);
protected abstract T GetResult();
private void FetchResult()
{
if (m_ResultFetched || NativeStatus.ConvertToManaged() != StatusCode.Success)
{
return;
}
m_ResultFetched = true;
m_Result = GetResult();
}
protected sealed override void FetchNativeData()
{
FetchResult();
base.FetchNativeData();
}
/// <summary>
/// Gets the result of the operation
/// </summary>
public T Result
{
get
{
FetchNativeData();
return m_ResultFetched ? m_Result : default(T);
}
}
/// <summary>
/// Constructor to support serialization. Internal to prevent
/// API consumers to extend the class.
/// </summary>
internal Request()
: base()
{
}
internal Request(long operationId, NativeStatusCode initialStatus)
: base(operationId, initialStatus)
{
}
}
}
| UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/Request.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/Request.cs",
"repo_id": "UnityCsReference",
"token_count": 2871
} | 395 |
// Unity 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;
namespace UnityEditor.PackageManager.UnityLifecycle
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[RequiredByNativeCode]
[NativeAsStruct]
internal class UnityLifecycleInfo
{
[SerializeField]
[NativeName("version")]
private string m_Version;
[SerializeField]
[NativeName("nextVersion")]
private string m_NextVersion;
[SerializeField]
[NativeName("recommendedVersion")]
private string m_RecommendedVersion;
[SerializeField]
[NativeName("isDeprecated")]
private bool m_IsDeprecated;
[SerializeField]
[NativeName("deprecationMessage")]
private string m_DeprecationMessage;
public string version => m_Version;
public string nextVersion => m_NextVersion;
public string recommendedVersion => m_RecommendedVersion;
public bool isDeprecated => m_IsDeprecated;
public string deprecationMessage => m_DeprecationMessage;
internal UnityLifecycleInfo() : this("", "", "", false, "") {}
internal UnityLifecycleInfo(string version, string nextVersion, string recommendedVersion, bool isDeprecated, string deprecationMessage)
{
m_Version = version;
m_NextVersion = nextVersion;
m_RecommendedVersion = recommendedVersion;
m_IsDeprecated = isDeprecated;
m_DeprecationMessage = deprecationMessage ?? "";
}
}
}
| UnityCsReference/Modules/PackageManager/Editor/Managed/UnityLifecycleInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/UnityLifecycleInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 668
} | 396 |
// 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.UI
{
internal interface IWindow
{
PackageSelectionArgs activeSelection { get; }
IMenu addMenu { get; }
IMenu advancedMenu { get; }
void Select(string identifier);
IDetailsExtension AddDetailsExtension();
IPackageActionMenu AddPackageActionMenu();
IPackageActionButton AddPackageActionButton();
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 198
} | 397 |
// Unity 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.RegularExpressions;
using UnityEngine.Analytics;
namespace UnityEditor.PackageManager.UI.Internal
{
[AnalyticInfo(eventName: k_EventName, vendorKey: k_VendorKey)]
internal class PackageManagerWindowAnalytics : IAnalytic
{
private const string k_EventName = "packageManagerWindowUserAction";
private const string k_VendorKey = "unity.package-manager-ui";
[Serializable]
internal class Data : IAnalytic.IData
{
public string action;
public string package_id;
public string[] package_ids;
public string search_text;
public string filter_name;
public string details_tab;
public bool window_docked;
public bool dependencies_visible;
public bool preview_visible;
public string package_tag;
public string[] package_tags;
}
private Data m_Data;
private PackageManagerWindowAnalytics(string action, string packageId, IEnumerable<string> packageIds, string packageTag, IEnumerable<string> packageTags)
{
var servicesContainer = ServicesContainer.instance;
// remove sensitive part of the id: file path or url is not tracked
if (!string.IsNullOrEmpty(packageId))
packageId = Regex.Replace(packageId, "(?<package>[^@]+)@(?<protocol>[^:]+):.+", "${package}@${protocol}");
var packageManagerPrefs = servicesContainer.Resolve<IPackageManagerPrefs>();
var pageManager = servicesContainer.Resolve<IPageManager>();
var activePage = pageManager.activePage;
var settingsProxy = servicesContainer.Resolve<IProjectSettingsProxy>();
m_Data = new Data
{
action = action,
package_id = packageId ?? string.Empty,
package_tag = packageTag ?? string.Empty,
package_ids = packageIds?.ToArray() ?? new string[0],
package_tags = packageTags?.ToArray() ?? new string[0],
search_text = activePage.searchText,
filter_name = activePage.id,
details_tab = packageManagerPrefs.selectedPackageDetailsTabIdentifier ?? string.Empty,
window_docked = PackageManagerWindow.instance?.docked ?? false,
// packages installed as dependency are always visible
// we keep the dependencies_visible to not break the analytics
dependencies_visible = true,
preview_visible = settingsProxy.enablePreReleasePackages
};
}
public bool TryGatherData(out IAnalytic.IData data, out Exception error)
{
error = null;
data = m_Data;
return data != null;
}
// Our current analytics backend expects package_id to match product id for legacy asset store packages.
// Hence we are doing the special handling here. If we want to change this in the future, we need to also make changes in the backend accordingly.
private static string GetAnalyticsPackageId(IPackageVersion version)
{
return version?.HasTag(PackageTag.LegacyFormat) == true ? version.package.uniqueId : version?.uniqueId;
}
public static void SendEvent(string action, IPackageVersion version)
{
SendEvent(action, GetAnalyticsPackageId(version), packageTag: version?.GetAnalyticsTags());
}
public static void SendEvent(string action, IEnumerable<IPackageVersion> versions)
{
SendEvent(action, packageIds: versions?.Select(GetAnalyticsPackageId), packageTags: versions?.Select(v => v.GetAnalyticsTags()));
}
public static void SendEvent(string action, string packageId = null, IEnumerable<string> packageIds = null, string packageTag = null, IEnumerable<string> packageTags = null)
{
var editorAnalyticsProxy = ServicesContainer.instance.Resolve<IEditorAnalyticsProxy>();
editorAnalyticsProxy.SendAnalytic(new PackageManagerWindowAnalytics(action, packageId, packageIds, packageTag, packageTags));
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerWindowAnalytics.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerWindowAnalytics.cs",
"repo_id": "UnityCsReference",
"token_count": 1738
} | 398 |
// Unity 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;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class AssetStorePurchaseInfo
{
public long productId;
public string purchasedTime;
public string displayName;
public List<string> tags;
public bool isHidden;
public bool Equals(AssetStorePurchaseInfo other)
{
return other != null &&
other.productId == productId &&
other.purchasedTime == purchasedTime &&
other.displayName == displayName &&
other.isHidden == isHidden &&
other.tags?.Count == tags?.Count &&
other.tags?.SequenceEqual(tags) != false;
}
}
internal partial class JsonParser
{
public AssetStorePurchaseInfo ParsePurchaseInfo(IDictionary<string, object> rawInfo)
{
if (rawInfo?.Any() != true)
return null;
try
{
return new AssetStorePurchaseInfo
{
productId = (long)rawInfo["packageId"],
purchasedTime = rawInfo.GetString("grantTime"),
displayName = rawInfo.GetString("displayName"),
tags = rawInfo.GetList<string>("tagging")?.ToList(),
isHidden = rawInfo.Get("isHidden", false)
};
}
catch (Exception)
{
return null;
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePurchaseInfo.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePurchaseInfo.cs",
"repo_id": "UnityCsReference",
"token_count": 821
} | 399 |
// Unity 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.PackageManager.UI.Internal
{
[Serializable]
internal class Package : IPackage, ISerializationCallbackReceiver
{
[SerializeField]
private string m_Name;
public string name => m_Name;
[SerializeField]
private Product m_Product;
public IProduct product => m_Product?.id > 0 ? m_Product : null;
[SerializeField]
private string m_UniqueId;
public string uniqueId => m_UniqueId;
[SerializeField]
private bool m_IsDiscoverable;
public bool isDiscoverable => m_IsDiscoverable || versions.installed?.isDirectDependency == true;
public string displayName => !string.IsNullOrEmpty(m_Product?.displayName) ? m_Product?.displayName : versions.FirstOrDefault()?.displayName ?? string.Empty;
public PackageState state
{
get
{
if (progress != PackageProgress.None)
return PackageState.InProgress;
var numErrors = 0;
var numWarnings = 0;
foreach (var error in GetAllErrorsInPackageAndVersions())
{
// We don't count HiddenFromUI errors when calculating the package state because the state is tightly coupled to the UI.
// The icon to display in the package list is directly mapped to the package state using a USS class name.
// For that reason, we need to disregard HiddenFromUI errors to avoid showing the error or warning icons.
if (error.HasAttribute(UIError.Attribute.HiddenFromUI))
continue;
++numErrors;
if (error.HasAttribute(UIError.Attribute.Warning))
++numWarnings;
else if (!error.HasAttribute(UIError.Attribute.Clearable))
return PackageState.Error;
}
var primary = versions.primary;
if (primary.HasTag(PackageTag.Deprecated) && primary.isInstalled)
return PackageState.Error;
if (numErrors > 0 && numWarnings == numErrors || isDeprecated)
return PackageState.Warning;
var latestKeyVersion = versions.key.LastOrDefault();
if (primary.HasTag(PackageTag.Custom))
return PackageState.InDevelopment;
if (primary.isInstalled && !primary.isDirectDependency)
return PackageState.InstalledAsDependency;
var recommended = versions.recommended;
if (recommended != null && primary != recommended && ((primary.isInstalled && primary != latestKeyVersion) || primary.HasTag(PackageTag.LegacyFormat)) && !primary.HasTag(PackageTag.Local))
return PackageState.UpdateAvailable;
if (primary.importedAssets?.Any() == true)
return PackageState.Imported;
if (versions.importAvailable != null)
return PackageState.ImportAvailable;
if (versions.installed != null)
return PackageState.Installed;
if (primary.HasTag(PackageTag.LegacyFormat))
return PackageState.DownloadAvailable;
return PackageState.None;
}
}
[SerializeField]
private PackageProgress m_Progress;
public virtual PackageProgress progress => m_Progress;
[SerializeField]
private string m_DeprecationMessage;
public virtual string deprecationMessage => m_DeprecationMessage;
[SerializeField]
private bool m_IsDeprecated;
public virtual bool isDeprecated => m_IsDeprecated;
// errors on the package level (not just about a particular version)
[SerializeField]
private List<UIError> m_Errors;
public IEnumerable<UIError> errors => m_Errors;
private IEnumerable<UIError> GetAllErrorsInPackageAndVersions()
{
if (m_Errors != null)
foreach (var error in m_Errors)
yield return error;
foreach (var version in versions.Where(v => v.errors != null))
foreach (var versionError in version.errors)
yield return versionError;
}
public bool hasEntitlements => versions.Any(v => v.HasTag(PackageTag.Unity) && v.hasEntitlements);
public bool hasEntitlementsError => versions.Any(v => v.hasEntitlementsError);
[SerializeReference]
private IVersionList m_VersionList;
public IVersionList versions => m_VersionList;
IEnumerable<UI.IPackageVersion> UI.IPackage.versions => versions;
private void LinkPackageAndVersions()
{
foreach (var version in versions)
version.package = this;
}
public void OnBeforeSerialize()
{
}
public void OnAfterDeserialize()
{
LinkPackageAndVersions();
}
private Package(string name, IVersionList versionList, Product product = null, bool isDiscoverable = true, bool isDeprecated = false, string deprecationMessage = null)
{
m_Name = name;
m_VersionList = versionList;
m_Product = product;
m_UniqueId = m_Product?.id > 0 ? product.id.ToString() : name;
m_IsDiscoverable = isDiscoverable;
m_Errors = new List<UIError>();
m_Progress = PackageProgress.None;
m_IsDeprecated = versionList.primary?.HasTag(PackageTag.InstalledFromPath) == false && isDeprecated;
m_DeprecationMessage = deprecationMessage;
LinkPackageAndVersions();
}
// We are making package factories inherit from a sub class of Package to make sure that we can keep all the package modifying code
// private and that only Packages themselves and factories can actually modify packages. This way there won't be any accidental
// package modifications that's not caught by the package change events.
internal class Factory : BaseService
{
public Package CreatePackage(string name, IVersionList versionList, Product product = null, bool isDiscoverable = true, bool isDeprecated = false, string deprecationMessage = null)
{
return new Package(name, versionList, product, isDiscoverable, isDeprecated, deprecationMessage);
}
public void AddError(Package package, UIError error)
{
package.m_Errors.Add(error);
}
public int ClearErrors(Package package, Predicate<UIError> match = null)
{
if (match != null)
return package.m_Errors.RemoveAll(match);
var numErrors = package.m_Errors.Count;
package.m_Errors.Clear();
return numErrors;
}
public void SetProgress(Package package, PackageProgress progress)
{
package.m_Progress = progress;
}
public override Type registrationType => null;
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/Package.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/Package.cs",
"repo_id": "UnityCsReference",
"token_count": 3244
} | 400 |
// Unity 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.PackageManager.UI.Internal
{
internal struct ListUpdateArgs
{
public IPage page;
public IEnumerable<IPackage> added;
public IEnumerable<IPackage> updated;
public IEnumerable<IPackage> removed;
public bool reorder;
}
internal struct VisualStateChangeArgs
{
public IPage page;
public IEnumerable<VisualState> visualStates;
}
internal struct PageSelectionChangeArgs
{
public IPage page;
public PageSelection selection;
public bool isExplicitUserSelection;
}
internal interface IPage
{
event Action<PageSelectionChangeArgs> onSelectionChanged;
// triggered when the state of the UI item is updated (expanded, hidden, see all versions toggled)
event Action<VisualStateChangeArgs> onVisualStateChange;
// triggered when packages are added/updated or removed
event Action<ListUpdateArgs> onListUpdate;
event Action<IPage> onListRebuild;
event Action<PageFilters> onFiltersChange;
event Action<string> onTrimmedSearchTextChanged;
event Action<IPage> onSupportedStatusFiltersChanged;
string id { get; }
string displayName { get; }
Icon icon { get; }
string searchText { get; set; }
string trimmedSearchText { get; }
PageFilters filters { get; }
PageCapability capability { get; }
IEnumerable<PageFilters.Status> supportedStatusFilters { get; }
IEnumerable<PageSortOption> supportedSortOptions { get; }
RefreshOptions refreshOptions { get; }
bool ShouldInclude(IPackage package);
bool isActivePage { get; }
// Called when a page got activated (when it became the current visible page)
void OnActivated();
// Called when a page got deactivated (when it went from the current page to the previous page)
void OnDeactivated();
// an ordered list of `packageUniqueIds`
IVisualStateList visualStates { get; }
// return true if filters are changed
bool ClearFilters(bool resetSortOptionToDefault = false);
// return true if filters are changed
bool UpdateFilters(PageFilters newFilters);
PageSelection GetSelection();
void OnPackagesChanged(PackagesChangeArgs args);
void OnEnable();
void OnDisable();
void LoadMore(long numberOfPackages);
void Load(string packageUniqueId);
void LoadExtraItems(IEnumerable<IPackage> packages);
bool SetNewSelection(IPackage package, IPackageVersion version = null, bool isExplicitUserSelection = false);
bool SetNewSelection(IEnumerable<PackageAndVersionIdPair> packageAndVersionIdPairs, bool isExplicitUserSelection = false);
void RemoveSelection(IEnumerable<PackageAndVersionIdPair> toRemove, bool isExplicitUserSelection = false);
bool ToggleSelection(string packageUniqueId, bool isExplicitUserSelection = false);
bool UpdateSelectionIfCurrentSelectionIsInvalid();
void TriggerOnSelectionChanged(bool isExplicitUserSelection = false);
bool IsGroupExpanded(string groupName);
void SetGroupExpanded(string groupName, bool value);
string GetGroupName(IPackage package);
void SetPackagesUserUnlockedState(IEnumerable<string> packageUniqueIds, bool unlocked);
void ResetUserUnlockedState();
bool GetDefaultLockState(IPackage package);
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IPage.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IPage.cs",
"repo_id": "UnityCsReference",
"token_count": 1327
} | 401 |
// 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.PackageManager.UI.Internal;
internal class PauseDownloadAction : PackageAction
{
private readonly IPackageOperationDispatcher m_OperationDispatcher;
private readonly IAssetStoreDownloadManager m_AssetStoreDownloadManager;
private readonly IApplicationProxy m_Application;
public PauseDownloadAction(IPackageOperationDispatcher operationDispatcher, IAssetStoreDownloadManager assetStoreDownloadManager, IApplicationProxy application)
{
m_OperationDispatcher = operationDispatcher;
m_AssetStoreDownloadManager = assetStoreDownloadManager;
m_Application = application;
}
public override Icon icon => Icon.Pause;
protected override bool TriggerActionImplementation(IPackageVersion version)
{
m_OperationDispatcher.PauseDownload(version.package);
PackageManagerWindowAnalytics.SendEvent("pauseDownload", version);
return true;
}
public override bool IsVisible(IPackageVersion version)
{
if (version?.HasTag(PackageTag.LegacyFormat) != true)
return false;
var operation = m_AssetStoreDownloadManager.GetDownloadOperation(version.package.product?.id);
// We only want to see two icons at the same time (cancel + resume OR cancel + pause)
// So we hide the pause button when the resume button is shown, that's why we check the ResumeRequested state
return operation?.state != DownloadState.ResumeRequested && (operation?.isInProgress == true || operation?.state == DownloadState.Pausing);
}
public override string GetTooltip(IPackageVersion version, bool isInProgress)
{
if (isInProgress)
return L10n.Tr("The pause request has been sent. Please wait for the download to pause.");
return string.Format(L10n.Tr("Click to pause the download of this {0}."), version.GetDescriptor());
}
public override string GetText(IPackageVersion version, bool isInProgress) => L10n.Tr("Pause");
public override bool IsInProgress(IPackageVersion version) => m_AssetStoreDownloadManager.GetDownloadOperation(version.package.product?.id).state == DownloadState.Pausing;
protected override IEnumerable<DisableCondition> GetAllTemporaryDisableConditions()
{
yield return new DisableIfCompiling(m_Application);
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/PauseDownloadAction.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/PauseDownloadAction.cs",
"repo_id": "UnityCsReference",
"token_count": 785
} | 402 |
// 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.UI.Internal
{
internal class PackageUpmChangelogLink : PackageLink
{
public PackageUpmChangelogLink(IPackageVersion version) : base(version)
{
}
public override bool isVisible => version != null && version.HasTag(PackageTag.UpmFormat) && !version.HasTag(PackageTag.Feature | PackageTag.BuiltIn);
public override bool isEnabled => !isEmpty;
public override ContextMenuAction[] contextMenuActions => new ContextMenuAction[] { ContextMenuAction.OpenInBrowser, ContextMenuAction.OpenLocally };
public override string tooltip
{
get
{
if (isEnabled)
return L10n.Tr("Right click to see viewing options: in browser or local.");
else if (version?.isInstalled != true && version?.package.product != null)
return L10n.Tr("Install to view changelog");
else
return L10n.Tr("Changelog unavailable");
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageLink/PackageUpmChangelogLink.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageLink/PackageUpmChangelogLink.cs",
"repo_id": "UnityCsReference",
"token_count": 490
} | 403 |
// Unity 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.PackageManager.UI.Internal
{
internal interface IPageRefreshHandler : IService
{
event Action onRefreshOperationStart;
event Action onRefreshOperationFinish;
event Action<UIError> onRefreshOperationError;
void Refresh(IPage page);
void Refresh(RefreshOptions options);
void CancelRefresh(RefreshOptions options);
bool IsRefreshInProgress(RefreshOptions options);
bool IsInitialFetchingDone(RefreshOptions options);
void SetRefreshTimestampSingleFlag(RefreshOptions option, long timestamp);
long GetRefreshTimestamp(RefreshOptions options);
void SetRefreshErrorSingleFlag(RefreshOptions option, UIError error);
UIError GetRefreshError(RefreshOptions options);
long GetRefreshTimestamp(IPage page);
UIError GetRefreshError(IPage page);
bool IsRefreshInProgress(IPage page);
bool IsInitialFetchingDone(IPage page);
}
[Serializable]
internal class PageRefreshHandler : BaseService<IPageRefreshHandler>, IPageRefreshHandler, ISerializationCallbackReceiver
{
public event Action onRefreshOperationStart = delegate { };
public event Action onRefreshOperationFinish = delegate { };
public event Action<UIError> onRefreshOperationError = delegate { };
private Dictionary<RefreshOptions, long> m_RefreshTimestamps = new();
private Dictionary<RefreshOptions, UIError> m_RefreshErrors = new();
[NonSerialized]
private List<IOperation> m_RefreshOperationsInProgress = new();
// array created to help serialize dictionaries
[SerializeField]
private RefreshOptions[] m_SerializedRefreshTimestampsKeys = Array.Empty<RefreshOptions>();
[SerializeField]
private long[] m_SerializedRefreshTimestampsValues = Array.Empty<long>();
[SerializeField]
private RefreshOptions[] m_SerializedRefreshErrorsKeys = Array.Empty<RefreshOptions>();
[SerializeField]
private UIError[] m_SerializedRefreshErrorsValues = Array.Empty<UIError>();
private readonly IApplicationProxy m_Application;
private readonly IUpmClient m_UpmClient;
private readonly IUpmRegistryClient m_UpmRegistryClient;
private readonly IPageManager m_PageManager;
private readonly IUnityConnectProxy m_UnityConnect;
private readonly IAssetDatabaseProxy m_AssetDatabase;
private readonly IPackageManagerPrefs m_PackageManagerPrefs;
private readonly IAssetStoreClient m_AssetStoreClient;
public PageRefreshHandler(IPageManager pageManager,
IApplicationProxy application,
IUnityConnectProxy unityConnect,
IAssetDatabaseProxy assetDatabase,
IPackageManagerPrefs packageManagerPrefs,
IUpmClient upmClient,
IUpmRegistryClient upmRegistryClient,
IAssetStoreClient assetStoreClient)
{
m_PageManager = RegisterDependency(pageManager);
m_Application = RegisterDependency(application);
m_UpmClient = RegisterDependency(upmClient);
m_UpmRegistryClient = RegisterDependency(upmRegistryClient);
m_UnityConnect = RegisterDependency(unityConnect);
m_AssetDatabase = RegisterDependency(assetDatabase);
m_PackageManagerPrefs = RegisterDependency(packageManagerPrefs);
m_AssetStoreClient = RegisterDependency(assetStoreClient);
}
public void OnBeforeSerialize()
{
m_SerializedRefreshTimestampsKeys = m_RefreshTimestamps.Keys.ToArray();
m_SerializedRefreshTimestampsValues = m_RefreshTimestamps.Values.ToArray();
m_SerializedRefreshErrorsKeys = m_RefreshErrors.Keys.ToArray();
m_SerializedRefreshErrorsValues = m_RefreshErrors.Values.ToArray();
}
public void OnAfterDeserialize()
{
for (var i = 0; i < m_SerializedRefreshTimestampsKeys.Length; i++)
m_RefreshTimestamps[m_SerializedRefreshTimestampsKeys[i]] = m_SerializedRefreshTimestampsValues[i];
for (var i = 0; i < m_SerializedRefreshErrorsKeys.Length; i++)
m_RefreshErrors[m_SerializedRefreshErrorsKeys[i]] = m_SerializedRefreshErrorsValues[i];
}
private void OnActivePageChanged(IPage page)
{
if (!IsInitialFetchingDone(page))
Refresh(page);
}
// The virtual keyword is needed for unit tests
public virtual void Refresh(IPage page)
{
Refresh(page.refreshOptions);
}
// The virtual keyword is needed for unit tests
public virtual void Refresh(RefreshOptions options)
{
if (options.Contains(RefreshOptions.UpmSearch))
{
m_UpmClient.SearchAll();
// Since the SearchAll online call now might return error and an empty list, we want to trigger a `SearchOffline` call if
// we detect that SearchOffline has not been called before. That way we will have some offline result to show to the user instead of nothing
if (GetRefreshTimestampSingleFlag(RefreshOptions.UpmSearchOffline) == 0)
options |= RefreshOptions.UpmSearchOffline;
}
if (options.Contains(RefreshOptions.UpmSearchOffline))
m_UpmClient.SearchAll(true);
if (options.Contains(RefreshOptions.UpmList))
{
m_UpmClient.List();
// Do the same logic for the List operations as the Search operations
if (GetRefreshTimestampSingleFlag(RefreshOptions.UpmListOffline) == 0)
options |= RefreshOptions.UpmListOffline;
}
if (options.Contains(RefreshOptions.UpmListOffline))
m_UpmClient.List(true);
if (options.Contains(RefreshOptions.LocalInfo))
RefreshLocalInfos();
if (options.Contains(RefreshOptions.Purchased))
{
var page = m_PageManager.GetPage(MyAssetsPage.k_Id);
var numItems = Math.Max((int)page.visualStates.countLoaded, m_PackageManagerPrefs.numItemsPerPage ?? PackageManagerPrefs.k_DefaultPageSize);
var queryArgs = new PurchasesQueryArgs(0, numItems, page.trimmedSearchText, page.filters);
m_AssetStoreClient.ListPurchases(queryArgs);
}
if (options.Contains(RefreshOptions.ImportedAssets))
RefreshImportedAssets();
}
private void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
// if a full scan was never done, it needs to be done now
// otherwise, we want to avoid doing a full scan on every OnPostprocessAllAssets trigger for performance, so
// if a full scan was done already, just modify the cached assets according to the parameters passed by the event
if (RefreshImportedAssets())
return;
SetRefreshTimestampSingleFlag(RefreshOptions.ImportedAssets, DateTime.Now.Ticks);
m_AssetStoreClient.OnPostProcessAllAssets(importedAssets, deletedAssets, movedAssets, movedFromAssetPaths);
}
// returns true if a full scan was done, false if not
private bool RefreshImportedAssets()
{
if (GetRefreshTimestampSingleFlag(RefreshOptions.ImportedAssets) != 0)
return false;
// We set the timestamp before the actual operation because the results are retrieved synchronously, if we set the timestamp after
// we will encounter an issue where the results are back but the UI still thinks the refresh is in progress
SetRefreshTimestampSingleFlag(RefreshOptions.ImportedAssets, DateTime.Now.Ticks);
m_AssetStoreClient.RefreshImportedAssets();
return true;
}
private void RefreshLocalInfos()
{
if (GetRefreshTimestampSingleFlag(RefreshOptions.LocalInfo) != 0)
return;
// We set the timestamp before the actual operation because the results are retrieved synchronously, if we set the timestamp after
// we will encounter an issue where the results are back but the UI still thinks the refresh is in progress
SetRefreshTimestampSingleFlag(RefreshOptions.LocalInfo, DateTime.Now.Ticks);
m_AssetStoreClient.RefreshLocal();
}
public void CancelRefresh(RefreshOptions options)
{
if (options.Contains(RefreshOptions.Purchased))
m_AssetStoreClient.CancelListPurchases();
}
private void OnUserLoginStateChange(bool userInfoReady, bool loggedIn)
{
if (!loggedIn)
{
// We also want to clear the refresh time stamp here so that the next time users visit the Asset Store page,
// we'll call refresh properly
m_RefreshTimestamps.Remove(RefreshOptions.Purchased);
m_RefreshErrors.Remove(RefreshOptions.Purchased);
}
else if (m_PageManager.activePage.refreshOptions.Contains(RefreshOptions.Purchased) &&
m_Application.isInternetReachable &&
!m_Application.isCompiling &&
!IsRefreshInProgress(RefreshOptions.Purchased))
Refresh(RefreshOptions.Purchased);
}
public override void OnEnable()
{
m_AssetDatabase.onPostprocessAllAssets += OnPostprocessAllAssets;
m_UpmClient.onListOperation += OnRefreshOperation;
m_UpmClient.onSearchAllOperation += OnRefreshOperation;
m_AssetStoreClient.onListOperation += OnRefreshOperation;
m_UpmRegistryClient.onRegistriesModified += OnRegistriesModified;
m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange;
m_PageManager.onActivePageChanged += OnActivePageChanged;
}
public override void OnDisable()
{
m_AssetDatabase.onPostprocessAllAssets -= OnPostprocessAllAssets;
m_UpmClient.onListOperation -= OnRefreshOperation;
m_UpmClient.onSearchAllOperation -= OnRefreshOperation;
m_AssetStoreClient.onListOperation -= OnRefreshOperation;
m_UpmRegistryClient.onRegistriesModified -= OnRegistriesModified;
m_UnityConnect.onUserLoginStateChange -= OnUserLoginStateChange;
m_PageManager.onActivePageChanged -= OnActivePageChanged;
}
private void OnRegistriesModified()
{
Refresh(RefreshOptions.UpmSearch);
}
private void OnRefreshOperation(IOperation operation)
{
m_RefreshOperationsInProgress.Add(operation);
operation.onOperationSuccess += OnRefreshOperationSuccess;
operation.onOperationFinalized += OnRefreshOperationFinalized;
operation.onOperationError += OnRefreshOperationError;
if (m_RefreshOperationsInProgress.Count > 1)
return;
onRefreshOperationStart?.Invoke();
}
private void OnRefreshOperationSuccess(IOperation operation)
{
SetRefreshTimestampSingleFlag(operation.refreshOptions, operation.timestamp);
switch (operation.refreshOptions)
{
// when an online operation successfully returns with a timestamp newer than the offline timestamp, we update the offline timestamp as well
// since we merge the online & offline result in the PackageDatabase and it's the newer ones that are being shown
case RefreshOptions.UpmSearch when GetRefreshTimestampSingleFlag(RefreshOptions.UpmSearchOffline) < operation.timestamp:
SetRefreshTimestampSingleFlag(RefreshOptions.UpmSearchOffline, operation.timestamp);
break;
case RefreshOptions.UpmList when GetRefreshTimestampSingleFlag(RefreshOptions.UpmListOffline) < operation.timestamp:
SetRefreshTimestampSingleFlag(RefreshOptions.UpmListOffline, operation.timestamp);
break;
}
m_RefreshErrors.Remove(operation.refreshOptions);
}
private void OnRefreshOperationError(IOperation operation, UIError error)
{
SetRefreshErrorSingleFlag(operation.refreshOptions, error);
onRefreshOperationError?.Invoke(error);
}
private void OnRefreshOperationFinalized(IOperation operation)
{
m_RefreshOperationsInProgress.Remove(operation);
if (m_RefreshOperationsInProgress.Any())
return;
onRefreshOperationFinish?.Invoke();
}
// The virtual keyword is needed for unit tests
public virtual bool IsRefreshInProgress(RefreshOptions options)
{
return m_RefreshOperationsInProgress.Any(i => options.Contains(i.refreshOptions));
}
// The virtual keyword is needed for unit tests
public virtual bool IsInitialFetchingDone(RefreshOptions options)
{
return options.Split().All(o => GetRefreshTimestampSingleFlag(o) != 0 || m_RefreshErrors.ContainsKey(o));
}
public void SetRefreshTimestampSingleFlag(RefreshOptions option, long timestamp)
{
m_RefreshTimestamps[option] = timestamp;
}
// The virtual keyword is needed for unit tests
public virtual long GetRefreshTimestamp(RefreshOptions options)
{
return options == RefreshOptions.None ? 0 : options.Split().Min(GetRefreshTimestampSingleFlag);
}
// This function only work with single flag (e.g. `RefreshOption.UpmList`) refresh option.
// If a refresh option with multiple flags (e.g. `RefreshOption.UpmList | RefreshOption.UpmSearch`)
// is passed, the result won't be correct.
private long GetRefreshTimestampSingleFlag(RefreshOptions option)
{
return m_RefreshTimestamps.TryGetValue(option, out var value) ? value : 0;
}
public void SetRefreshErrorSingleFlag(RefreshOptions option, UIError error)
{
m_RefreshErrors[option] = error;
}
// The virtual keyword is needed for unit tests
public virtual UIError GetRefreshError(RefreshOptions options)
{
return options.Split()
.Select(o => m_RefreshErrors.TryGetValue(o, out var error) ? error : null)
.FirstOrDefault(e => e != null);
}
public long GetRefreshTimestamp(IPage page)
{
return GetRefreshTimestamp(page.refreshOptions);
}
public UIError GetRefreshError(IPage page)
{
return GetRefreshError(page.refreshOptions);
}
public bool IsRefreshInProgress(IPage page)
{
return IsRefreshInProgress(page.refreshOptions);
}
// The virtual keyword is needed for unit tests
public virtual bool IsInitialFetchingDone(IPage page)
{
return IsInitialFetchingDone(page.refreshOptions);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageRefreshHandler.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageRefreshHandler.cs",
"repo_id": "UnityCsReference",
"token_count": 6395
} | 404 |
// Unity 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.PackageManager.UI.Internal
{
[FilePath("ProjectSettings/PackageManagerSettings.asset", FilePathAttribute.Location.ProjectFolder)]
internal class PackageManagerProjectSettings : ScriptableSingleton<PackageManagerProjectSettings>
{
public event Action<bool> onEnablePreReleasePackagesChanged = delegate {};
public event Action<bool> onAdvancedSettingsFoldoutChanged = delegate {};
public event Action<bool> onScopedRegistriesSettingsFoldoutChanged = delegate {};
public event Action<bool> onSeeAllVersionsChanged = delegate {};
public event Action<long> onLoadAssetsChanged = delegate {};
public event Action onInitializationFinished = delegate {};
[SerializeField]
private bool m_EnablePreReleasePackages;
public bool enablePreReleasePackages
{
get { return m_EnablePreReleasePackages; }
set
{
if (value != m_EnablePreReleasePackages)
{
m_EnablePreReleasePackages = value;
onEnablePreReleasePackagesChanged?.Invoke(m_EnablePreReleasePackages);
}
}
}
[SerializeField]
private bool m_AdvancedSettingsExpanded = true;
public virtual bool advancedSettingsExpanded
{
get { return m_AdvancedSettingsExpanded; }
set
{
if (value != m_AdvancedSettingsExpanded)
{
m_AdvancedSettingsExpanded = value;
onAdvancedSettingsFoldoutChanged?.Invoke(m_AdvancedSettingsExpanded);
}
}
}
[SerializeField]
private bool m_ScopedRegistriesSettingsExpanded = true;
public virtual bool scopedRegistriesSettingsExpanded
{
get { return m_ScopedRegistriesSettingsExpanded; }
set
{
if (value != m_ScopedRegistriesSettingsExpanded)
{
m_ScopedRegistriesSettingsExpanded = value;
onScopedRegistriesSettingsFoldoutChanged?.Invoke(m_ScopedRegistriesSettingsExpanded);
}
}
}
[SerializeField]
private bool m_SeeAllPackageVersions;
public virtual bool seeAllPackageVersions
{
get { return m_SeeAllPackageVersions; }
set
{
if (value != m_SeeAllPackageVersions)
{
m_SeeAllPackageVersions = value;
onSeeAllVersionsChanged?.Invoke(m_SeeAllPackageVersions);
}
}
}
[SerializeField]
private bool m_DismissPreviewPackagesInUse;
public virtual bool dismissPreviewPackagesInUse
{
get { return m_DismissPreviewPackagesInUse; }
set
{
if (value != m_DismissPreviewPackagesInUse)
m_DismissPreviewPackagesInUse = value;
}
}
[SerializeField]
public bool oneTimeWarningShown;
[SerializeField]
public bool oneTimeDeprecatedPopUpShown;
[SerializeField]
private List<RegistryInfo> m_Registries = new List<RegistryInfo>();
public IList<RegistryInfo> registries => m_Registries;
public IEnumerable<RegistryInfo> scopedRegistries => m_Registries.Skip(1);
// `m_UserSelectedRegistryName` and `m_UserAddingNewScopedRegistry` only reflect what scoped registry the user selected
// by interacting with the settings window. registryInfoDraft.original is what's actually selected and displayed to the user
// When the user opens the settings window for the first time, `m_UserAddingNewScopedRegistry` would be false and
// `m_UserSelectedRegistryName` is empty, but registryInfoDraft.original would be the first scoped registry since that's the default value.
[SerializeField]
private string m_UserSelectedRegistryName;
[SerializeField]
private bool m_UserAddingNewScopedRegistry;
public bool isUserAddingNewScopedRegistry
{
get => m_UserAddingNewScopedRegistry;
set => m_UserAddingNewScopedRegistry = value;
}
[SerializeField]
private RegistryInfoDraft m_RegistryInfoDraft = new RegistryInfoDraft();
public RegistryInfoDraft registryInfoDraft => m_RegistryInfoDraft;
public void SelectRegistry(string name)
{
var registry = string.IsNullOrEmpty(name) ? null : scopedRegistries.FirstOrDefault(r => r.name == name);
m_UserSelectedRegistryName = name;
m_RegistryInfoDraft.SetOriginalRegistryInfo(registry);
}
public void SetRegistries(RegistryInfo[] newRegistries)
{
var sanitizedNewRegistries = newRegistries?.Where(r => r != null).ToArray();
var oldSelectionIndex = Math.Max(0, m_Registries.FindIndex(r => r.name == m_UserSelectedRegistryName));
m_Registries.Clear();
if (sanitizedNewRegistries?.Length > 0)
m_Registries.AddRange(sanitizedNewRegistries);
RefreshSelection(oldSelectionIndex);
}
public bool AddRegistry(RegistryInfo registry)
{
if (!IsValidRegistryInfo(registry))
return false;
m_Registries.Add(registry);
if (m_RegistryInfoDraft.original == null && m_RegistryInfoDraft.name == registry.name)
{
m_UserSelectedRegistryName = registry.name;
isUserAddingNewScopedRegistry = false;
m_RegistryInfoDraft.SetOriginalRegistryInfo(registry);
}
return true;
}
public bool UpdateRegistry(string oldName, RegistryInfo newRegistry)
{
if (!IsValidRegistryInfo(newRegistry) || string.IsNullOrEmpty(oldName))
return false;
for (var i = 0; i < m_Registries.Count; i++)
{
var registry = m_Registries[i];
if (registry.name != oldName)
continue;
m_Registries[i] = newRegistry;
if (m_UserSelectedRegistryName == oldName)
m_UserSelectedRegistryName = newRegistry.name;
if (m_RegistryInfoDraft.original?.name == oldName)
m_RegistryInfoDraft.SetOriginalRegistryInfo(newRegistry);
return true;
}
return false;
}
public bool RemoveRegistry(string name)
{
var registryIndex = m_Registries.FindIndex(r => r.name == name);
if (registryIndex >= 0)
{
m_Registries.RemoveAt(registryIndex);
if (m_RegistryInfoDraft.original?.name == name)
RefreshSelection(registryIndex);
return true;
}
return false;
}
private void RefreshSelection(int oldSelectionIndex = 0)
{
if (!string.IsNullOrEmpty(m_UserSelectedRegistryName))
{
var selectedRegistry = scopedRegistries.FirstOrDefault(r => r.name == m_UserSelectedRegistryName);
if (selectedRegistry == null)
{
// We use `m_Registries.Count - 2` because m_Registries always contains the main registry
// and scopedRegistries is always one element less than m_Registries
var newSelectionIndex = Math.Max(0, Math.Min(oldSelectionIndex, m_Registries.Count - 2));
selectedRegistry = scopedRegistries.Skip(newSelectionIndex).FirstOrDefault();
}
m_UserSelectedRegistryName = selectedRegistry?.name ?? string.Empty;
m_RegistryInfoDraft.SetOriginalRegistryInfo(selectedRegistry);
}
else
{
var selectedRegistry = m_UserAddingNewScopedRegistry ? null : scopedRegistries.FirstOrDefault();
m_RegistryInfoDraft.SetOriginalRegistryInfo(selectedRegistry);
}
}
private static bool IsValidRegistryInfo(RegistryInfo info)
{
if (info?.scopes == null)
return false;
return !string.IsNullOrEmpty(info.id?.Trim()) && !string.IsNullOrEmpty(info.name?.Trim())
&& !string.IsNullOrEmpty(info.url?.Trim()) && info.scopes.Any()
&& info.scopes.All(s => !string.IsNullOrEmpty(s.Trim()));
}
void OnEnable()
{
m_RegistryInfoDraft.OnEnable();
if (m_RegistryInfoDraft.original == null && !m_RegistryInfoDraft.hasUnsavedChanges && !isUserAddingNewScopedRegistry)
{
var firstScopedRegistry = scopedRegistries.FirstOrDefault();
if (firstScopedRegistry != null)
m_RegistryInfoDraft.SetOriginalRegistryInfo(firstScopedRegistry);
}
onInitializationFinished.Invoke();
}
public void Save()
{
Save(true);
}
[SerializeField]
private long m_LoadAssets;
public long loadAssets
{
get { return m_LoadAssets == 0 ? (long)PackageLoadBar.AssetsToLoad.Min : m_LoadAssets; }
set
{
if (value != m_LoadAssets)
{
m_LoadAssets = value;
onLoadAssetsChanged?.Invoke(m_LoadAssets);
}
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/ProjectSettings/PackageManagerProjectSettings.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/ProjectSettings/PackageManagerProjectSettings.cs",
"repo_id": "UnityCsReference",
"token_count": 4640
} | 405 |
// Unity 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.CodeAnalysis;
using UnityEditor.Connect;
namespace UnityEditor.PackageManager.UI.Internal
{
internal interface IUnityOAuthProxy : IService
{
void GetAuthorizationCodeAsync(string clientId, Action<UnityOAuth.AuthCodeResponse> callback);
}
[ExcludeFromCodeCoverage]
internal class UnityOAuthProxy : BaseService<IUnityOAuthProxy>, IUnityOAuthProxy
{
public void GetAuthorizationCodeAsync(string clientId, Action<UnityOAuth.AuthCodeResponse> callback)
{
try
{
UnityOAuth.GetAuthorizationCodeAsync(clientId, callback);
}
catch (Exception e)
{
callback?.Invoke(new UnityOAuth.AuthCodeResponse { Exception = e});
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/UnityOAuthProxy.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/UnityOAuthProxy.cs",
"repo_id": "UnityCsReference",
"token_count": 385
} | 406 |
// Unity 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.PackageManager.Requests;
namespace UnityEditor.PackageManager.UI.Internal
{
[Serializable]
internal class UpmRemoveOperation : UpmBaseOperation<RemoveRequest>
{
public override RefreshOptions refreshOptions => RefreshOptions.None;
protected override string operationErrorMessage => string.Format(L10n.Tr("Error removing package: {0}."), packageName);
public void Remove(string packageIdOrName)
{
m_PackageIdOrName = packageIdOrName;
Start();
}
protected override RemoveRequest CreateRequest()
{
return m_ClientProxy.Remove(packageName);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmRemoveOperation.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmRemoveOperation.cs",
"repo_id": "UnityCsReference",
"token_count": 301
} | 407 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal abstract class BaseTabElement : VisualElement, ITabElement
{
protected string m_DisplayName;
public virtual string displayName => m_DisplayName;
protected string m_Id;
public virtual string id => m_Id;
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/Tabs/BaseTabElement.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/Tabs/BaseTabElement.cs",
"repo_id": "UnityCsReference",
"token_count": 163
} | 408 |
// Unity 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 UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class InProgressDropdown : DropdownContent
{
internal const int k_Width = 220;
internal const int k_LineHeight = 32;
private int m_Height;
internal override Vector2 windowSize => new Vector2(k_Width, m_Height);
private class InProgressContainer : VisualElement
{
public Label label { get; private set; }
public Button button { get; private set; }
public InProgressContainer(Action buttonAction)
{
label = new Label();
Add(label);
button = new Button() { text = L10n.Tr("View") };
button.clickable.clicked += buttonAction;
Add(button);
}
}
private InProgressContainer m_DownloadingContainer;
private InProgressContainer downloadingContainer => m_DownloadingContainer ??= new InProgressContainer(ViewDownloading);
private InProgressContainer m_InstallingContainer;
private InProgressContainer installingContainer => m_InstallingContainer ??= new InProgressContainer(ViewInstalling);
private InProgressContainer m_EnablingContainer;
private InProgressContainer enablingContainer => m_EnablingContainer ??= new InProgressContainer(ViewEnabling);
private IResourceLoader m_ResourceLoader;
private IUpmClient m_UpmClient;
private IAssetStoreDownloadManager m_AssetStoreDownloadManager;
private IPackageDatabase m_PackageDatabase;
private IPageManager m_PageManager;
private void ResolveDependencies(IResourceLoader resourceLoader,
IUpmClient upmClient,
IAssetStoreDownloadManager assetStoreDownloadManager,
IPackageDatabase packageDatabase,
IPageManager packageManager)
{
m_ResourceLoader = resourceLoader;
m_UpmClient = upmClient;
m_AssetStoreDownloadManager = assetStoreDownloadManager;
m_PackageDatabase = packageDatabase;
m_PageManager = packageManager;
}
public InProgressDropdown(IResourceLoader resourceLoader,
IUpmClient upmClient,
IAssetStoreDownloadManager assetStoreDownloadManager,
IPackageDatabase packageDatabase,
IPageManager packageManager)
{
ResolveDependencies(resourceLoader, upmClient, assetStoreDownloadManager, packageDatabase, packageManager);
styleSheets.Add(m_ResourceLoader.inProgressDropdownStyleSheet);
m_Height = 0;
Refresh();
}
private bool Refresh()
{
Clear();
var numDownloading = m_AssetStoreDownloadManager.DownloadInProgressCount();
var numBuiltInPackagesInstalling = 0;
var numRegularPackagesInstalling = 0;
foreach (var idOrName in m_UpmClient.packageIdsOrNamesInstalling)
{
var version = m_PackageDatabase.GetPackageByIdOrName(idOrName)?.versions.primary;
if (version == null)
continue;
if (version.HasTag(PackageTag.BuiltIn))
++numBuiltInPackagesInstalling;
else
++numRegularPackagesInstalling;
}
m_Height = 0;
if (AddInProgressContainer(installingContainer, numRegularPackagesInstalling, L10n.Tr("Installing {0}")))
m_Height += k_LineHeight;
if (AddInProgressContainer(enablingContainer, numBuiltInPackagesInstalling, L10n.Tr("Enabling {0}")))
m_Height += k_LineHeight;
if (AddInProgressContainer(downloadingContainer, numDownloading, L10n.Tr("Downloading {0}")))
m_Height += k_LineHeight;
return m_Height != 0;
}
private bool AddInProgressContainer(InProgressContainer container, int numItemsInProgress, string textFormat)
{
if (numItemsInProgress <= 0)
return false;
var numItemsText = string.Format(numItemsInProgress > 1 ? L10n.Tr("{0} items") : L10n.Tr("{0} item"), numItemsInProgress);
container.label.text = string.Format(textFormat, numItemsText);
Add(container);
return true;
}
private void ViewDownloading()
{
ViewPackagesOnPage(m_PageManager.GetPage(MyAssetsPage.k_Id), PackageProgress.Downloading);
}
private void ViewInstalling()
{
ViewPackagesOnPage(m_PageManager.GetPage(InProjectPage.k_Id), PackageProgress.Installing, ~PackageTag.BuiltIn);
}
private void ViewEnabling()
{
ViewPackagesOnPage(m_PageManager.GetPage(BuiltInPage.k_Id), PackageProgress.Installing, PackageTag.BuiltIn);
}
private void ViewPackagesOnPage(IPage page, PackageProgress progress, PackageTag tag = PackageTag.None)
{
var packagesInProgress = m_PackageDatabase.allPackages.Where(p =>
p.progress == progress && (tag == PackageTag.None || p.versions.primary.HasTag(tag))).ToArray();
if (packagesInProgress.Any())
{
m_PageManager.activePage = page;
page.LoadExtraItems(packagesInProgress);
page.SetNewSelection(packagesInProgress.Select(p => new PackageAndVersionIdPair(p.uniqueId)));
}
Close();
}
private void OnPackagesChanged(PackagesChangeArgs args)
{
if (args.progressUpdated.Any() || args.added.Any() || args.removed.Any())
{
if (Refresh())
ShowWithNewWindowSize();
else
Close();
}
}
internal override void OnDropdownShown()
{
// Since OnDropdownShown might be called multiple times, we want to make sure the events are not registered multiple times
m_PackageDatabase.onPackagesChanged -= OnPackagesChanged;
m_PackageDatabase.onPackagesChanged += OnPackagesChanged;
}
internal override void OnDropdownClosed()
{
m_PackageDatabase.onPackagesChanged -= OnPackagesChanged;
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/InProgressDropdown.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/InProgressDropdown.cs",
"repo_id": "UnityCsReference",
"token_count": 3008
} | 409 |
// 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;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class RemoveImportedFoldoutGroup : MultiSelectFoldoutGroup
{
public RemoveImportedFoldoutGroup(IApplicationProxy applicationProxy, IPackageOperationDispatcher operationDispatcher)
: base(new RemoveImportedAction(operationDispatcher, applicationProxy))
{
}
public override void Refresh()
{
mainFoldout.headerTextTemplate = L10n.Tr("Remove imported assets from {0}");
inProgressFoldout.headerTextTemplate = L10n.Tr("Removing imported assets from {0}");
base.Refresh();
}
public override bool AddPackageVersion(IPackageVersion version)
{
return version.importedAssets?.Any() == true && base.AddPackageVersion(version);
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/RemoveImportedFoldoutGroup.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/RemoveImportedFoldoutGroup.cs",
"repo_id": "UnityCsReference",
"token_count": 375
} | 410 |
// 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 System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.PackageManager.UI.Internal
{
internal class PackageDetailsSampleItem
{
private readonly IPackageVersion m_Version;
private Sample m_Sample;
private readonly ISelectionProxy m_Selection;
private readonly IAssetDatabaseProxy m_AssetDatabase;
private readonly IApplicationProxy m_Application;
private readonly IIOProxy m_IOProxy;
public PackageDetailsSampleItem(IPackageVersion version, Sample sample, ISelectionProxy selection, IAssetDatabaseProxy assetDatabase, IApplicationProxy application, IIOProxy iOProxy)
{
m_Selection = selection;
m_AssetDatabase = assetDatabase;
m_Application = application;
m_IOProxy = iOProxy;
m_Version = version;
m_Sample = sample;
nameLabel.text = sample.displayName;
nameLabel.tooltip = sample.displayName; // add tooltip for when the label text is cut off
sizeLabel.text = sample.size;
descriptionLabel.SetValueWithoutNotify(sample.description);
descriptionLabel.multiline = true;
RefreshImportStatus();
importButton.clickable.clicked += OnImportButtonClicked;
}
private void OnImportButtonClicked()
{
var previousImports = m_Sample.previousImports;
var previousImportPaths = previousImports.Aggregate(string.Empty,
(current, next) => current + next.Replace(@"\", "/").Replace(Application.dataPath, "Assets") + "\n");
var warningMessage = string.Empty;
if (previousImports.Count > 1)
{
warningMessage = L10n.Tr("Different versions of the sample are already imported at") + "\n\n"
+ previousImportPaths + "\n" + L10n.Tr("They will be deleted when you update.");
}
else if (previousImports.Count == 1)
{
if (m_Sample.isImported)
{
warningMessage = L10n.Tr("The sample is already imported at") + "\n\n"
+ previousImportPaths + "\n" + L10n.Tr("Importing again will override all changes you have made to it.");
}
else
{
warningMessage = L10n.Tr("A different version of the sample is already imported at") + "\n\n"
+ previousImportPaths + "\n" + L10n.Tr("It will be deleted when you update.");
}
}
if (!string.IsNullOrEmpty(warningMessage) &&
!m_Application.DisplayDialog("importPackageSample",
L10n.Tr("Importing package sample"),
warningMessage + L10n.Tr(" Are you sure you want to continue?"),
L10n.Tr("Yes"), L10n.Tr("No")))
{
return;
}
if (previousImports.Count < 1)
PackageManagerWindowAnalytics.SendEvent("importSample", m_Version.uniqueId);
else
PackageManagerWindowAnalytics.SendEvent("reimportSample", m_Version.uniqueId);
if (m_Sample.Import(Sample.ImportOptions.OverridePreviousImports))
{
RefreshImportStatus();
if (m_Sample.isImported)
{
// Highlight import path
var currentPath = m_IOProxy.CurrentDirectory;
var importRelativePath = m_Sample.importPath.Replace(currentPath + Path.DirectorySeparatorChar, "");
var obj = m_AssetDatabase.LoadMainAssetAtPath(importRelativePath);
m_Selection.activeObject = obj;
EditorGUIUtility.PingObject(obj);
}
}
}
private void RefreshImportStatus()
{
if (m_Sample.isImported)
{
importStatus.AddToClassList("imported");
importButton.text = L10n.Tr("Reimport");
}
else if (m_Sample.previousImports.Count != 0)
{
importStatus.AddToClassList("imported");
importButton.text = L10n.Tr("Update");
}
else
{
importStatus.RemoveFromClassList("imported");
importButton.text = L10n.Tr("Import");
}
}
private Label m_ImportStatus;
internal Label importStatus { get { return m_ImportStatus ??= new Label { classList = { "importStatus" } }; } }
private Label m_NameLabel;
internal Label nameLabel { get { return m_NameLabel ??= new Label { classList = { "nameLabel" } }; } }
private Label m_SizeLabel;
internal Label sizeLabel { get { return m_SizeLabel ??= new Label { classList = { "sizeLabel" } }; } }
private SelectableLabel m_DescriptionLabel;
internal SelectableLabel descriptionLabel { get { return m_DescriptionLabel ??= new SelectableLabel { classList = { "descriptionLabel" } }; } }
private Button m_ImportButton;
internal Button importButton { get { return m_ImportButton ??= new Button { classList = { "importButton" } }; } }
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsSampleItem.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsSampleItem.cs",
"repo_id": "UnityCsReference",
"token_count": 2468
} | 411 |
// Unity 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.PackageManager.UI
{
/// <summary>
/// Package Manager UI Extensions
/// </summary>
public static class PackageManagerExtensions
{
internal static List<IPackageManagerExtension> Extensions { get { return extensions ?? (extensions = new List<IPackageManagerExtension>()); } }
static List<IPackageManagerExtension> extensions;
internal static bool extensionsGUICreated = false;
/// <summary>
/// Registers a new Package Manager UI extension
/// </summary>
/// <param name="extension">A Package Manager UI extension</param>
public static void RegisterExtension(IPackageManagerExtension extension)
{
if (extension == null)
return;
Extensions.Add(extension);
}
/// <summary>
/// Protected call to package manager extension.
/// </summary>
internal static void ExtensionCallback(Action action)
{
try
{
action();
}
catch (Exception exception)
{
Debug.LogError(string.Format(L10n.Tr("[Package Manager Window] Package manager extension failed with error: {0}"), exception));
}
}
}
}
| UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageManagerExtensions.cs/0 | {
"file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageManagerExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 592
} | 412 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.